@inkeep/open-knowledge 0.7.0 → 0.8.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +4 -4
  3. package/dist/cli.mjs +4 -4
  4. package/dist/constants-QwHy5SUR.mjs +2 -0
  5. package/dist/{dist-8f5sZjjU.mjs → dist-BxVp6JIv.mjs} +1 -1
  6. package/dist/{dist-D-D0ROxy.mjs → dist-DFP-WbfQ.mjs} +4 -4
  7. package/dist/index.mjs +1 -1
  8. package/dist/{init-Crl56koT.mjs → init-Bu75oD7o.mjs} +4 -4
  9. package/dist/init-vAxGNlYM.mjs +1 -0
  10. package/dist/{loader-CWTimQxz.mjs → loader-cZTzqIix.mjs} +2 -2
  11. package/dist/loader-pZ2M09-9.mjs +1 -0
  12. package/dist/{preview-CI2t6ZHI.mjs → preview-BD3RlE5k.mjs} +2 -2
  13. package/dist/preview-dZ43AldZ.mjs +1 -0
  14. package/dist/public/assets/{ActivityModeContent-oe_KmZ6Y.js → ActivityModeContent-B6kiEV0Z.js} +1 -1
  15. package/dist/public/assets/{DocumentContext-DbnbvMHR.js → DocumentContext-DQthEgAw.js} +5 -5
  16. package/dist/public/assets/{GraphPanel-D7AmXBQV.js → GraphPanel-DH4KEhpm.js} +1 -1
  17. package/dist/public/assets/{SettingsDialogBody-BpLMuvP2.js → SettingsDialogBody-CkhbuZUC.js} +1 -1
  18. package/dist/public/assets/{SourceEditor-BEQlTn2N.js → SourceEditor-DCfA-0XQ.js} +1 -1
  19. package/dist/public/assets/{config-validation-events-COByjXe4.js → config-validation-events-Bu9fT2I9.js} +1 -1
  20. package/dist/public/assets/{index-Boa7vp1g.js → index-BOcIN5SL.js} +11 -11
  21. package/dist/public/assets/{index-BA5hvX-L.css → index-e9F2K9Wn.css} +1 -1
  22. package/dist/public/assets/{prop-types-Cy-YM1RJ.js → prop-types-DElMwZBx.js} +1 -1
  23. package/dist/public/assets/{target-navigation-intent-Bi7iq3EI.js → target-navigation-intent-De80l_HY.js} +1 -1
  24. package/dist/public/assets/{toggle-group-CaNMUr-8.js → toggle-group-C_ml7tl7.js} +1 -1
  25. package/dist/public/assets/{typing-burst-detector-Cik-Z5me.js → typing-burst-detector-V2hpfMDK.js} +1 -1
  26. package/dist/public/index.html +8 -8
  27. package/dist/{repair-launch-json-DWpeccLv.mjs → repair-launch-json-DQ43_GZT.mjs} +2 -2
  28. package/dist/{repair-mcp-configs-CYHG9O47.mjs → repair-mcp-configs-B6oUFOCk.mjs} +2 -2
  29. package/dist/{src-zdkJjt77.mjs → src-ReEPg7w2.mjs} +2 -2
  30. package/dist/start-BNNVqCuE.mjs +1 -0
  31. package/dist/{start-BqJk2pfE.mjs → start-fETp6kQ-.mjs} +2 -2
  32. package/package.json +1 -1
  33. package/dist/constants-TIaTTdiI.mjs +0 -2
  34. package/dist/init-kWgObjIf.mjs +0 -1
  35. package/dist/loader-Dk7DlcV0.mjs +0 -1
  36. package/dist/preview-q0rtsl75.mjs +0 -1
  37. package/dist/start-BEIQv4Al.mjs +0 -1
@@ -387,7 +387,7 @@ $2`).split(`
387
387
  });
388
388
  <\/script>
389
389
  </div>`}];function previewEmbedFence(e){return["```html preview",e.html,"```"].join(`
390
- `)}const PREVIEW_THEME_TOKENS=[{name:`--chart-1`,light:`oklch(0.62 0.19 259)`,dark:`oklch(0.72 0.14 259)`},{name:`--chart-2`,light:`oklch(0.58 0.14 145)`,dark:`oklch(0.73 0.13 145)`},{name:`--chart-3`,light:`oklch(0.62 0.15 70)`,dark:`oklch(0.77 0.14 70)`},{name:`--chart-4`,light:`oklch(0.55 0.18 290)`,dark:`oklch(0.72 0.16 290)`},{name:`--chart-5`,light:`oklch(0.58 0.21 25)`,dark:`oklch(0.72 0.2 25)`},{name:`--primary`,light:`oklch(0.6321 0.1983 259.59)`,dark:`#69a3ff`},{name:`--primary-foreground`,light:`oklch(0.985 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--background`,light:`oklch(1 0 0)`,dark:`oklch(0.145 0 0)`},{name:`--card`,light:`oklch(1 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--card-foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--muted-foreground`,light:`oklch(0.556 0 0)`,dark:`oklch(0.708 0 0)`},{name:`--border`,light:`oklch(0.922 0 0)`,dark:`oklch(1 0 0 / 10%)`},{name:`--destructive`,light:`oklch(0.577 0.245 27.325)`,dark:`oklch(0.704 0.191 22.216)`},{name:`--radius`,light:`0.625rem`,dark:`0.625rem`}],DEFAULT_SERVER_HOST=`localhost`,ALLOWED_IMAGE_MIME_TYPES=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`],ALLOWED_VIDEO_MIME_TYPES=[`video/mp4`,`video/webm`,`video/ogg`],ALLOWED_AUDIO_MIME_TYPES=[`audio/mpeg`,`audio/wav`,`audio/ogg`],ALLOWED_PDF_MIME_TYPES=[`application/pdf`],IMAGE_EXTENSIONS=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`svg`]),VIDEO_EXTENSIONS=new Set([`mp4`,`webm`,`mov`,`m4v`,`mkv`]),PDF_EXTENSIONS=new Set([`pdf`]),AUDIO_EXTENSIONS=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]),FILE_ATTACHMENT_EXTENSIONS=new Set(`pdf.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),EXECUTABLE_BLOCKLIST_EXTENSIONS=new Set(`exe.bat.cmd.ps1.com.msi.vbs.js.jse.wsf.wsh.hta.sh.command.csh.ksh.bash.zsh.fish.desktop.action.workflow.html.htm.svg.xml.mhtml.svgz.dmg.pkg.mpkg.scpt.applescript.terminal.prefpane.webloc.inetloc.fileloc.jar.appimage.deb.rpm.msix.appx.ipa.apk.pif.scr.lnk.url`.split(`.`)),ASSET_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.apng.heic.heif.tiff.bmp.ico.pdf.mp4.webm.mov.m4v.mkv.avi.flv.wmv.mpeg.mpg.mp3.wav.ogg.m4a.flac.aac.opus.zip.woff.woff2.ttf.otf.eot.docx.xlsx.pptx.csv.txt.rtf.json.toml`.split(`.`)),INLINE_RENDERABLE_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.apng.heic.heif.tiff.bmp.ico.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.json.toml`.split(`.`)),DEFAULT_DEDUP_MODE=`same-dir`,WIKI_EMBED_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),SIDEBAR_IMAGE_EXTENSIONS=[`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`,`webm`,`mov`,`m4v`],SIDEBAR_AUDIO_EXTENSIONS=[`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`],SIDEBAR_PDF_EXTENSIONS=[`pdf`],SIDEBAR_TEXT_EXTENSIONS=[`json`,`toml`];function assertSubset(e,t,S){for(let w of t)if(!S.has(w))throw Error(`${e}: ${w} is not present in canonical upload constants`)}assertSubset(`SIDEBAR_IMAGE_ASSET_EXTENSIONS`,SIDEBAR_IMAGE_EXTENSIONS,IMAGE_EXTENSIONS),assertSubset(`SIDEBAR_VIDEO_ASSET_EXTENSIONS`,SIDEBAR_VIDEO_EXTENSIONS,VIDEO_EXTENSIONS),assertSubset(`SIDEBAR_AUDIO_ASSET_EXTENSIONS`,SIDEBAR_AUDIO_EXTENSIONS,AUDIO_EXTENSIONS),assertSubset(`SIDEBAR_PDF_ASSET_EXTENSIONS`,SIDEBAR_PDF_EXTENSIONS,PDF_EXTENSIONS),assertSubset(`FILE_ATTACHMENT_EXTENSIONS`,[...FILE_ATTACHMENT_EXTENSIONS],WIKI_EMBED_EXTENSIONS);const SIDEBAR_IMAGE_ASSET_EXTENSIONS=new Set(SIDEBAR_IMAGE_EXTENSIONS),SIDEBAR_VIDEO_ASSET_EXTENSIONS=new Set(SIDEBAR_VIDEO_EXTENSIONS),SIDEBAR_AUDIO_ASSET_EXTENSIONS=new Set(SIDEBAR_AUDIO_EXTENSIONS),SIDEBAR_PDF_ASSET_EXTENSIONS=new Set(SIDEBAR_PDF_EXTENSIONS),SIDEBAR_TEXT_ASSET_EXTENSIONS=new Set(SIDEBAR_TEXT_EXTENSIONS),SIDEBAR_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_EXTENSIONS,...SIDEBAR_AUDIO_EXTENSIONS,...SIDEBAR_PDF_EXTENSIONS,...SIDEBAR_TEXT_EXTENSIONS]);assertSubset(`SIDEBAR_RENDERABLE_ASSET_EXTENSIONS`,[...SIDEBAR_RENDERABLE_ASSET_EXTENSIONS],INLINE_RENDERABLE_EXTENSIONS);function mediaKindForSidebarAssetExtension(e){let t=e.toLowerCase().replace(/^\./,``);return SIDEBAR_IMAGE_ASSET_EXTENSIONS.has(t)?`image`:SIDEBAR_VIDEO_ASSET_EXTENSIONS.has(t)?`video`:SIDEBAR_AUDIO_ASSET_EXTENSIONS.has(t)?`audio`:SIDEBAR_PDF_ASSET_EXTENSIONS.has(t)?`pdf`:SIDEBAR_TEXT_ASSET_EXTENSIONS.has(t)?`text`:null}const CodeBlockFidelity=index_default$11.extend({priority:60,addAttributes(){return{...this.parent?.(),fenceDelimiter:{default:"`"},fenceLength:{default:3},meta:{default:null},sourceStyle:{default:`fenced`}}}}),EmphasisFidelity=index_default$9.extend({name:`emphasis`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`*`}}},addInputRules(){return[markInputRule({find:starInputRegex,type:this.type,getAttributes:{sourceDelimiter:`*`}}),markInputRule({find:underscoreInputRegex,type:this.type,getAttributes:{sourceDelimiter:`_`}})]}}),StrongFidelity=index_default$10.extend({name:`strong`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`**`}}},addInputRules(){return[markInputRule({find:starInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`**`}}),markInputRule({find:underscoreInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`__`}})]}}),EscapeMark=Mark.create({name:`escapeMark`,priority:10,excludes:``,inclusive:!1,parseHTML(){return[{tag:`span[data-escape-mark]`}]},renderHTML(){return[`span`,{"data-escape-mark":``},0]}}),HardBreakFidelity=index_default$8.extend({priority:60,addAttributes(){return{...this.parent?.(),hardBreakStyle:{default:`backslash`}}}}),HeadingFidelity=index_default$7.extend({priority:60,addAttributes(){return{...this.parent?.(),headingStyle:{default:`atx`},sourceTrailingHashes:{default:null},sourceUnderlineLength:{default:null},sourceContiguousNext:{default:!1}}}}),HtmlBlockFidelity=Node3.create({name:`htmlBlock`,group:`block`,atom:!0,priority:60,addAttributes(){return{content:{default:``}}},parseHTML(){return[{tag:`div[data-html-block]`}]},renderHTML({node:e}){return[`div`,{"data-html-block":``,class:`html-block`},e.attrs.content]}});function toDesktopAssetHref(e){if(typeof e!=`string`||!e.startsWith(`/`))return e;let t=globalThis.window?.okDesktop?.config?.apiOrigin;return typeof t==`string`&&t?t+e:e}const ImageSrcFidelity=index_default$6.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceUrl:{default:null,rendered:!1}}},renderHTML({HTMLAttributes:e}){let t=mergeAttributes(this.options.HTMLAttributes,e);return typeof t.src==`string`&&(t.src=toDesktopAssetHref(t.src)),[`img`,t]}}),JsxComponent=Node3.create({name:`jsxComponent`,group:`block`,atom:!1,content:`block*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{componentName:{default:``},kind:{default:`element`},attributes:{default:[]},sourceRaw:{default:``},sourceDirty:{default:!1},props:{default:{}}}},parseHTML(){return[{tag:`div[data-jsx-component]`,getAttrs:e=>typeof e==`string`?!1:{componentName:e.getAttribute(`data-component-name`)||``,sourceRaw:e.getAttribute(`data-source-raw`)||``}}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-jsx-component":``,"data-component-name":e.componentName,"data-source-raw":e.sourceRaw},0]},addCommands(){return{insertJsxComponent:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{sourceRaw:e}})}}}),JsxInline=Node3.create({name:`jsxInline`,group:`inline`,inline:!0,atom:!1,content:`text*`,isolating:!1,selectable:!0,priority:60,addAttributes(){return{}},parseHTML(){return[{tag:`span[data-jsx-inline]`}]},renderHTML(){return[`span`,{"data-jsx-inline":``},0]}}),SAFE_URL_SCHEMES=[`https`,`http`,`mailto`,`tel`,`ftp`,`sms`],SCHEME_ALT=SAFE_URL_SCHEMES.map(e=>`${e}:`).join(`|`),SAFE_URL_SCHEME_RE=RegExp(`^(?:${SCHEME_ALT}|\\/|#|\\?|\\.\\/|\\.\\.\\/)`,`i`);function isRelativeUrl(e){let t=e.trim();if(t===``)return!0;let S=t.indexOf(`:`);if(S===-1)return!0;let w=t.indexOf(`/`),E=t.indexOf(`?`),D=t.indexOf(`#`);return S>Math.min(w===-1?1/0:w,E===-1?1/0:E,D===-1?1/0:D)}const ALLOWED_LINK_SCHEMES=new Set(SAFE_URL_SCHEMES.map(e=>`${e}:`)),PLACEHOLDER_BASE=`https://placeholder.invalid`;function isAllowedLinkUri(e){try{let t=new URL(e,PLACEHOLDER_BASE);return ALLOWED_LINK_SCHEMES.has(t.protocol.toLowerCase())}catch{return!1}}const LinkFidelity=index_default$5.extend({priority:60,addOptions(){return{openOnClick:!1,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer`},isAllowedUri:isAllowedLinkUri,validate:isAllowedLinkUri,shouldAutoLink:()=>!0}},addAttributes(){return{...this.parent?.(),linkStyle:{default:`inline`,rendered:!1},refLabel:{default:null,rendered:!1},sourceForm:{default:null,rendered:!1},target:{default:null,rendered:!1},anchor:{default:null,rendered:!1},alias:{default:null,rendered:!1},sourceUrlForm:{default:null,rendered:!1},sourceTitleMarker:{default:null,rendered:!1}}}}),LinkRefDefFidelity=Node3.create({name:`linkRefDef`,group:`block`,atom:!0,priority:60,addAttributes(){return{label:{default:``},href:{default:``},title:{default:null},sourceLayout:{default:null},sourceTitleMarker:{default:null}}},parseHTML(){return[{tag:`div[data-link-ref-def]`}]},renderHTML({node:e}){let{label:t,href:S,title:w}=e.attrs,E=w?`[${t}]: ${S} "${w}"`:`[${t}]: ${S}`;return[`div`,{"data-link-ref-def":``,class:`link-ref-def`},E]}});function isBulletList(e){return e.type.name===`list`&&!e.attrs.ordered}function isOrderedList(e){return e.type.name===`list`&&!!e.attrs.ordered}function hasTaskItems(e){let t=!1;return e.forEach(e=>{e.type.name===`listItem`&&e.attrs.checked!==null&&(t=!0)}),t}function toggleListKind(e,t,S,w,E,D,O){let k=findParentNode(e=>e.type.name===`list`)(e.selection);if(k&&E(k.node)){let{$from:S,$to:E}=e.selection;return S.blockRange(E)?liftListItem$1(w)(e,t):!1}if(k){if(!t)return!0;let{tr:S}=e;return S.setNodeMarkup(k.pos,void 0,{...k.node.attrs,...D}),O!==void 0&&k.node.forEach((e,t)=>{if(e.type.name===`listItem`){let w=k.pos+1+t;S.setNodeMarkup(w,void 0,{...e.attrs,...O})}}),t(S),!0}return wrapInList$1(S,D)(e,void 0)?t?wrapInList$1(S,D)(e,S=>{if(O){let t=S.mapping.map(e.selection.$from.pos),w=S.doc.resolve(t);for(let e=w.depth;e>0;e--){let t=w.node(e);if(t.type.name===`listItem`){S.setNodeMarkup(w.before(e),void 0,{...t.attrs,...O});break}}}t(S)}):!0:!1}const ListNode=Node3.create({name:`list`,group:`block list`,content:`listItem+`,priority:60,addAttributes(){return{ordered:{default:!1},start:{default:1},spread:{default:!1},bulletMarker:{default:null},listMarkerDelimiter:{default:null}}},parseHTML(){return[{tag:`ul`,getAttrs:()=>({ordered:!1})},{tag:`ol`,getAttrs:e=>({ordered:!0,start:e.getAttribute(`start`)?Number(e.getAttribute(`start`)):1})}]},renderHTML({node:e,HTMLAttributes:t}){let S=e.attrs.ordered?`ol`:`ul`,w={};return e.attrs.ordered&&e.attrs.start!==1&&(w.start=e.attrs.start),[S,mergeAttributes(t,w),0]},addCommands(){return{toggleBulletList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&!hasTaskItems(e),{ordered:!1},{checked:null})},toggleOrderedList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isOrderedList(e),{ordered:!0},{checked:null})},toggleTaskList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&hasTaskItems(e),{ordered:!1},{checked:!1})}}},addInputRules(){return[wrappingInputRule({find:/^\s*([-+*])(?!\s*\[[ xX]\])\s$/,type:this.type,getAttributes:e=>({ordered:!1,bulletMarker:e[1]})}),wrappingInputRule({find:/^\s*(\d+)([.)])\s$/,type:this.type,getAttributes:e=>({ordered:!0,start:Number(e[1]),listMarkerDelimiter:e[2]})}),new InputRule({find:/^\s*[-*+]\s\[([ xX])\]\s$/,handler:({state:e,range:t,match:S})=>{let w=e.schema.nodes.list;if(!w)return null;let E=S[1]!==` `,D=e.tr.delete(t.from,t.to),O=D.doc.resolve(t.from).blockRange();if(!O)return null;let k=findWrapping(O,w,{ordered:!1});if(!k)return null;D.wrap(O,k);let j=D.doc.resolve(D.mapping.map(t.from));for(let e=j.depth;e>0;e--){let t=j.node(e);if(t.type.name===`listItem`){D.setNodeMarkup(j.before(e),void 0,{...t.attrs,checked:E});break}}}})]},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList(),"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList(),"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),ListItemNode=Node3.create({name:`listItem`,content:`paragraph block*`,defining:!0,addAttributes(){return{checked:{default:null},spread:{default:!1}}},parseHTML(){return[{tag:`li`,getAttrs:e=>{let t=e.querySelector(`input[type="checkbox"]`);return{checked:t?t.checked:null}}}]},renderHTML({node:e,HTMLAttributes:t}){return e.attrs.checked===null?[`li`,mergeAttributes(t),0]:[`li`,mergeAttributes(t,{"data-type":`taskItem`,"data-checked":e.attrs.checked?`true`:`false`}),[`label`,{contenteditable:`false`},[`input`,{type:`checkbox`,...e.attrs.checked?{checked:`checked`}:{}}]],[`div`,0]]},addNodeView(){return({node:e,getPos:t,editor:S,HTMLAttributes:w})=>{let E=document.createElement(`li`);Object.entries(mergeAttributes(w,e.attrs.checked===null?{}:{"data-type":`taskItem`,"data-checked":String(!!e.attrs.checked)})).forEach(([e,t])=>{t!=null&&E.setAttribute(e,String(t))});let D=null,O=null,k=document.createElement(`div`);return e.attrs.checked!==null&&(D=document.createElement(`label`),D.contentEditable=`false`,O=document.createElement(`input`),O.type=`checkbox`,O.checked=!!e.attrs.checked,S.isEditable||(O.disabled=!0),O.addEventListener(`change`,()=>{let w=t();w===void 0||typeof w!=`number`||S.view.dispatch(S.view.state.tr.setNodeMarkup(w,void 0,{...e.attrs,checked:O?.checked??!1}))}),D.appendChild(O),E.appendChild(D)),E.appendChild(k),{dom:E,contentDOM:k,update(t){return t.type!==e.type||t.attrs.checked!==null!=(e.attrs.checked!==null)?!1:(O&&t.attrs.checked!==null&&(O.checked=!!t.attrs.checked,E.setAttribute(`data-checked`,String(!!t.attrs.checked))),e=t,!0)}}}},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.sinkListItem(this.name);return!1},"Shift-Tab":()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.liftListItem(this.name);return!1}}}}),List=ListNode,ListItem=ListItemNode,MathInline=Node3.create({name:`mathInline`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{formula:{default:``},id:{default:null},language:{default:`latex`}}},parseHTML(){return[{tag:`span[data-math-inline]`,getAttrs:e=>typeof e==`string`?!1:{formula:e.getAttribute(`data-formula`)||``,id:e.getAttribute(`id`)||null,language:e.getAttribute(`data-language`)||`latex`}}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-math-inline":``,"data-formula":e.formula,"data-language":e.language,...e.id?{id:e.id}:{}}]},addCommands(){return{insertMathInline:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{formula:e}})}}}),RawMdxFallback=Node3.create({name:`rawMdxFallback`,group:`block`,atom:!1,content:`text*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{reason:{default:``},originalSpan:{default:{start:0,end:0}}}},parseHTML(){let e=e=>typeof e==`string`?!1:{reason:e.getAttribute(`data-reason`)||``};return[{tag:`div[data-raw-mdx-fallback]`,getAttrs:e},{tag:`pre[data-raw-mdx-fallback]`,getAttrs:e}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-raw-mdx-fallback":``,"data-raw-badge":`raw`,"data-reason":e.reason,contenteditable:`false`,class:`raw-mdx-fallback`},0]},addNodeView(){return({HTMLAttributes:e})=>{let t=document.createElement(`div`);t.setAttribute(`data-raw-mdx-fallback`,``),t.setAttribute(`data-raw-badge`,`raw`),t.setAttribute(`contenteditable`,`false`),t.classList.add(`raw-mdx-fallback`),e.reason&&t.setAttribute(`data-reason`,e.reason);let S=document.createElement(`pre`);return S.classList.add(`raw-mdx-fallback-content`),S.setAttribute(`contenteditable`,`false`),t.appendChild(S),{dom:t,contentDOM:S,ignoreMutation:()=>!0}}}}),BlockquoteFidelity=index_default$3.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$2.extend({excludes:``,addAttributes(){return{...this.parent?.(),sourceFenceChar:{default:"`"},sourceFenceLength:{default:1}}}}),CommentBlock=Node3.create({name:`commentBlock`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}},sourceLayout:{default:`block`,parseHTML:e=>e.getAttribute(`data-source-layout`)===`inline`?`inline`:`block`,renderHTML:e=>e.sourceLayout===`inline`?{"data-source-layout":`inline`}:{}}}},parseHTML(){return[{tag:`aside[data-comment-block]`},{tag:`aside.comment-block`}]},renderHTML({HTMLAttributes:e}){return[`aside`,{"data-comment-block":``,"data-clipboard-omit":`true`,class:`comment-block`,style:`display: none;`,...e},0]},addCommands(){return{setCommentBlock:()=>({commands:e})=>e.wrapIn(this.name),toggleCommentBlock:()=>({commands:e})=>e.toggleWrap(this.name),unsetCommentBlock:()=>({commands:e})=>e.lift(this.name)}}}),CommentMark=Mark.create({name:`comment`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}}}},parseHTML(){return[{tag:`span[data-comment-mark]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-comment-mark":``,"data-clipboard-omit":`true`,class:`comment-mark`,style:`display: none;`,...e},0]},addCommands(){return{setComment:()=>({commands:e})=>e.setMark(this.name),toggleComment:()=>({commands:e})=>e.toggleMark(this.name),unsetComment:()=>({commands:e})=>e.unsetMark(this.name)}}}),FootnoteDefinition=Node3.create({name:`footnoteDefinition`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){let e=e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}};return[{tag:`aside[data-footnote-def]`,getAttrs:e},{tag:`aside.footnote-def`,getAttrs:e}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.identifier??``);return[`aside`,{...t,"data-footnote-def":``,"data-footnote-id":S,id:`fn-${S}`,class:`footnote-def`},[`div`,{class:`footnote-body`},0],[`a`,{href:`#fnref-${S}`,class:`footnote-backref`,contentEditable:`false`,"aria-label":`Back to reference`},`↩`]]},addCommands(){return{insertFootnoteDefinition:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e},content:[{type:`paragraph`}]})}}}),FootnoteReference=Node3.create({name:`footnoteReference`,group:`inline`,inline:!0,atom:!0,selectable:!0,draggable:!1,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){return[{tag:`sup[data-footnote-ref]`,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}}}]},renderHTML({node:e}){let t=String(e.attrs.identifier??``);return[`sup`,{id:`fnref-${t}`,"data-footnote-ref":``,"data-footnote-id":t,class:`footnote-ref`},[`a`,{href:`#fn-${t}`,class:`footnote-ref-link`},`[${t}]`]]},addCommands(){return{insertFootnoteReference:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e}})}}}),ImageReferenceFidelity=Node3.create({name:`imageReference`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{alt:{default:``},label:{default:``},identifier:{default:``},referenceType:{default:`shortcut`}}},parseHTML(){return[{tag:`img[data-image-reference]`}]},renderHTML({node:e}){let{alt:t,label:S,referenceType:w}=e.attrs,E=t||S;return[`img`,{"data-image-reference":``,"data-reference-type":w,"data-label":S,alt:E}]}}),SourceLiteralMark=Mark.create({name:`sourceLiteral`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceRaw:{default:``}}},parseHTML(){return[{tag:`span[data-source-literal]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-source-literal":``,...e},0]}});function isValidSourceLiteralRaw(e,t){if(typeof e!=`string`||typeof t!=`string`||/[\x00-\x1F\x7F]/.test(e))return!1;let S=e.replaceAll(`\xA0`,` `),w=t.replaceAll(`\xA0`,` `);return S===w?!0:stripMarkdownBackslashEscapes(S)===w}function stripMarkdownBackslashEscapes(e){return e.replace(/\\([!-/:-@[-`{-~])/g,`$1`)}const TableFidelity=Table.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceDashCounts:{default:null}}}}),TableCellFidelity=TableCell.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),TableHeaderFidelity=TableHeader.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),Tag=Node3.create({name:`tag`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{value:{default:``}}},parseHTML(){return[{tag:`a[data-tag]`,getAttrs:e=>typeof e==`string`?!1:{value:e.getAttribute(`data-tag`)||``}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.value??``);return[`a`,{...t,"data-tag":S,href:`#tag/${S}`,class:`tag`},`#${S}`]},addCommands(){return{insertTag:e=>({chain:t})=>t().insertContent({type:`tag`,attrs:{value:e}}).run()}}}),THEMATIC_BREAK_INPUT_RE=/^(?:---|—-|___\s|\*\*\*\s)$/;function thematicBreakSourceRawFromMatch(e){let t=String(e[0]??``).replace(/\s+$/,``);return t===`—-`?`---`:t}const ThematicBreakFidelity=index_default$1.extend({name:`thematicBreak`,priority:60,addAttributes(){return{...this.parent?.(),sourceRaw:{default:`---`}}},addInputRules(){return[nodeInputRule({find:THEMATIC_BREAK_INPUT_RE,type:this.type,getAttributes:e=>({sourceRaw:thematicBreakSourceRawFromMatch(e)})})]}});function normalizeNullableString(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function getWikiLinkText(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLink=Node3.create({name:`wikiLink`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolved:{default:!1}}},parseHTML(){return[{tag:`span[data-wiki-link]`,getAttrs:e=>typeof e==`string`?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:e.getAttribute(`data-resolved`)===`true`}},{tag:`a.wiki-link[data-target]`,priority:100,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-target`)??``;return t?{target:t,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:!1}:!1}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=e.attrs.resolved===!0;return[`span`,{...t,"data-wiki-link":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,"data-resolved":D?`true`:`false`},getWikiLinkText({target:S,alias:w,anchor:E})]}});function extensionOf(e){let t=e.split(`/`).pop()??e,S=t.lastIndexOf(`.`);return S<=0||S===t.length-1?``:t.slice(S+1).toLowerCase()}function labelFor(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLinkEmbed=Node3.create({name:`wikiLinkEmbed`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolvedSrc:{default:null,rendered:!1,parseHTML:()=>null}}},parseHTML(){let e=e=>typeof e==`string`||!e.hasAttribute(`data-wiki-embed`)?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`))};return[{tag:`img[data-wiki-embed]`,getAttrs:e,priority:100},{tag:`a[data-wiki-embed]`,getAttrs:e,priority:100}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=normalizeNullableString(e.attrs.resolvedSrc),O=extensionOf(S);if(IMAGE_EXTENSIONS.has(O))return[`img`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,src:D??S,alt:w??S}];let k=D??S;return[`a`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,href:E?`${k}#${E}`:k,target:`_blank`,rel:`noopener noreferrer`},labelFor({target:S,alias:w,anchor:E})]}}),sharedExtensions=[JsxComponent,RawMdxFallback,JsxInline,MathInline,WikiLink,WikiLinkEmbed,Tag,List,ListItem,EmphasisFidelity,StrongFidelity,CodeMarkFidelity,CodeBlockFidelity,BlockquoteFidelity,HeadingFidelity,ThematicBreakFidelity,LinkFidelity,HtmlBlockFidelity,LinkRefDefFidelity,HardBreakFidelity,EscapeMark,SourceLiteralMark,index_default.configure({undoRedo:!1,bulletList:!1,orderedList:!1,listItem:!1,italic:!1,bold:!1,code:!1,codeBlock:!1,heading:!1,horizontalRule:!1,hardBreak:!1,link:!1,blockquote:!1,dropcursor:{color:`color-mix(in oklch, var(--primary) 50%, transparent)`,width:2}}),TableFidelity.configure({resizable:!0}),TableRow,TableHeaderFidelity,TableCellFidelity,ImageSrcFidelity.configure({inline:!0}),ImageReferenceFidelity,index_default$4,CommentMark,CommentBlock,FootnoteReference,FootnoteDefinition],FRONTMATTER_TAG_VALUE_RE=/^[a-zA-Z][\w/-]*$/;function stripLeadingHash(e){return e.startsWith(`#`)?e.slice(1):e}function coerceCandidates(e){return typeof e==`string`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function extractFrontmatterTags(e){if(!e||e.trim()===``)return[];let{map:t}=parseFrontmatterYaml(e);if(!t)return[];let S=coerceCandidates(t.tags),w=[];for(let e of S){let t=stripLeadingHash(e);FRONTMATTER_TAG_VALUE_RE.test(t)?w.push(t):console.warn(`[frontmatter-tags] dropping invalid tag entry: ${JSON.stringify(e)}`)}return w}const safeDocNameField=string$2().refine(e=>!e.includes(`..`)&&!e.startsWith(`/`)&&!e.includes(`\0`)&&!e.includes(`\\`),{message:`docName contains unsafe path characters`}).optional(),agentIdentityFields={agentId:string$2().optional(),agentName:string$2().optional(),colorSeed:string$2().optional(),clientName:string$2().optional(),clientVersion:string$2().optional(),label:string$2().optional()},summaryField=string$2().optional(),URN_UUID_RE=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]);function isValidBranchName(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const refineBranchName=e=>e.refine(isValidBranchName,`invalid branch name`);function isBranchNotFoundGitError(e){if(e==null)return!1;let t=e instanceof Error?e.message:String(e);return/couldn'?t find remote ref|Remote branch .+ not found/i.test(t)}const BranchInfoSharedFields={shareFileExists:boolean$1(),dirtyConflicts:object$1({conflicts:boolean$1(),files:array(string$2().min(1))}).loose(),branchIsLocal:boolean$1()},BranchInfoResponseSchema=discriminatedUnion(`detached`,[object$1({detached:literal(!1),currentBranch:string$2().min(1).nullable(),currentHeadSha:_null(),...BranchInfoSharedFields}).loose(),object$1({detached:literal(!0),currentBranch:_null(),currentHeadSha:string$2().min(1),...BranchInfoSharedFields}).loose()]),CheckoutRequestSchema=object$1({branch:refineBranchName(string$2().min(1)),principalId:string$2().optional()}).loose(),CheckoutFailureReasonSchema=_enum([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`]),CheckoutResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0)}).loose(),object$1({ok:literal(!1),reason:CheckoutFailureReasonSchema,files:array(string$2().min(1)).optional()}).loose()]),ServerInfoSuccessSchema=object$1({serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional(),currentDiskAckSVs:record(string$2().min(1),string$2().min(1)).optional()}).loose(),PrincipalSuccessSchema=object$1({id:string$2().min(1),display_name:string$2().min(1),display_email:string$2(),source:_enum([`git-config`,`synthesized`]),created_at:string$2().min(1)}).loose(),ProblemTypeSchema=_enum(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:no-conflict-tracked.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed`.split(`.`));function assertNeverProblemType(e){throw Error(`Unexpected ProblemType variant: ${JSON.stringify(e)}`)}const ProblemDetailsSchema=object$1({type:ProblemTypeSchema,title:string$2().min(1),status:number$1().int().min(400).max(599),instance:string$2().regex(URN_UUID_RE,`instance must be urn:uuid:<uuid>`).optional(),detail:string$2().optional()}).loose(),UploadRequestSchema=object$1({parentDocName:string$2().min(1),agentId:string$2().min(1).optional(),agentName:string$2().min(1).optional()}).loose(),UploadAssetSuccessSchema=object$1({src:string$2().min(1),path:string$2().min(1).optional(),deduped:boolean$1().optional()}).loose(),LocalOpCloneRequestSchema=object$1({url:string$2().min(1),dir:string$2().min(1),branch:string$2().min(1).refine(isValidBranchName,`invalid branch name`).optional()}).loose(),StreamingProblemEventSchema=object$1({type:literal(`error`),problem:ProblemDetailsSchema}).loose();function reconstructAttrs(e,t){let S=Array.isArray(e.attrs.attributes)?e.attrs.attributes.filter(e=>typeof e==`object`&&!!e&&`type`in e):[],w=e.attrs.props??{},E=new Map,D=new Set;if(t)for(let e of t)e.omitOnDefault===!0&&`defaultValue`in e&&e.defaultValue!==void 0&&E.set(e.name,e.defaultValue),e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&D.add(e.name);for(let[e,t]of Object.entries(w)){let w=S.findIndex(t=>t.type===`mdxJsxAttribute`&&t.name===e);if(E.has(e)&&Object.is(E.get(e),t)){w>=0&&S.splice(w,1);continue}if(D.has(e)&&t===``){w>=0&&S.splice(w,1);continue}let O=propToMdxJsxAttribute(e,t);w>=0?S[w]=O:S.push(O)}return S}function propToMdxJsxAttribute(e,t){if(t===!0)return{type:`mdxJsxAttribute`,name:e,value:null};if(t===!1)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:`false`}};if(t==null)return{type:`mdxJsxAttribute`,name:e,value:null};if(typeof t==`string`)return{type:`mdxJsxAttribute`,name:e,value:t};if(typeof t==`number`)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:JSON.stringify(t)}};if(typeof t==`object`){let S;try{S=JSON.stringify(t)}catch{S=String(t)}return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:S}}}return{type:`mdxJsxAttribute`,name:e,value:String(t)}}function emitMdxJsx(e,t,S,w){return{type:`mdxJsxFlowElement`,name:e,attributes:reconstructAttrs(t,w),children:S.all(t),data:{}}}const LOOM_ID_RE=/^[A-Za-z0-9]{20,}$/,LOOM_TIMESTAMP_RE=/^(?:\d+s?|(?:\d+h)?(?:\d+m)?(?:\d+s)?)$/;function isLoomHost(e){let t=e.toLowerCase();return t===`loom.com`||t===`www.loom.com`}function extractLoomId(e){let t=e.pathname.match(/^\/(?:share|embed)\/([A-Za-z0-9]+)\/?$/);if(!t)return null;let S=t[1]??``;return LOOM_ID_RE.test(S)?S:null}function parseLoomUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isLoomHost(t.hostname))return null;let S=extractLoomId(t);if(!S)return null;let w=t.searchParams.get(`t`);return{id:S,startRaw:w&&w.length>0&&LOOM_TIMESTAMP_RE.test(w)?w:null}}function isLoomUrl(e){return parseLoomUrl(e)!==null}function isVimeoHost(e){let t=e.toLowerCase();return t===`vimeo.com`||t===`www.vimeo.com`||t===`player.vimeo.com`}function isVimeoUrl(e){if(typeof e!=`string`||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol!==`http:`&&t.protocol!==`https:`?!1:isVimeoHost(t.hostname)}const YOUTUBE_VIDEO_ID_RE=/^[A-Za-z0-9_-]{11}$/;function isYouTubeHost(e){let t=e.toLowerCase();return t===`youtube.com`||t===`www.youtube.com`||t===`m.youtube.com`||t===`music.youtube.com`||t===`youtu.be`||t===`youtube-nocookie.com`||t===`www.youtube-nocookie.com`}function parseTimestampToSeconds(e){if(e.length===0)return null;if(/^[0-9]+$/.test(e)){let t=Number.parseInt(e,10);return t>0?t:null}let t=e.match(/^(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s?)?$/);if(!t)return null;let S=t[1]?Number.parseInt(t[1],10):0,w=t[2]?Number.parseInt(t[2],10):0,E=t[3]?Number.parseInt(t[3],10):0,D=S*3600+w*60+E;return D>0?D:null}function extractVideoId(e){if(e.hostname.toLowerCase()===`youtu.be`){let t=e.pathname.replace(/^\//,``).split(`/`)[0]??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}if(e.pathname===`/watch`){let t=e.searchParams.get(`v`)??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}let t=e.pathname.match(/^\/(?:embed|shorts|v)\/([A-Za-z0-9_-]{11})\/?$/);return t?t[1]??null:null}function parseYouTubeUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isYouTubeHost(t.hostname))return null;let S=extractVideoId(t);if(!S)return null;let w=t.searchParams.get(`t`)??t.searchParams.get(`start`)??``;return{id:S,startSeconds:w.length>0?parseTimestampToSeconds(w):null,noCookie:t.hostname.toLowerCase().endsWith(`youtube-nocookie.com`)}}const calloutProps=[{name:`type`,type:`enum`,enumValues:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`],defaultValue:`note`,required:!1,description:`Callout variant`},{name:`title`,type:`string`,required:!1,description:`Optional heading shown above the body`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Lightbulb`)"},{name:`color`,type:`string`,required:!1,advanced:!0,description:"Optional accent color override (hex — e.g. `#F05032`)"},{name:`collapsible`,type:`boolean`,required:!1,defaultValue:!1,advanced:!0,description:"Render as a foldable `<details>` (Obsidian `[!TYPE]+/-`)"},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,description:`When collapsible, start in the open state`},{name:`children`,type:`reactnode`,required:!0,description:`Callout content`}],htmlImgProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Image source URL`,accept:ALLOWED_IMAGE_MIME_TYPES,autoFocus:!0},{name:`alt`,type:`string`,required:!0,description:`Alt text`},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Image width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Image height`},{name:`srcset`,type:`string`,required:!1,advanced:!0,description:`Responsive image candidate set (e.g. "x.png 1x, y.png 2x")`},{name:`sizes`,type:`string`,required:!1,advanced:!0,description:`Responsive image sizes hint paired with srcset`},{name:`loading`,type:`enum`,enumValues:[`eager`,`lazy`],defaultValue:`lazy`,required:!1,advanced:!0,omitOnDefault:!0,description:`Native img loading strategy (defaults to lazy)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`decoding`,type:`enum`,enumValues:[`sync`,`async`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Hint for how the browser should decode the image`},{name:`fetchpriority`,type:`enum`,enumValues:[`high`,`low`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Resource fetch priority hint`},{name:`crossorigin`,type:`enum`,enumValues:[`anonymous`,`use-credentials`],required:!1,advanced:!0,description:`CORS mode for the image fetch`},{name:`referrerpolicy`,type:`string`,required:!1,advanced:!0,description:`Referrer policy for the image fetch (HTML referrerpolicy values)`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],embedProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Embedded page URL (must start with http:// or https://)`,autoFocus:!0},{name:`title`,type:`string`,required:!1,description:`Iframe title (accessible label for screen readers)`},{name:`width`,type:`string`,required:!1,advanced:!0,description:`Embed width as a CSS length (e.g. "100%", "640px")`},{name:`height`,type:`string`,required:!1,advanced:!0,description:`Embed height as a CSS length (e.g. "26rem", "480px")`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],htmlVideoProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Video source URL`,accept:ALLOWED_VIDEO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 video controls (defaults to true)`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`poster`,type:`string`,required:!1,advanced:!0,description:`Poster image URL shown before playback`,accept:ALLOWED_IMAGE_MIME_TYPES,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Video width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Video height`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`,hideWhen:e=>typeof e.src==`string`&&isLoomUrl(e.src)},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`,hideWhen:e=>typeof e.src==`string`&&(parseYouTubeUrl(e.src)!==null||isVimeoUrl(e.src)||isLoomUrl(e.src))}],htmlAudioProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Audio source URL`,accept:ALLOWED_AUDIO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 audio controls (defaults to true)`},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the audio to preload`}],accordionProps=[{name:`title`,type:`string`,required:!0,description:`Accordion heading shown inside the <summary>`},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!1,description:`When true, the accordion renders expanded on initial load`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Rocket`)"},{name:`description`,type:`string`,required:!1,advanced:!0,description:`Optional subtitle rendered below the title inside <summary>`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#advanced-options`)"},{name:`name`,type:`string`,required:!1,advanced:!0,description:`HTML5 <details name=> group — siblings with the same name are mutually exclusive`}],gfmCalloutProps=[calloutProps[0],calloutProps[1],calloutProps[4],calloutProps[5],calloutProps[6]],commonMarkImageProps=[htmlImgProps[0],htmlImgProps[1],htmlImgProps[7]],htmlDetailsAccordionProps=[accordionProps[0],accordionProps[1],accordionProps[4],accordionProps[5]],wikiEmbedImageProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Alt text (Obsidian alias syntax: `![[file.png|alt text]]`)"}],wikiEmbedVideoProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[clip.mp4|title]]`)"}],wikiEmbedAudioProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[song.mp3|title]]`)"}],tabsProps=[{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#install-tabs`)"}],tabProps=[{name:`label`,type:`string`,required:!0,autoFocus:!0,defaultValue:`Tab`,description:`Tab strip label — shown in the clickable pill at the top`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#tab-npm`)"}],mathProps=[{name:`formula`,type:`string`,required:!0,autoFocus:!0,language:`latex`,description:`LaTeX math source (rendered with KaTeX in the browser)`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#eq-pythagoras`)"},{name:`language`,type:`string`,required:!1,advanced:!0,description:"Forward-compat hint for the math source language (default `latex`). Reserved for future MathJax / Typst / AsciiMath substrates."}],dollarMathProps=[mathProps[0]],mathFenceProps=[mathProps[0]],mermaidProps=[{name:`chart`,type:`string`,required:!0,autoFocus:!0,language:`mermaid`,description:`Mermaid chart source (graph / flowchart / sequenceDiagram / class / state / etc.)`}],wikiEmbedFileProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Display name override (Obsidian alias syntax: `![[file.zip|label]]`)"}],fileProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`File URL`,accept:[`*/*`],autoFocus:!0}],pdfProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`PDF source URL`,accept:ALLOWED_PDF_MIME_TYPES,autoFocus:!0},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Accessible label for the embedded PDF viewer`},{name:`anchor`,type:`string`,required:!1,advanced:!0,description:"PDF viewer parameters as a single URL-fragment string (e.g. `page=3&height=600`)"}],mirrorProps=[{name:`src`,type:`string`,required:!0,description:"Path of the source doc, extension-less (e.g. `api-spec`).",autoFocus:!0},{name:`anchor`,type:`string`,required:!0,description:"Id of the `<MirrorSource>` block within the source doc."}],mirrorSourceProps=[{name:`id`,type:`string`,required:!0,description:"Stable id agents and authors use to reference this block from `<Mirror>` elsewhere.",autoFocus:!0},{name:`children`,type:`reactnode`,required:!0,description:`Block content this MirrorSource owns — paragraphs, callouts, code, nested JSX, anything.`}];function escapeHtmlAttr(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function escapeHtmlText(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function serializeWikiEmbed(e){let t=e.attrs.props,S=t?.target??``,w=typeof t?.alias==`string`&&t.alias.length>0?t.alias:null,E=typeof t?.anchor==`string`&&t.anchor.length>0?t.anchor:null,D=w??(E?`${S}#${E}`:S);return{type:`wikiLinkEmbed`,value:D,data:{target:S,anchor:E,alias:w},children:[{type:`text`,value:D}]}}const builtInComponents=[{name:`Callout`,surface:`canonical`,hasChildren:!0,props:calloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`Callout`,description:`Alert / admonition with 15 type variants — 5 GFM (note, tip, important, warning, caution) plus 10 Obsidian-parity (abstract, info, todo, success, question, failure, danger, bug, example, quote)`,searchTerms:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`,`alert`,`admonition`,`callout`],serialize:(e,t)=>emitMdxJsx(`Callout`,e,t,calloutProps)},{name:`img`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlImgProps,icon:`Image`,category:`media`,displayName:`Image`,description:`Image with click-to-zoom and HTML-native attributes`,searchTerms:[`image`,`zoom`,`picture`,`photo`],placeholder:{label:`Add an image`},serialize:(e,t)=>emitMdxJsx(`img`,e,t,htmlImgProps)},{name:`video`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlVideoProps,icon:`SquarePlay`,category:`media`,displayName:`Video`,description:`HTML5 video player with native controls`,searchTerms:[`video`,`media`,`player`,`mp4`,`webm`,`movie`],placeholder:{label:`Add a video`},serialize:(e,t)=>emitMdxJsx(`video`,e,t,htmlVideoProps)},{name:`audio`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlAudioProps,icon:`Volume2`,category:`media`,displayName:`Audio`,description:`HTML5 audio player with native controls`,searchTerms:[`audio`,`sound`,`music`,`mp3`,`podcast`,`player`],placeholder:{label:`Add audio`},serialize:(e,t)=>emitMdxJsx(`audio`,e,t,htmlAudioProps)},{name:`Pdf`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:pdfProps,icon:`FileText`,category:`media`,displayName:`PDF`,description:"Embedded PDF viewer (`#page=N` to open at page N, `#height=N` for viewer height)",searchTerms:[`pdf`,`document`,`embed`,`pdfjs`],placeholder:{label:`Add a PDF`},serialize:(e,t)=>emitMdxJsx(`Pdf`,e,t,pdfProps)},{name:`File`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:fileProps,icon:`Paperclip`,category:`media`,displayName:`File`,description:`Downloadable file attachment — inline row with name + size + download link`,searchTerms:[`file`,`attachment`,`download`,`document`,`zip`,`docx`,`doc`],placeholder:{label:`Add a file`},serialize:(e,t)=>emitMdxJsx(`File`,e,t,fileProps)},{name:`Embed`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:embedProps,icon:`AppWindow`,category:`media`,displayName:`Embed`,description:`Inline web embed (iframe) — drop a URL, get a resizable preview pane`,searchTerms:[`embed`,`iframe`,`website`,`page`,`inline`,`frame`,`preview`],placeholder:{label:`Embed a URL`},serialize:(e,t)=>emitMdxJsx(`Embed`,e,t,embedProps)},{name:`Accordion`,surface:`canonical`,hasChildren:!0,props:accordionProps,icon:`ChevronRight`,category:`content`,displayName:`Accordion`,description:"Standalone expand/collapse via native HTML5 <details>/<summary>. Group siblings with the `name` prop for exclusive-accordion UX.",searchTerms:[`toggle`,`accordion`,`expandable`,`details`,`disclosure`,`collapse`,`fold`],exampleBody:`Body content revealed when the accordion is expanded.`,serialize:(e,t)=>emitMdxJsx(`Accordion`,e,t,accordionProps)},{name:`Tabs`,surface:`canonical`,hasChildren:!0,emptyChildName:`Tab`,props:tabsProps,icon:`LayoutPanelTop`,category:`content`,displayName:`Tabs`,description:"Horizontal tab strip + active panel below. Each `<Tab>` child is one panel; clickable pills at the top switch the active one. Active selection is ephemeral (resets on reload).",searchTerms:[`tabs`,`tabbed`,`panels`,`tabgroup`,`switcher`],exampleBody:`<Tab label="One">Body of the first tab panel.</Tab>
390
+ `)}const PREVIEW_THEME_TOKENS=[{name:`--chart-1`,light:`oklch(0.62 0.19 259)`,dark:`oklch(0.72 0.14 259)`},{name:`--chart-2`,light:`oklch(0.58 0.14 145)`,dark:`oklch(0.73 0.13 145)`},{name:`--chart-3`,light:`oklch(0.62 0.15 70)`,dark:`oklch(0.77 0.14 70)`},{name:`--chart-4`,light:`oklch(0.55 0.18 290)`,dark:`oklch(0.72 0.16 290)`},{name:`--chart-5`,light:`oklch(0.58 0.21 25)`,dark:`oklch(0.72 0.2 25)`},{name:`--primary`,light:`oklch(0.6321 0.1983 259.59)`,dark:`#69a3ff`},{name:`--primary-foreground`,light:`oklch(0.985 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--background`,light:`oklch(1 0 0)`,dark:`oklch(0.145 0 0)`},{name:`--card`,light:`oklch(1 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--card-foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--muted-foreground`,light:`oklch(0.556 0 0)`,dark:`oklch(0.708 0 0)`},{name:`--border`,light:`oklch(0.922 0 0)`,dark:`oklch(1 0 0 / 10%)`},{name:`--destructive`,light:`oklch(0.577 0.245 27.325)`,dark:`oklch(0.704 0.191 22.216)`},{name:`--radius`,light:`0.625rem`,dark:`0.625rem`}],DEFAULT_SERVER_HOST=`localhost`,ALLOWED_IMAGE_MIME_TYPES=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`],ALLOWED_VIDEO_MIME_TYPES=[`video/mp4`,`video/webm`,`video/ogg`],ALLOWED_AUDIO_MIME_TYPES=[`audio/mpeg`,`audio/wav`,`audio/ogg`],ALLOWED_PDF_MIME_TYPES=[`application/pdf`],IMAGE_EXTENSIONS=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`svg`]),VIDEO_EXTENSIONS=new Set([`mp4`,`webm`,`mov`,`m4v`,`mkv`]),PDF_EXTENSIONS=new Set([`pdf`]),AUDIO_EXTENSIONS=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]),FILE_ATTACHMENT_EXTENSIONS=new Set(`pdf.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),EXECUTABLE_BLOCKLIST_EXTENSIONS=new Set(`exe.bat.cmd.ps1.com.msi.vbs.js.jse.wsf.wsh.hta.sh.command.csh.ksh.bash.zsh.fish.desktop.action.workflow.html.htm.svg.xml.mhtml.svgz.dmg.pkg.mpkg.scpt.applescript.terminal.prefpane.webloc.inetloc.fileloc.jar.appimage.deb.rpm.msix.appx.ipa.apk.pif.scr.lnk.url`.split(`.`)),ASSET_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.apng.heic.heif.tiff.bmp.ico.pdf.mp4.webm.mov.m4v.mkv.avi.flv.wmv.mpeg.mpg.mp3.wav.ogg.m4a.flac.aac.opus.zip.woff.woff2.ttf.otf.eot.docx.xlsx.pptx.csv.txt.rtf.json.toml.lock`.split(`.`)),INLINE_RENDERABLE_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.apng.heic.heif.tiff.bmp.ico.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.json.toml.lock`.split(`.`)),DEFAULT_DEDUP_MODE=`same-dir`,WIKI_EMBED_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),SIDEBAR_IMAGE_EXTENSIONS=[`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`,`webm`,`mov`,`m4v`],SIDEBAR_AUDIO_EXTENSIONS=[`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`],SIDEBAR_PDF_EXTENSIONS=[`pdf`],SIDEBAR_TEXT_EXTENSIONS=[`json`,`toml`,`lock`];function assertSubset(e,t,S){for(let w of t)if(!S.has(w))throw Error(`${e}: ${w} is not present in canonical upload constants`)}assertSubset(`SIDEBAR_IMAGE_ASSET_EXTENSIONS`,SIDEBAR_IMAGE_EXTENSIONS,IMAGE_EXTENSIONS),assertSubset(`SIDEBAR_VIDEO_ASSET_EXTENSIONS`,SIDEBAR_VIDEO_EXTENSIONS,VIDEO_EXTENSIONS),assertSubset(`SIDEBAR_AUDIO_ASSET_EXTENSIONS`,SIDEBAR_AUDIO_EXTENSIONS,AUDIO_EXTENSIONS),assertSubset(`SIDEBAR_PDF_ASSET_EXTENSIONS`,SIDEBAR_PDF_EXTENSIONS,PDF_EXTENSIONS),assertSubset(`FILE_ATTACHMENT_EXTENSIONS`,[...FILE_ATTACHMENT_EXTENSIONS],WIKI_EMBED_EXTENSIONS);const SIDEBAR_IMAGE_ASSET_EXTENSIONS=new Set(SIDEBAR_IMAGE_EXTENSIONS),SIDEBAR_VIDEO_ASSET_EXTENSIONS=new Set(SIDEBAR_VIDEO_EXTENSIONS),SIDEBAR_AUDIO_ASSET_EXTENSIONS=new Set(SIDEBAR_AUDIO_EXTENSIONS),SIDEBAR_PDF_ASSET_EXTENSIONS=new Set(SIDEBAR_PDF_EXTENSIONS),SIDEBAR_TEXT_ASSET_EXTENSIONS=new Set(SIDEBAR_TEXT_EXTENSIONS),SIDEBAR_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_EXTENSIONS,...SIDEBAR_AUDIO_EXTENSIONS,...SIDEBAR_PDF_EXTENSIONS,...SIDEBAR_TEXT_EXTENSIONS]);assertSubset(`SIDEBAR_RENDERABLE_ASSET_EXTENSIONS`,[...SIDEBAR_RENDERABLE_ASSET_EXTENSIONS],INLINE_RENDERABLE_EXTENSIONS);function mediaKindForSidebarAssetExtension(e){let t=e.toLowerCase().replace(/^\./,``);return SIDEBAR_IMAGE_ASSET_EXTENSIONS.has(t)?`image`:SIDEBAR_VIDEO_ASSET_EXTENSIONS.has(t)?`video`:SIDEBAR_AUDIO_ASSET_EXTENSIONS.has(t)?`audio`:SIDEBAR_PDF_ASSET_EXTENSIONS.has(t)?`pdf`:SIDEBAR_TEXT_ASSET_EXTENSIONS.has(t)?`text`:null}const CodeBlockFidelity=index_default$11.extend({priority:60,addAttributes(){return{...this.parent?.(),fenceDelimiter:{default:"`"},fenceLength:{default:3},meta:{default:null},sourceStyle:{default:`fenced`}}}}),EmphasisFidelity=index_default$9.extend({name:`emphasis`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`*`}}},addInputRules(){return[markInputRule({find:starInputRegex,type:this.type,getAttributes:{sourceDelimiter:`*`}}),markInputRule({find:underscoreInputRegex,type:this.type,getAttributes:{sourceDelimiter:`_`}})]}}),StrongFidelity=index_default$10.extend({name:`strong`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`**`}}},addInputRules(){return[markInputRule({find:starInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`**`}}),markInputRule({find:underscoreInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`__`}})]}}),EscapeMark=Mark.create({name:`escapeMark`,priority:10,excludes:``,inclusive:!1,parseHTML(){return[{tag:`span[data-escape-mark]`}]},renderHTML(){return[`span`,{"data-escape-mark":``},0]}}),HardBreakFidelity=index_default$8.extend({priority:60,addAttributes(){return{...this.parent?.(),hardBreakStyle:{default:`backslash`}}}}),HeadingFidelity=index_default$7.extend({priority:60,addAttributes(){return{...this.parent?.(),headingStyle:{default:`atx`},sourceTrailingHashes:{default:null},sourceUnderlineLength:{default:null},sourceContiguousNext:{default:!1}}}}),HtmlBlockFidelity=Node3.create({name:`htmlBlock`,group:`block`,atom:!0,priority:60,addAttributes(){return{content:{default:``}}},parseHTML(){return[{tag:`div[data-html-block]`}]},renderHTML({node:e}){return[`div`,{"data-html-block":``,class:`html-block`},e.attrs.content]}});function toDesktopAssetHref(e){if(typeof e!=`string`||!e.startsWith(`/`))return e;let t=globalThis.window?.okDesktop?.config?.apiOrigin;return typeof t==`string`&&t?t+e:e}const ImageSrcFidelity=index_default$6.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceUrl:{default:null,rendered:!1}}},renderHTML({HTMLAttributes:e}){let t=mergeAttributes(this.options.HTMLAttributes,e);return typeof t.src==`string`&&(t.src=toDesktopAssetHref(t.src)),[`img`,t]}}),JsxComponent=Node3.create({name:`jsxComponent`,group:`block`,atom:!1,content:`block*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{componentName:{default:``},kind:{default:`element`},attributes:{default:[]},sourceRaw:{default:``},sourceDirty:{default:!1},props:{default:{}}}},parseHTML(){return[{tag:`div[data-jsx-component]`,getAttrs:e=>typeof e==`string`?!1:{componentName:e.getAttribute(`data-component-name`)||``,sourceRaw:e.getAttribute(`data-source-raw`)||``}}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-jsx-component":``,"data-component-name":e.componentName,"data-source-raw":e.sourceRaw},0]},addCommands(){return{insertJsxComponent:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{sourceRaw:e}})}}}),JsxInline=Node3.create({name:`jsxInline`,group:`inline`,inline:!0,atom:!1,content:`text*`,isolating:!1,selectable:!0,priority:60,addAttributes(){return{}},parseHTML(){return[{tag:`span[data-jsx-inline]`}]},renderHTML(){return[`span`,{"data-jsx-inline":``},0]}}),SAFE_URL_SCHEMES=[`https`,`http`,`mailto`,`tel`,`ftp`,`sms`],SCHEME_ALT=SAFE_URL_SCHEMES.map(e=>`${e}:`).join(`|`),SAFE_URL_SCHEME_RE=RegExp(`^(?:${SCHEME_ALT}|\\/|#|\\?|\\.\\/|\\.\\.\\/)`,`i`);function isRelativeUrl(e){let t=e.trim();if(t===``)return!0;let S=t.indexOf(`:`);if(S===-1)return!0;let w=t.indexOf(`/`),E=t.indexOf(`?`),D=t.indexOf(`#`);return S>Math.min(w===-1?1/0:w,E===-1?1/0:E,D===-1?1/0:D)}const ALLOWED_LINK_SCHEMES=new Set(SAFE_URL_SCHEMES.map(e=>`${e}:`)),PLACEHOLDER_BASE=`https://placeholder.invalid`;function isAllowedLinkUri(e){try{let t=new URL(e,PLACEHOLDER_BASE);return ALLOWED_LINK_SCHEMES.has(t.protocol.toLowerCase())}catch{return!1}}const LinkFidelity=index_default$5.extend({priority:60,addOptions(){return{openOnClick:!1,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer`},isAllowedUri:isAllowedLinkUri,validate:isAllowedLinkUri,shouldAutoLink:()=>!0}},addAttributes(){return{...this.parent?.(),linkStyle:{default:`inline`,rendered:!1},refLabel:{default:null,rendered:!1},sourceForm:{default:null,rendered:!1},target:{default:null,rendered:!1},anchor:{default:null,rendered:!1},alias:{default:null,rendered:!1},sourceUrlForm:{default:null,rendered:!1},sourceTitleMarker:{default:null,rendered:!1}}}}),LinkRefDefFidelity=Node3.create({name:`linkRefDef`,group:`block`,atom:!0,priority:60,addAttributes(){return{label:{default:``},href:{default:``},title:{default:null},sourceLayout:{default:null},sourceTitleMarker:{default:null}}},parseHTML(){return[{tag:`div[data-link-ref-def]`}]},renderHTML({node:e}){let{label:t,href:S,title:w}=e.attrs,E=w?`[${t}]: ${S} "${w}"`:`[${t}]: ${S}`;return[`div`,{"data-link-ref-def":``,class:`link-ref-def`},E]}});function isBulletList(e){return e.type.name===`list`&&!e.attrs.ordered}function isOrderedList(e){return e.type.name===`list`&&!!e.attrs.ordered}function hasTaskItems(e){let t=!1;return e.forEach(e=>{e.type.name===`listItem`&&e.attrs.checked!==null&&(t=!0)}),t}function toggleListKind(e,t,S,w,E,D,O){let k=findParentNode(e=>e.type.name===`list`)(e.selection);if(k&&E(k.node)){let{$from:S,$to:E}=e.selection;return S.blockRange(E)?liftListItem$1(w)(e,t):!1}if(k){if(!t)return!0;let{tr:S}=e;return S.setNodeMarkup(k.pos,void 0,{...k.node.attrs,...D}),O!==void 0&&k.node.forEach((e,t)=>{if(e.type.name===`listItem`){let w=k.pos+1+t;S.setNodeMarkup(w,void 0,{...e.attrs,...O})}}),t(S),!0}return wrapInList$1(S,D)(e,void 0)?t?wrapInList$1(S,D)(e,S=>{if(O){let t=S.mapping.map(e.selection.$from.pos),w=S.doc.resolve(t);for(let e=w.depth;e>0;e--){let t=w.node(e);if(t.type.name===`listItem`){S.setNodeMarkup(w.before(e),void 0,{...t.attrs,...O});break}}}t(S)}):!0:!1}const ListNode=Node3.create({name:`list`,group:`block list`,content:`listItem+`,priority:60,addAttributes(){return{ordered:{default:!1},start:{default:1},spread:{default:!1},bulletMarker:{default:null},listMarkerDelimiter:{default:null}}},parseHTML(){return[{tag:`ul`,getAttrs:()=>({ordered:!1})},{tag:`ol`,getAttrs:e=>({ordered:!0,start:e.getAttribute(`start`)?Number(e.getAttribute(`start`)):1})}]},renderHTML({node:e,HTMLAttributes:t}){let S=e.attrs.ordered?`ol`:`ul`,w={};return e.attrs.ordered&&e.attrs.start!==1&&(w.start=e.attrs.start),[S,mergeAttributes(t,w),0]},addCommands(){return{toggleBulletList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&!hasTaskItems(e),{ordered:!1},{checked:null})},toggleOrderedList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isOrderedList(e),{ordered:!0},{checked:null})},toggleTaskList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&hasTaskItems(e),{ordered:!1},{checked:!1})}}},addInputRules(){return[wrappingInputRule({find:/^\s*([-+*])(?!\s*\[[ xX]\])\s$/,type:this.type,getAttributes:e=>({ordered:!1,bulletMarker:e[1]})}),wrappingInputRule({find:/^\s*(\d+)([.)])\s$/,type:this.type,getAttributes:e=>({ordered:!0,start:Number(e[1]),listMarkerDelimiter:e[2]})}),new InputRule({find:/^\s*[-*+]\s\[([ xX])\]\s$/,handler:({state:e,range:t,match:S})=>{let w=e.schema.nodes.list;if(!w)return null;let E=S[1]!==` `,D=e.tr.delete(t.from,t.to),O=D.doc.resolve(t.from).blockRange();if(!O)return null;let k=findWrapping(O,w,{ordered:!1});if(!k)return null;D.wrap(O,k);let j=D.doc.resolve(D.mapping.map(t.from));for(let e=j.depth;e>0;e--){let t=j.node(e);if(t.type.name===`listItem`){D.setNodeMarkup(j.before(e),void 0,{...t.attrs,checked:E});break}}}})]},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList(),"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList(),"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),ListItemNode=Node3.create({name:`listItem`,content:`paragraph block*`,defining:!0,addAttributes(){return{checked:{default:null},spread:{default:!1}}},parseHTML(){return[{tag:`li`,getAttrs:e=>{let t=e.querySelector(`input[type="checkbox"]`);return{checked:t?t.checked:null}}}]},renderHTML({node:e,HTMLAttributes:t}){return e.attrs.checked===null?[`li`,mergeAttributes(t),0]:[`li`,mergeAttributes(t,{"data-type":`taskItem`,"data-checked":e.attrs.checked?`true`:`false`}),[`label`,{contenteditable:`false`},[`input`,{type:`checkbox`,...e.attrs.checked?{checked:`checked`}:{}}]],[`div`,0]]},addNodeView(){return({node:e,getPos:t,editor:S,HTMLAttributes:w})=>{let E=document.createElement(`li`);Object.entries(mergeAttributes(w,e.attrs.checked===null?{}:{"data-type":`taskItem`,"data-checked":String(!!e.attrs.checked)})).forEach(([e,t])=>{t!=null&&E.setAttribute(e,String(t))});let D=null,O=null,k=document.createElement(`div`);return e.attrs.checked!==null&&(D=document.createElement(`label`),D.contentEditable=`false`,O=document.createElement(`input`),O.type=`checkbox`,O.checked=!!e.attrs.checked,S.isEditable||(O.disabled=!0),O.addEventListener(`change`,()=>{let w=t();w===void 0||typeof w!=`number`||S.view.dispatch(S.view.state.tr.setNodeMarkup(w,void 0,{...e.attrs,checked:O?.checked??!1}))}),D.appendChild(O),E.appendChild(D)),E.appendChild(k),{dom:E,contentDOM:k,update(t){return t.type!==e.type||t.attrs.checked!==null!=(e.attrs.checked!==null)?!1:(O&&t.attrs.checked!==null&&(O.checked=!!t.attrs.checked,E.setAttribute(`data-checked`,String(!!t.attrs.checked))),e=t,!0)}}}},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.sinkListItem(this.name);return!1},"Shift-Tab":()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.liftListItem(this.name);return!1}}}}),List=ListNode,ListItem=ListItemNode,MathInline=Node3.create({name:`mathInline`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{formula:{default:``},id:{default:null},language:{default:`latex`}}},parseHTML(){return[{tag:`span[data-math-inline]`,getAttrs:e=>typeof e==`string`?!1:{formula:e.getAttribute(`data-formula`)||``,id:e.getAttribute(`id`)||null,language:e.getAttribute(`data-language`)||`latex`}}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-math-inline":``,"data-formula":e.formula,"data-language":e.language,...e.id?{id:e.id}:{}}]},addCommands(){return{insertMathInline:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{formula:e}})}}}),RawMdxFallback=Node3.create({name:`rawMdxFallback`,group:`block`,atom:!1,content:`text*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{reason:{default:``},originalSpan:{default:{start:0,end:0}}}},parseHTML(){let e=e=>typeof e==`string`?!1:{reason:e.getAttribute(`data-reason`)||``};return[{tag:`div[data-raw-mdx-fallback]`,getAttrs:e},{tag:`pre[data-raw-mdx-fallback]`,getAttrs:e}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-raw-mdx-fallback":``,"data-raw-badge":`raw`,"data-reason":e.reason,contenteditable:`false`,class:`raw-mdx-fallback`},0]},addNodeView(){return({HTMLAttributes:e})=>{let t=document.createElement(`div`);t.setAttribute(`data-raw-mdx-fallback`,``),t.setAttribute(`data-raw-badge`,`raw`),t.setAttribute(`contenteditable`,`false`),t.classList.add(`raw-mdx-fallback`),e.reason&&t.setAttribute(`data-reason`,e.reason);let S=document.createElement(`pre`);return S.classList.add(`raw-mdx-fallback-content`),S.setAttribute(`contenteditable`,`false`),t.appendChild(S),{dom:t,contentDOM:S,ignoreMutation:()=>!0}}}}),BlockquoteFidelity=index_default$3.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$2.extend({excludes:``,addAttributes(){return{...this.parent?.(),sourceFenceChar:{default:"`"},sourceFenceLength:{default:1}}}}),CommentBlock=Node3.create({name:`commentBlock`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}},sourceLayout:{default:`block`,parseHTML:e=>e.getAttribute(`data-source-layout`)===`inline`?`inline`:`block`,renderHTML:e=>e.sourceLayout===`inline`?{"data-source-layout":`inline`}:{}}}},parseHTML(){return[{tag:`aside[data-comment-block]`},{tag:`aside.comment-block`}]},renderHTML({HTMLAttributes:e}){return[`aside`,{"data-comment-block":``,"data-clipboard-omit":`true`,class:`comment-block`,style:`display: none;`,...e},0]},addCommands(){return{setCommentBlock:()=>({commands:e})=>e.wrapIn(this.name),toggleCommentBlock:()=>({commands:e})=>e.toggleWrap(this.name),unsetCommentBlock:()=>({commands:e})=>e.lift(this.name)}}}),CommentMark=Mark.create({name:`comment`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}}}},parseHTML(){return[{tag:`span[data-comment-mark]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-comment-mark":``,"data-clipboard-omit":`true`,class:`comment-mark`,style:`display: none;`,...e},0]},addCommands(){return{setComment:()=>({commands:e})=>e.setMark(this.name),toggleComment:()=>({commands:e})=>e.toggleMark(this.name),unsetComment:()=>({commands:e})=>e.unsetMark(this.name)}}}),FootnoteDefinition=Node3.create({name:`footnoteDefinition`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){let e=e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}};return[{tag:`aside[data-footnote-def]`,getAttrs:e},{tag:`aside.footnote-def`,getAttrs:e}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.identifier??``);return[`aside`,{...t,"data-footnote-def":``,"data-footnote-id":S,id:`fn-${S}`,class:`footnote-def`},[`div`,{class:`footnote-body`},0],[`a`,{href:`#fnref-${S}`,class:`footnote-backref`,contentEditable:`false`,"aria-label":`Back to reference`},`↩`]]},addCommands(){return{insertFootnoteDefinition:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e},content:[{type:`paragraph`}]})}}}),FootnoteReference=Node3.create({name:`footnoteReference`,group:`inline`,inline:!0,atom:!0,selectable:!0,draggable:!1,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){return[{tag:`sup[data-footnote-ref]`,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}}}]},renderHTML({node:e}){let t=String(e.attrs.identifier??``);return[`sup`,{id:`fnref-${t}`,"data-footnote-ref":``,"data-footnote-id":t,class:`footnote-ref`},[`a`,{href:`#fn-${t}`,class:`footnote-ref-link`},`[${t}]`]]},addCommands(){return{insertFootnoteReference:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e}})}}}),ImageReferenceFidelity=Node3.create({name:`imageReference`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{alt:{default:``},label:{default:``},identifier:{default:``},referenceType:{default:`shortcut`}}},parseHTML(){return[{tag:`img[data-image-reference]`}]},renderHTML({node:e}){let{alt:t,label:S,referenceType:w}=e.attrs,E=t||S;return[`img`,{"data-image-reference":``,"data-reference-type":w,"data-label":S,alt:E}]}}),SourceLiteralMark=Mark.create({name:`sourceLiteral`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceRaw:{default:``}}},parseHTML(){return[{tag:`span[data-source-literal]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-source-literal":``,...e},0]}});function isValidSourceLiteralRaw(e,t){if(typeof e!=`string`||typeof t!=`string`||/[\x00-\x1F\x7F]/.test(e))return!1;let S=e.replaceAll(`\xA0`,` `),w=t.replaceAll(`\xA0`,` `);return S===w?!0:stripMarkdownBackslashEscapes(S)===w}function stripMarkdownBackslashEscapes(e){return e.replace(/\\([!-/:-@[-`{-~])/g,`$1`)}const TableFidelity=Table.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceDashCounts:{default:null}}}}),TableCellFidelity=TableCell.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),TableHeaderFidelity=TableHeader.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),Tag=Node3.create({name:`tag`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{value:{default:``}}},parseHTML(){return[{tag:`a[data-tag]`,getAttrs:e=>typeof e==`string`?!1:{value:e.getAttribute(`data-tag`)||``}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.value??``);return[`a`,{...t,"data-tag":S,href:`#tag/${S}`,class:`tag`},`#${S}`]},addCommands(){return{insertTag:e=>({chain:t})=>t().insertContent({type:`tag`,attrs:{value:e}}).run()}}}),THEMATIC_BREAK_INPUT_RE=/^(?:---|—-|___\s|\*\*\*\s)$/;function thematicBreakSourceRawFromMatch(e){let t=String(e[0]??``).replace(/\s+$/,``);return t===`—-`?`---`:t}const ThematicBreakFidelity=index_default$1.extend({name:`thematicBreak`,priority:60,addAttributes(){return{...this.parent?.(),sourceRaw:{default:`---`}}},addInputRules(){return[nodeInputRule({find:THEMATIC_BREAK_INPUT_RE,type:this.type,getAttributes:e=>({sourceRaw:thematicBreakSourceRawFromMatch(e)})})]}});function normalizeNullableString(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function getWikiLinkText(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLink=Node3.create({name:`wikiLink`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolved:{default:!1}}},parseHTML(){return[{tag:`span[data-wiki-link]`,getAttrs:e=>typeof e==`string`?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:e.getAttribute(`data-resolved`)===`true`}},{tag:`a.wiki-link[data-target]`,priority:100,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-target`)??``;return t?{target:t,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:!1}:!1}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=e.attrs.resolved===!0;return[`span`,{...t,"data-wiki-link":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,"data-resolved":D?`true`:`false`},getWikiLinkText({target:S,alias:w,anchor:E})]}});function extensionOf(e){let t=e.split(`/`).pop()??e,S=t.lastIndexOf(`.`);return S<=0||S===t.length-1?``:t.slice(S+1).toLowerCase()}function labelFor(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLinkEmbed=Node3.create({name:`wikiLinkEmbed`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolvedSrc:{default:null,rendered:!1,parseHTML:()=>null}}},parseHTML(){let e=e=>typeof e==`string`||!e.hasAttribute(`data-wiki-embed`)?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`))};return[{tag:`img[data-wiki-embed]`,getAttrs:e,priority:100},{tag:`a[data-wiki-embed]`,getAttrs:e,priority:100}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=normalizeNullableString(e.attrs.resolvedSrc),O=extensionOf(S);if(IMAGE_EXTENSIONS.has(O))return[`img`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,src:D??S,alt:w??S}];let k=D??S;return[`a`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,href:E?`${k}#${E}`:k,target:`_blank`,rel:`noopener noreferrer`},labelFor({target:S,alias:w,anchor:E})]}}),sharedExtensions=[JsxComponent,RawMdxFallback,JsxInline,MathInline,WikiLink,WikiLinkEmbed,Tag,List,ListItem,EmphasisFidelity,StrongFidelity,CodeMarkFidelity,CodeBlockFidelity,BlockquoteFidelity,HeadingFidelity,ThematicBreakFidelity,LinkFidelity,HtmlBlockFidelity,LinkRefDefFidelity,HardBreakFidelity,EscapeMark,SourceLiteralMark,index_default.configure({undoRedo:!1,bulletList:!1,orderedList:!1,listItem:!1,italic:!1,bold:!1,code:!1,codeBlock:!1,heading:!1,horizontalRule:!1,hardBreak:!1,link:!1,blockquote:!1,dropcursor:{color:`color-mix(in oklch, var(--primary) 50%, transparent)`,width:2}}),TableFidelity.configure({resizable:!0}),TableRow,TableHeaderFidelity,TableCellFidelity,ImageSrcFidelity.configure({inline:!0}),ImageReferenceFidelity,index_default$4,CommentMark,CommentBlock,FootnoteReference,FootnoteDefinition],FRONTMATTER_TAG_VALUE_RE=/^[a-zA-Z][\w/-]*$/;function stripLeadingHash(e){return e.startsWith(`#`)?e.slice(1):e}function coerceCandidates(e){return typeof e==`string`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function extractFrontmatterTags(e){if(!e||e.trim()===``)return[];let{map:t}=parseFrontmatterYaml(e);if(!t)return[];let S=coerceCandidates(t.tags),w=[];for(let e of S){let t=stripLeadingHash(e);FRONTMATTER_TAG_VALUE_RE.test(t)?w.push(t):console.warn(`[frontmatter-tags] dropping invalid tag entry: ${JSON.stringify(e)}`)}return w}const safeDocNameField=string$2().refine(e=>!e.includes(`..`)&&!e.startsWith(`/`)&&!e.includes(`\0`)&&!e.includes(`\\`),{message:`docName contains unsafe path characters`}).optional(),agentIdentityFields={agentId:string$2().optional(),agentName:string$2().optional(),colorSeed:string$2().optional(),clientName:string$2().optional(),clientVersion:string$2().optional(),label:string$2().optional()},summaryField=string$2().optional(),URN_UUID_RE=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]);function isValidBranchName(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const refineBranchName=e=>e.refine(isValidBranchName,`invalid branch name`);function isBranchNotFoundGitError(e){if(e==null)return!1;let t=e instanceof Error?e.message:String(e);return/couldn'?t find remote ref|Remote branch .+ not found/i.test(t)}const BranchInfoSharedFields={shareFileExists:boolean$1(),dirtyConflicts:object$1({conflicts:boolean$1(),files:array(string$2().min(1))}).loose(),branchIsLocal:boolean$1()},BranchInfoResponseSchema=discriminatedUnion(`detached`,[object$1({detached:literal(!1),currentBranch:string$2().min(1).nullable(),currentHeadSha:_null(),...BranchInfoSharedFields}).loose(),object$1({detached:literal(!0),currentBranch:_null(),currentHeadSha:string$2().min(1),...BranchInfoSharedFields}).loose()]),CheckoutRequestSchema=object$1({branch:refineBranchName(string$2().min(1)),principalId:string$2().optional()}).loose(),CheckoutFailureReasonSchema=_enum([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`]),CheckoutResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0)}).loose(),object$1({ok:literal(!1),reason:CheckoutFailureReasonSchema,files:array(string$2().min(1)).optional()}).loose()]),ServerInfoSuccessSchema=object$1({serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional(),currentDiskAckSVs:record(string$2().min(1),string$2().min(1)).optional()}).loose(),PrincipalSuccessSchema=object$1({id:string$2().min(1),display_name:string$2().min(1),display_email:string$2(),source:_enum([`git-config`,`synthesized`]),created_at:string$2().min(1)}).loose(),ProblemTypeSchema=_enum(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:no-conflict-tracked.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed`.split(`.`));function assertNeverProblemType(e){throw Error(`Unexpected ProblemType variant: ${JSON.stringify(e)}`)}const ProblemDetailsSchema=object$1({type:ProblemTypeSchema,title:string$2().min(1),status:number$1().int().min(400).max(599),instance:string$2().regex(URN_UUID_RE,`instance must be urn:uuid:<uuid>`).optional(),detail:string$2().optional()}).loose(),UploadRequestSchema=object$1({parentDocName:string$2().min(1),agentId:string$2().min(1).optional(),agentName:string$2().min(1).optional()}).loose(),UploadAssetSuccessSchema=object$1({src:string$2().min(1),path:string$2().min(1).optional(),deduped:boolean$1().optional()}).loose(),LocalOpCloneRequestSchema=object$1({url:string$2().min(1),dir:string$2().min(1),branch:string$2().min(1).refine(isValidBranchName,`invalid branch name`).optional()}).loose(),StreamingProblemEventSchema=object$1({type:literal(`error`),problem:ProblemDetailsSchema}).loose();function reconstructAttrs(e,t){let S=Array.isArray(e.attrs.attributes)?e.attrs.attributes.filter(e=>typeof e==`object`&&!!e&&`type`in e):[],w=e.attrs.props??{},E=new Map,D=new Set;if(t)for(let e of t)e.omitOnDefault===!0&&`defaultValue`in e&&e.defaultValue!==void 0&&E.set(e.name,e.defaultValue),e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&D.add(e.name);for(let[e,t]of Object.entries(w)){let w=S.findIndex(t=>t.type===`mdxJsxAttribute`&&t.name===e);if(E.has(e)&&Object.is(E.get(e),t)){w>=0&&S.splice(w,1);continue}if(D.has(e)&&t===``){w>=0&&S.splice(w,1);continue}let O=propToMdxJsxAttribute(e,t);w>=0?S[w]=O:S.push(O)}return S}function propToMdxJsxAttribute(e,t){if(t===!0)return{type:`mdxJsxAttribute`,name:e,value:null};if(t===!1)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:`false`}};if(t==null)return{type:`mdxJsxAttribute`,name:e,value:null};if(typeof t==`string`)return{type:`mdxJsxAttribute`,name:e,value:t};if(typeof t==`number`)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:JSON.stringify(t)}};if(typeof t==`object`){let S;try{S=JSON.stringify(t)}catch{S=String(t)}return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:S}}}return{type:`mdxJsxAttribute`,name:e,value:String(t)}}function emitMdxJsx(e,t,S,w){return{type:`mdxJsxFlowElement`,name:e,attributes:reconstructAttrs(t,w),children:S.all(t),data:{}}}const LOOM_ID_RE=/^[A-Za-z0-9]{20,}$/,LOOM_TIMESTAMP_RE=/^(?:\d+s?|(?:\d+h)?(?:\d+m)?(?:\d+s)?)$/;function isLoomHost(e){let t=e.toLowerCase();return t===`loom.com`||t===`www.loom.com`}function extractLoomId(e){let t=e.pathname.match(/^\/(?:share|embed)\/([A-Za-z0-9]+)\/?$/);if(!t)return null;let S=t[1]??``;return LOOM_ID_RE.test(S)?S:null}function parseLoomUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isLoomHost(t.hostname))return null;let S=extractLoomId(t);if(!S)return null;let w=t.searchParams.get(`t`);return{id:S,startRaw:w&&w.length>0&&LOOM_TIMESTAMP_RE.test(w)?w:null}}function isLoomUrl(e){return parseLoomUrl(e)!==null}function isVimeoHost(e){let t=e.toLowerCase();return t===`vimeo.com`||t===`www.vimeo.com`||t===`player.vimeo.com`}function isVimeoUrl(e){if(typeof e!=`string`||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol!==`http:`&&t.protocol!==`https:`?!1:isVimeoHost(t.hostname)}const YOUTUBE_VIDEO_ID_RE=/^[A-Za-z0-9_-]{11}$/;function isYouTubeHost(e){let t=e.toLowerCase();return t===`youtube.com`||t===`www.youtube.com`||t===`m.youtube.com`||t===`music.youtube.com`||t===`youtu.be`||t===`youtube-nocookie.com`||t===`www.youtube-nocookie.com`}function parseTimestampToSeconds(e){if(e.length===0)return null;if(/^[0-9]+$/.test(e)){let t=Number.parseInt(e,10);return t>0?t:null}let t=e.match(/^(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s?)?$/);if(!t)return null;let S=t[1]?Number.parseInt(t[1],10):0,w=t[2]?Number.parseInt(t[2],10):0,E=t[3]?Number.parseInt(t[3],10):0,D=S*3600+w*60+E;return D>0?D:null}function extractVideoId(e){if(e.hostname.toLowerCase()===`youtu.be`){let t=e.pathname.replace(/^\//,``).split(`/`)[0]??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}if(e.pathname===`/watch`){let t=e.searchParams.get(`v`)??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}let t=e.pathname.match(/^\/(?:embed|shorts|v)\/([A-Za-z0-9_-]{11})\/?$/);return t?t[1]??null:null}function parseYouTubeUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isYouTubeHost(t.hostname))return null;let S=extractVideoId(t);if(!S)return null;let w=t.searchParams.get(`t`)??t.searchParams.get(`start`)??``;return{id:S,startSeconds:w.length>0?parseTimestampToSeconds(w):null,noCookie:t.hostname.toLowerCase().endsWith(`youtube-nocookie.com`)}}const calloutProps=[{name:`type`,type:`enum`,enumValues:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`],defaultValue:`note`,required:!1,description:`Callout variant`},{name:`title`,type:`string`,required:!1,description:`Optional heading shown above the body`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Lightbulb`)"},{name:`color`,type:`string`,required:!1,advanced:!0,description:"Optional accent color override (hex — e.g. `#F05032`)"},{name:`collapsible`,type:`boolean`,required:!1,defaultValue:!1,advanced:!0,description:"Render as a foldable `<details>` (Obsidian `[!TYPE]+/-`)"},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,description:`When collapsible, start in the open state`},{name:`children`,type:`reactnode`,required:!0,description:`Callout content`}],htmlImgProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Image source URL`,accept:ALLOWED_IMAGE_MIME_TYPES,autoFocus:!0},{name:`alt`,type:`string`,required:!0,description:`Alt text`},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Image width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Image height`},{name:`srcset`,type:`string`,required:!1,advanced:!0,description:`Responsive image candidate set (e.g. "x.png 1x, y.png 2x")`},{name:`sizes`,type:`string`,required:!1,advanced:!0,description:`Responsive image sizes hint paired with srcset`},{name:`loading`,type:`enum`,enumValues:[`eager`,`lazy`],defaultValue:`lazy`,required:!1,advanced:!0,omitOnDefault:!0,description:`Native img loading strategy (defaults to lazy)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`decoding`,type:`enum`,enumValues:[`sync`,`async`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Hint for how the browser should decode the image`},{name:`fetchpriority`,type:`enum`,enumValues:[`high`,`low`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Resource fetch priority hint`},{name:`crossorigin`,type:`enum`,enumValues:[`anonymous`,`use-credentials`],required:!1,advanced:!0,description:`CORS mode for the image fetch`},{name:`referrerpolicy`,type:`string`,required:!1,advanced:!0,description:`Referrer policy for the image fetch (HTML referrerpolicy values)`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],embedProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Embedded page URL (must start with http:// or https://)`,autoFocus:!0},{name:`title`,type:`string`,required:!1,description:`Iframe title (accessible label for screen readers)`},{name:`width`,type:`string`,required:!1,advanced:!0,description:`Embed width as a CSS length (e.g. "100%", "640px")`},{name:`height`,type:`string`,required:!1,advanced:!0,description:`Embed height as a CSS length (e.g. "26rem", "480px")`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],htmlVideoProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Video source URL`,accept:ALLOWED_VIDEO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 video controls (defaults to true)`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`poster`,type:`string`,required:!1,advanced:!0,description:`Poster image URL shown before playback`,accept:ALLOWED_IMAGE_MIME_TYPES,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Video width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Video height`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`,hideWhen:e=>typeof e.src==`string`&&isLoomUrl(e.src)},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`,hideWhen:e=>typeof e.src==`string`&&(parseYouTubeUrl(e.src)!==null||isVimeoUrl(e.src)||isLoomUrl(e.src))}],htmlAudioProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Audio source URL`,accept:ALLOWED_AUDIO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 audio controls (defaults to true)`},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the audio to preload`}],accordionProps=[{name:`title`,type:`string`,required:!0,description:`Accordion heading shown inside the <summary>`},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!1,description:`When true, the accordion renders expanded on initial load`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Rocket`)"},{name:`description`,type:`string`,required:!1,advanced:!0,description:`Optional subtitle rendered below the title inside <summary>`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#advanced-options`)"},{name:`name`,type:`string`,required:!1,advanced:!0,description:`HTML5 <details name=> group — siblings with the same name are mutually exclusive`}],gfmCalloutProps=[calloutProps[0],calloutProps[1],calloutProps[4],calloutProps[5],calloutProps[6]],commonMarkImageProps=[htmlImgProps[0],htmlImgProps[1],htmlImgProps[7]],htmlDetailsAccordionProps=[accordionProps[0],accordionProps[1],accordionProps[4],accordionProps[5]],wikiEmbedImageProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Alt text (Obsidian alias syntax: `![[file.png|alt text]]`)"}],wikiEmbedVideoProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[clip.mp4|title]]`)"}],wikiEmbedAudioProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[song.mp3|title]]`)"}],tabsProps=[{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#install-tabs`)"}],tabProps=[{name:`label`,type:`string`,required:!0,autoFocus:!0,defaultValue:`Tab`,description:`Tab strip label — shown in the clickable pill at the top`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#tab-npm`)"}],mathProps=[{name:`formula`,type:`string`,required:!0,autoFocus:!0,language:`latex`,description:`LaTeX math source (rendered with KaTeX in the browser)`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#eq-pythagoras`)"},{name:`language`,type:`string`,required:!1,advanced:!0,description:"Forward-compat hint for the math source language (default `latex`). Reserved for future MathJax / Typst / AsciiMath substrates."}],dollarMathProps=[mathProps[0]],mathFenceProps=[mathProps[0]],mermaidProps=[{name:`chart`,type:`string`,required:!0,autoFocus:!0,language:`mermaid`,description:`Mermaid chart source (graph / flowchart / sequenceDiagram / class / state / etc.)`}],wikiEmbedFileProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Display name override (Obsidian alias syntax: `![[file.zip|label]]`)"}],fileProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`File URL`,accept:[`*/*`],autoFocus:!0}],pdfProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`PDF source URL`,accept:ALLOWED_PDF_MIME_TYPES,autoFocus:!0},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Accessible label for the embedded PDF viewer`},{name:`anchor`,type:`string`,required:!1,advanced:!0,description:"PDF viewer parameters as a single URL-fragment string (e.g. `page=3&height=600`)"}],mirrorProps=[{name:`src`,type:`string`,required:!0,description:"Path of the source doc, extension-less (e.g. `api-spec`).",autoFocus:!0},{name:`anchor`,type:`string`,required:!0,description:"Id of the `<MirrorSource>` block within the source doc."}],mirrorSourceProps=[{name:`id`,type:`string`,required:!0,description:"Stable id agents and authors use to reference this block from `<Mirror>` elsewhere.",autoFocus:!0},{name:`children`,type:`reactnode`,required:!0,description:`Block content this MirrorSource owns — paragraphs, callouts, code, nested JSX, anything.`}];function escapeHtmlAttr(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function escapeHtmlText(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function serializeWikiEmbed(e){let t=e.attrs.props,S=t?.target??``,w=typeof t?.alias==`string`&&t.alias.length>0?t.alias:null,E=typeof t?.anchor==`string`&&t.anchor.length>0?t.anchor:null,D=w??(E?`${S}#${E}`:S);return{type:`wikiLinkEmbed`,value:D,data:{target:S,anchor:E,alias:w},children:[{type:`text`,value:D}]}}const builtInComponents=[{name:`Callout`,surface:`canonical`,hasChildren:!0,props:calloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`Callout`,description:`Alert / admonition with 15 type variants — 5 GFM (note, tip, important, warning, caution) plus 10 Obsidian-parity (abstract, info, todo, success, question, failure, danger, bug, example, quote)`,searchTerms:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`,`alert`,`admonition`,`callout`],serialize:(e,t)=>emitMdxJsx(`Callout`,e,t,calloutProps)},{name:`img`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlImgProps,icon:`Image`,category:`media`,displayName:`Image`,description:`Image with click-to-zoom and HTML-native attributes`,searchTerms:[`image`,`zoom`,`picture`,`photo`],placeholder:{label:`Add an image`},serialize:(e,t)=>emitMdxJsx(`img`,e,t,htmlImgProps)},{name:`video`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlVideoProps,icon:`SquarePlay`,category:`media`,displayName:`Video`,description:`HTML5 video player with native controls`,searchTerms:[`video`,`media`,`player`,`mp4`,`webm`,`movie`],placeholder:{label:`Add a video`},serialize:(e,t)=>emitMdxJsx(`video`,e,t,htmlVideoProps)},{name:`audio`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlAudioProps,icon:`Volume2`,category:`media`,displayName:`Audio`,description:`HTML5 audio player with native controls`,searchTerms:[`audio`,`sound`,`music`,`mp3`,`podcast`,`player`],placeholder:{label:`Add audio`},serialize:(e,t)=>emitMdxJsx(`audio`,e,t,htmlAudioProps)},{name:`Pdf`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:pdfProps,icon:`FileText`,category:`media`,displayName:`PDF`,description:"Embedded PDF viewer (`#page=N` to open at page N, `#height=N` for viewer height)",searchTerms:[`pdf`,`document`,`embed`,`pdfjs`],placeholder:{label:`Add a PDF`},serialize:(e,t)=>emitMdxJsx(`Pdf`,e,t,pdfProps)},{name:`File`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:fileProps,icon:`Paperclip`,category:`media`,displayName:`File`,description:`Downloadable file attachment — inline row with name + size + download link`,searchTerms:[`file`,`attachment`,`download`,`document`,`zip`,`docx`,`doc`],placeholder:{label:`Add a file`},serialize:(e,t)=>emitMdxJsx(`File`,e,t,fileProps)},{name:`Embed`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:embedProps,icon:`AppWindow`,category:`media`,displayName:`Embed`,description:`Inline web embed (iframe) — drop a URL, get a resizable preview pane`,searchTerms:[`embed`,`iframe`,`website`,`page`,`inline`,`frame`,`preview`],placeholder:{label:`Embed a URL`},serialize:(e,t)=>emitMdxJsx(`Embed`,e,t,embedProps)},{name:`Accordion`,surface:`canonical`,hasChildren:!0,props:accordionProps,icon:`ChevronRight`,category:`content`,displayName:`Accordion`,description:"Standalone expand/collapse via native HTML5 <details>/<summary>. Group siblings with the `name` prop for exclusive-accordion UX.",searchTerms:[`toggle`,`accordion`,`expandable`,`details`,`disclosure`,`collapse`,`fold`],exampleBody:`Body content revealed when the accordion is expanded.`,serialize:(e,t)=>emitMdxJsx(`Accordion`,e,t,accordionProps)},{name:`Tabs`,surface:`canonical`,hasChildren:!0,emptyChildName:`Tab`,props:tabsProps,icon:`LayoutPanelTop`,category:`content`,displayName:`Tabs`,description:"Horizontal tab strip + active panel below. Each `<Tab>` child is one panel; clickable pills at the top switch the active one. Active selection is ephemeral (resets on reload).",searchTerms:[`tabs`,`tabbed`,`panels`,`tabgroup`,`switcher`],exampleBody:`<Tab label="One">Body of the first tab panel.</Tab>
391
391
  <Tab label="Two">Body of the second tab panel.</Tab>`,serialize:(e,t)=>emitMdxJsx(`Tabs`,e,t,tabsProps)},{name:`Tab`,surface:`canonical`,hasChildren:!0,props:tabProps,icon:`PanelTop`,category:`content`,displayName:`Tab`,description:"A single tab panel inside a `<Tabs>` container — carries the strip label and the block-content body.",searchTerms:[`tab`,`panel`],exampleBody:"Panel content — must be nested inside a `<Tabs>` parent.",serialize:(e,t)=>emitMdxJsx(`Tab`,e,t,tabProps)},{name:`Math`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mathProps,icon:`Sigma`,category:`content`,displayName:`Math`,description:`Block math equation rendered with KaTeX from a LaTeX source string`,searchTerms:[`math`,`latex`,`equation`,`formula`,`katex`,`tex`],serialize:(e,t)=>emitMdxJsx(`Math`,e,t,mathProps)},{name:`MermaidFence`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mermaidProps,icon:`Workflow`,category:`content`,displayName:`Mermaid`,description:"Diagram rendered from Mermaid source (flowchart, sequence, class, state, ER, gantt, pie). Authored exclusively as ` ```mermaid ` fenced code.",searchTerms:[`mermaid`,`diagram`,`flowchart`,`graph`,`sequence`,`sequencediagram`,`class`,`state`,`er`,`erdiagram`,`gantt`,`pie`,`chart`],serialize:e=>({type:`code`,lang:`mermaid`,meta:null,value:e.attrs.props?.chart??``})},{name:`Mirror`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mirrorProps,icon:`CopyPlus`,category:`content`,displayName:`Mirror`,description:"Render a read-only copy of a `<MirrorSource>` block from another doc. Use to keep the same content in sync across multiple docs without copy-paste — edits land at the source, every Mirror reflects the change.",searchTerms:[`mirror`,`sync`,`synced`,`transclude`,`embed`,`reference`,`shared block`],serialize:(e,t)=>emitMdxJsx(`Mirror`,e,t,mirrorProps)},{name:`MirrorSource`,surface:`canonical`,hasChildren:!0,props:mirrorSourceProps,icon:`GitBranch`,category:`content`,displayName:`Mirror Source`,description:'Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" anchor="<id>">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.',searchTerms:[`mirror source`,`sync source`,`source block`,`master block`,`shared`],exampleBody:"Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this id.",serialize:(e,t)=>emitMdxJsx(`MirrorSource`,e,t,mirrorSourceProps)},{name:`GFMCallout`,surface:`compat`,hasChildren:!0,props:gfmCalloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`GFM Callout`,description:"GFM blockquote alert (`> [!NOTE]`) — read-only compat. Preserves `> [!NOTE]` syntax on round-trip; insert a fresh Callout block for the full prop surface.",rendersAs:`Callout`,translateProps:e=>e,serialize:(e,t)=>{let S=e.attrs.props,w=new Set([`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`]),E=S?.type??`note`;return{type:`blockquote`,children:[{type:`html`,value:`[!${(w.has(E.toLowerCase())?E:`note`).toUpperCase()}]${S?.collapsible?S.defaultOpen===!1?`-`:`+`:``}${S?.title?` ${S.title}`:``}`},...t.all(e).filter(e=>{if(e.type!==`paragraph`)return!0;let t=e;return Array.isArray(t.children)&&t.children.length>0})]}}},{name:`CommonMarkImage`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:commonMarkImageProps,icon:`Image`,category:`media`,displayName:`CommonMark Image`,description:'CommonMark image (`![alt](src "title")`) — read-only compat. Preserves `![alt](src)` syntax on round-trip; insert a fresh Image block for the full HTML-native attribute surface (srcset, sizes, decoding, etc.).',rendersAs:`img`,translateProps:e=>e,serialize:e=>{let t=e.attrs.props;return{type:`paragraph`,children:[{type:`image`,url:t?.sourceUrl??t?.src??``,alt:t?.alt??``,title:t?.title??null}]}}},{name:`WikiEmbedImage`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedImageProps,icon:`ZoomIn`,category:`media`,displayName:`Wiki Embed Image`,description:"Obsidian-style `![[file.png]]` wiki-embed — read-only compat. Edit the alt-text via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`img`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,alt:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedVideo`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedVideoProps,icon:`Film`,category:`media`,displayName:`Wiki Embed Video`,description:"Obsidian-style `![[clip.mp4]]` wiki-embed — read-only compat. Edit the title via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`video`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,title:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedAudio`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedAudioProps,icon:`Volume2`,category:`media`,displayName:`Wiki Embed Audio`,description:"Obsidian-style `![[song.mp3]]` wiki-embed — read-only compat. Edit the title via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`audio`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,title:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedFile`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedFileProps,icon:`Paperclip`,category:`media`,displayName:`Wiki Embed File`,description:"Obsidian-style `![[file.zip]]` wiki-embed — read-only compat for arbitrary downloadable attachments. Renders through the `File` canonical (inline row with file-up icon + bold name + optional dim size). Edit the display name via the alias slot.",rendersAs:`File`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.size==`string`&&e.size.length>0?e.size:null;return{src:e.src,name:t??void 0,size:S??void 0}},serialize:serializeWikiEmbed},{name:`HtmlDetailsAccordion`,surface:`compat`,hasChildren:!0,props:htmlDetailsAccordionProps,icon:`ChevronRight`,category:`content`,displayName:`HTML5 Details`,description:"HTML5 `<details><summary>` collapsible — read-only compat. Preserves `<details>` syntax on round-trip; insert a fresh Accordion block for icon / description / group-name props.",rendersAs:`Accordion`,translateProps:e=>e,serialize:(e,t)=>{let S=e.attrs.props,w=S?.defaultOpen?` open`:``,E=S?.name?` name="${escapeHtmlAttr(S.name)}"`:``,D=S?.id?` id="${escapeHtmlAttr(S.id)}"`:``,O=S?.title?.trim(),k=O?`<summary>${escapeHtmlText(O)}</summary>`:``;return{type:`mdxJsxFlowElement`,name:`HtmlDetailsAccordion`,attributes:[],children:t.all(e),data:{htmlBoundary:{opener:`<details${w}${E}${D}>\n${k}`,closer:`</details>`}}}}},{name:`DollarMath`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:dollarMathProps,icon:`Sigma`,category:`content`,displayName:`Dollar Math`,description:"Block math via `$$…$$` syntax — read-only compat. Preserves `$$…$$` form on round-trip; insert a fresh Math block for the full prop surface (id, language).",rendersAs:`Math`,translateProps:e=>e,serialize:e=>({type:`math`,value:e.attrs.props?.formula??``})},{name:`MathFence`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:mathFenceProps,icon:`Sigma`,category:`content`,displayName:`Math Fence`,description:"Block math via ` ```math ` fenced code syntax — read-only compat. Preserves the fence form on round-trip; insert a fresh Math block for the full prop surface (id, language).",rendersAs:`Math`,translateProps:e=>e,serialize:e=>({type:`code`,lang:`math`,meta:null,value:e.attrs.props?.formula??``})}],wildcardMeta={name:`*`,surface:`canonical`,hasChildren:!0,props:[],description:`Unregistered component — children editable as markdown`,serialize:(e,t)=>emitMdxJsx(e.attrs.componentName||`*`,e,t)};function createRegistry(){let e=new Map;e.set(`*`,wildcardMeta);for(let t of builtInComponents)e.set(t.name,t);return{get(t){return e.get(t)},getOrWildcard(t){return e.get(t)??e.get(`*`)},set(t,S){e.set(t,S)},has(t){return e.has(t)},entries(){return e.entries()}}}function ypsCounters(){let e=globalThis;return e.__okYpsCounters||={block:0,inline:0},e.__okYpsCounters}const metrics={parseFallback:{blockLevel:0,wholeDoc:0},jsxRenderFailure:{},jsxAutoConvertFailed:{},jsxAutoConvertSucceeded:{},jsxPropDropped:{},jsxMoveFailed:{},jsxStuckCopyFailed:{},jsxStuckDeleteFailed:{},jsxPopoverCloseRestoreFailed:{},jsxKeyboardDeleteFailed:{},blockGripClickSelectFailed:{},jsxArrowNodeSelectFailed:{}};function incrementBlockFallback(){metrics.parseFallback.blockLevel++}function incrementWholeDocFallback(){metrics.parseFallback.wholeDoc++}function getParseHealth(){let e=ypsCounters();return{parseFallback:{...metrics.parseFallback},ypsMismatch:{block:e.block,inline:e.inline},jsxRenderFailure:{...metrics.jsxRenderFailure},jsxAutoConvertFailed:{...metrics.jsxAutoConvertFailed},jsxAutoConvertSucceeded:{...metrics.jsxAutoConvertSucceeded},jsxPropDropped:{...metrics.jsxPropDropped},jsxMoveFailed:{...metrics.jsxMoveFailed},jsxStuckCopyFailed:{...metrics.jsxStuckCopyFailed},jsxStuckDeleteFailed:{...metrics.jsxStuckDeleteFailed},jsxPopoverCloseRestoreFailed:{...metrics.jsxPopoverCloseRestoreFailed},jsxKeyboardDeleteFailed:{...metrics.jsxKeyboardDeleteFailed},blockGripClickSelectFailed:{...metrics.blockGripClickSelectFailed},jsxArrowNodeSelectFailed:{...metrics.jsxArrowNodeSelectFailed}}}const FENCE_RE=/^(`{3,}|~{3,})/gm;function findFencedRegions(e){let t=[],S=null;for(let w of e.matchAll(FENCE_RE)){let e=w[1],E=w.index;S?e[0]===S.marker[0]&&e.length>=S.marker.length&&(t.push([S.offset,E+w[0].length]),S=null):S={marker:e,offset:E}}return S&&t.push([S.offset,e.length]),t}function isInsideFence(e,t){return t.some(([t,S])=>e>=t&&e<S)}const REF_DEF_RE=/^[ \t]{0,3}\[([^\]]+)\]:\s*(\S+)(\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*$/gm;function hoistRefDefs(e){let t=findFencedRegions(e),S=[];for(let w of e.matchAll(REF_DEF_RE))isInsideFence(w.index,t)||S.push(w[0].trimEnd());return S.length>0?`${S.join(`
392
392
  `)}\n\n`:``}const MAX_PARSE_WALLCLOCK_MS=500,MAX_TOTAL_PARSE_CALLS=1e3;function parseWithFallback(e,t){let S={startMs:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),calls:0};return parseRecursive(e,t.parse,0,S)}function budgetExhausted(e){return e.calls>=MAX_TOTAL_PARSE_CALLS?!0:(typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now())-e.startMs>=MAX_PARSE_WALLCLOCK_MS}const MAX_ERROR_MESSAGE_LEN=500;function errorPayload(e){return e instanceof Error?{name:e.name,message:e.message.slice(0,MAX_ERROR_MESSAGE_LEN),stack:e.stack?.split(`
393
393
  `).slice(0,4).join(`
@@ -1226,7 +1226,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
1226
1226
  `,`
1227
1227
  `).replaceAll(`\r`,`
1228
1228
  `).split(`
1229
- `))S(E)||collectHrefsFromLine(stripHtmlComments(E,w).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let S=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(S))return null;let w=resolveAssetProjectPath(t,e.fromDocName);if(!w)return null;let E=resolve(e.contentDir,w),D,O;try{if(D=normalize(realpathSync(E)),!isWithinContentDir(D,e.contentDir))return null;O=statSync(D)}catch(t){let S=errnoCode$1(t);return S!==`ENOENT`&&S!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return O.isFile()?{absolutePath:D,relativePath:toContentRelativePath(e.contentDir,D),stat:O}:null}function toContentRelativePath(e,t){let S=normalize(realpathSync(e));return normalize(t).slice(S.length+(S.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let S=new Map;for(let[w,E]of e.fileIndex){let D=e.readMarkdown(E.canonicalPath);if(D!==null)for(let E of extractLocalAssetHrefs(D)){let D=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:w,href:E});if(!D||e.isExcluded?.(D.relativePath))continue;let O=mediaKindForAssetPath(D.absolutePath),k=S.get(D.relativePath);if(k){k.referencedBy.includes(w)||k.referencedBy.push(w);continue}S.set(D.relativePath,{kind:`asset`,path:D.relativePath,assetExt:extname(D.relativePath).toLowerCase(),mediaKind:O,size:D.stat.size,modified:D.stat.mtime.toISOString(),referencedBy:[w]})}}return[...S.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:S,inlineExtensions:w,assetExtensions:E,blocklistExtensions:D}=e;return(e,O,k)=>{let j;try{j=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return k()}let F=extname(j).slice(1).toLowerCase(),L=F===`md`||F===`mdx`;if(!j||t.isPathIgnored(j)||!L&&!E.has(F))return k();O.setHeader(`X-Content-Type-Options`,`nosniff`),L||(w.has(F)?O.setHeader(`Content-Disposition`,`inline`):O.setHeader(`Content-Disposition`,`attachment`)),F===`svg`&&O.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),S(e,O,()=>{if(!O.headersSent){if(E.has(F)||D.has(F)){O.statusCode=404,O.end();return}k()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let S=resolve(e),w=resolve(S,t),E=relative(S,w);return E===``?{ok:!0,abs:w,rel:``}:E===`..`||E.startsWith(`../`)||isAbsolute(E)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:w,rel:E}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string$2().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string$2().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,S){let w={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:w,...S?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
1229
+ `))S(E)||collectHrefsFromLine(stripHtmlComments(E,w).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let S=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(S))return null;let w=resolveAssetProjectPath(t,e.fromDocName);if(!w)return null;let E=resolve(e.contentDir,w),D,O;try{if(D=normalize(realpathSync(E)),!isWithinContentDir(D,e.contentDir))return null;O=statSync(D)}catch(t){let S=errnoCode$1(t);return S!==`ENOENT`&&S!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return O.isFile()?{absolutePath:D,relativePath:toContentRelativePath(e.contentDir,D),stat:O}:null}function toContentRelativePath(e,t){let S=normalize(realpathSync(e));return normalize(t).slice(S.length+(S.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let S=new Map;for(let[w,E]of e.fileIndex){let D=e.readMarkdown(E.canonicalPath);if(D!==null)for(let E of extractLocalAssetHrefs(D)){let D=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:w,href:E});if(!D||e.isExcluded?.(D.relativePath))continue;let O=mediaKindForAssetPath(D.absolutePath),k=S.get(D.relativePath);if(k){k.referencedBy.includes(w)||k.referencedBy.push(w);continue}S.set(D.relativePath,{kind:`asset`,path:D.relativePath,assetExt:extname(D.relativePath).toLowerCase(),mediaKind:O,size:D.stat.size,modified:D.stat.mtime.toISOString(),referencedBy:[w]})}}return[...S.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:S,inlineExtensions:w,assetExtensions:E,blocklistExtensions:D}=e;return(e,O,k)=>{let j;try{j=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return k()}let F=extname(j).slice(1).toLowerCase(),L=F===`md`||F===`mdx`;if(!j||t.isPathIgnored(j)||!L&&!E.has(F))return k();O.setHeader(`X-Content-Type-Options`,`nosniff`),L||(w.has(F)?O.setHeader(`Content-Disposition`,`inline`):O.setHeader(`Content-Disposition`,`attachment`)),F===`svg`&&O.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),S(e,O,()=>{if(!O.headersSent){if(E.has(F)||D.has(F)){O.statusCode=404,O.end();return}k()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let S=resolve(e),w=resolve(S,t),E=relative(S,w);return E===``?{ok:!0,abs:w,rel:``}:E===`..`||E.startsWith(`../`)||isAbsolute(E)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:w,rel:E}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string$2().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string$2().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,S){let w={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:w,...S?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
1230
1230
 
1231
1231
  Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
1232
1232
 
@@ -2240,7 +2240,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
2240
2240
  `).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:xc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:xc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:xc,cause:e})}finally{we.release(pc)}},{handler:xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xc})}),Cc=`local-op-auth-repos`,wc=withValidation(LocalOpAuthHostRequestSchema,Tc,{handler:Cc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cc})});async function Tc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Cc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Cc),[D,...O]=ue,k=[...O,`auth`,`repos`,`--json`,`--host`,w],j=!1,F=``,L=spawn(D,k,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),B=setTimeout(()=>{L.kill(`SIGTERM`)},ic);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
2241
2241
  `);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),we.release(mc))}),L.on(`error`,e=>{clearTimeout(B),j||(j=!0,t.writableEnded||(E(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),we.release(mc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),we.release(mc))})}let Ec=`local-op-auth-signout`,Dc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ec,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`signout`,`--host`,w];await new Promise((t,S)=>{let w=spawn(e,E,{stdio:`ignore`,env:{...process.env}}),D=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.on(`close`,()=>{clearTimeout(D),t()}),w.on(`error`,e=>{clearTimeout(D),S(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Ec})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ec,cause:e})}finally{we.release(hc)}},{handler:Ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ec})}),Oc=`local-op-auth-pat`,kc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!we.tryAcquire(gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Oc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`pat`,`--json`,`--host`,D],O=(await new Promise((t,S)=>{let D=spawn(e,E,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),O=setTimeout(()=>{D.kill(`SIGTERM`)},3e4);D.stdin.write(`${w}\n`),D.stdin.end();let k=[];D.stdout.on(`data`,e=>k.push(e)),D.on(`close`,e=>{clearTimeout(O),e===0?t(Buffer.concat(k).toString(`utf-8`)):S(Error(`auth pat exited with code ${e}`))}),D.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
2242
2242
  `).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:Oc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Oc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Oc,cause:e})}finally{we.release(gc)}},{handler:Oc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Oc})}),Ac=`local-op-auth-identity`;async function jc(e,t){if(checkLocalOpSecurity(e,t,{handler:Ac})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Ac,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ac});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Ac})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Ac,cause:e})}}}let Mc=`/api/local-op/auth/set-identity`,Nc=`local-op-auth-set-identity`,Pc=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Nc});return}if(!we.tryAcquire(Mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Nc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Nc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Nc,cause:e})}finally{we.release(Mc)}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nc})});async function Fc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Ic=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Lc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Rc=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function zc(e,S){if(!checkLocalOpSecurity(e,S,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(S,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`file`);if(!E){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(E.includes(`..`)||E.startsWith(`/`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let D=stripDocExtension(E),O=t.documents.get(D)?.getMap(`lifecycle`).get(`status`)===`conflict`,k=ce?.(),j=k?k.getConflicts().some(e=>e.file===E):!1;if(!O&&!j){errorResponse(S,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:E}});return}let F=w.searchParams.get(`source`),L=esm_default({baseDir:de,timeout:{block:15e3}});async function B(e){try{return await L.raw([`show`,`:${e}:${E}`])}catch{return``}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=w,k=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);k=typeof t==`string`&&t.length>0?t:null;let w=Ce?Ce(e):null;w!==null&&!ytextHasConflictMarkers(w)?O=w:w!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(S,200,SyncConflictContentSuccessSchema,{file:E,base:e,ours:O,theirs:D,lifecycleStatus:k},{handler:`sync-conflict-content`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Bc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Vc=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Hc(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Uc=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Wc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,ze.probeAll)}catch(e){t.headersSent||(log$2.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Gc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ce?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Kc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:te.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function qc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=te.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:Ve(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Jc(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let Yc=/^[A-Za-z0-9_-]+$/;function Xc(e,t,S=`template`){return!e||!Yc.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function Zc(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}async function Qc(e,t){if(e.method===`GET`)return $c(e,t);if(e.method===`PUT`)return nl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let $c=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Jc(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`,`frontmatter.yml`),D=null;if(existsSync(E))try{let e=(0,import_dist$1.parse)(await readFile$1(E,`utf-8`));D=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${E}: ${t}`),D=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:D},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),nl=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Jc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:Zc(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:E.applied},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function il(e,S,w,E){if(!S)return!1;let D=e===``?`.ok/templates/${S}`:`${e.replace(/\/$/,``)}/.ok/templates/${S}`,O=t.documents.get(D);return O&&isDocInConflict(O)?(respondDocInConflict(E,new DocInConflictError({file:`${D}.md`}),w),!0):!1}async function al(e,t){if(e.method===`GET`)return ul(e,t);if(e.method===`PUT`)return dl(e,t);if(e.method===`DELETE`)return fl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let cl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,ll=e=>{let t=e.match(cl),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},ul=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Xc(w,t,`template-get`))return;let E=Jc(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=ll(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),dl=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Xc(e,t,`template-put`))return;let w=Jc(S.folder,t,`folder`,`template-put`);if(!w||il(w.folderRel,e,`template-put`,t))return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:Zc(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),fl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Xc(w,t,`template-delete`))return;let E=Jc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||il(E.folderRel,w,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function pl(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function ml(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function hl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function gl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function _l(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,...pl(e)]}function vl(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function yl(){let e=`${w}${de??``}`,t=vl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=_l().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function xl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{yl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}xl();async function Cl(e,t){if(e.method===`GET`)return Tl(e,t);if(e.method===`POST`)return El(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Tl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=hl(S.searchParams.get(`intent`)),O=gl(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await yl(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ml(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),El=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=hl(S.intent),D=gl(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await yl(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ml(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),Dl=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function Ol(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let jl=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!de){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(de);if(e===null){if(readOriginGitHubRepo(de).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(de);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(de,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),Ml=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`branch`),E=S.searchParams.get(`path`);if(!isValidBranchName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoDocPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(de,w,E),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Pl=withValidation(CheckoutRequestSchema,async(e,t,S)=>{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(de,S.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function Fl(e){let[t,...S]=ue,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Il=withValidation(EmptyRequestSchema,async(e,t)=>{if(!we.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Fl([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Ll=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Fl([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Rl=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!de){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,de,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await Fl(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),zl={"/api/asset":ka,"/api/asset-text":xs,"/api/document":jr,"/api/documents":Mr,"/api/backlinks":Fr,"/api/backlink-counts":Ir,"/api/forward-links":Lr,"/api/link-graph":zr,"/api/dead-links":Hr,"/api/orphans":Br,"/api/hubs":Vr,"/api/tags":Kc,"/api/pages":$s,"/api/folder-config":Qc,"/api/template":al,"/api/search":Cl,"/api/suggest-links":ec,"/api/page-headings":Ns,"/api/create-page":Os,"/api/create-folder":ks,"/api/duplicate-path":As,"/api/rename-path":Ps,"/api/delete-path":Is,"/api/trash/cleanup":Rs,"/api/upload":tc,"/api/agent-write":Wt,"/api/agent-write-md":Kt,"/api/frontmatter-patch":$t,"/api/agent-patch":Ur,"/api/agent-undo":Wr,"/api/agent-activity":Gr,"/api/agent-burst-diff":Kr,"/api/save-version":Xr,"/api/history":Zr,"/api/diff":ji,"/api/rollback":Hi,"/api/metrics/reconciliation":Ui,"/api/metrics/parse-health":Gi,"/api/metrics/agent-presence":Xi,"/api/server-info":Ki,"/api/share/construct-url":jl,"/api/git/branch-info":Ml,"/api/git/checkout":Pl,"/api/share/publish/owners":Il,"/api/share/publish/name-check":Ll,"/api/share/publish":Rl,"/api/principal":Yi,"/api/rescue":Ts,"/api/workspace":Zi,"/api/sync/status":Fc,"/api/sync/trigger":Ic,"/api/sync/conflicts":Lc,"/api/sync/conflict-content":zc,"/api/sync/resolve-conflict":Rc,"/api/sync/abort-merge":Gc,"/api/local-op/clone":sc,"/api/local-op/open":dc,"/api/local-op/auth/login":yc,"/api/local-op/auth/status":Sc,"/api/local-op/auth/repos":wc,"/api/local-op/auth/signout":Dc,"/api/local-op/auth/pat":kc,"/api/local-op/auth/identity":jc,"/api/local-op/auth/set-identity":Pc,"/api/installed-agents":Wc,"/api/spawn-cursor":kl,"/api/handoff":Ol,"/api/install-skill":Uc,"/api/skill/install-state":Dl,"/api/seed/plan":Bc,"/api/seed/apply":Vc,"/api/seed/packs":Hc};F&&(zl[`/api/test-reset`]=qr,zl[`/api/test-rescan-backlinks`]=Jr,zl[`/api/test-rescan-files`]=Yr);let Bl=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Vl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Bl.has(S)||Vl.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:zl[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=zl[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await Ds(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Qr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await qc(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const log$1=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$1.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$1.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-CjyGVy33-DVACqhWk.mjs`).then(e=>e.n),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(!S)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$1.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
2243
- `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session:\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **No browser tool at all** (a stdio host such as the Codex CLI, which has no embedded browser) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
2243
+ `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — including Codex\'s built-in browser, and any host tool whose contract is "navigate to a URL" (`browser`, `view_url`, `open_url`, `web.browse`, host-specific names, etc.) → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
2244
2244
  `).length};let S=e===`command`?240:120;return t.length<=S?t:{type:`string`,length:t.length,preview:`${t.slice(0,S)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let S of COMMON_SCALAR_KEYS)S in e&&(t[S]=e[S]);for(let S of COMMON_ARRAY_KEYS){let w=e[S];Array.isArray(w)&&(t[`${S}Count`]=w.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,S){let w=S.logger;return w?async(...E)=>{let D=w.child(),O=Date.now(),{toolArgs:k,extra:j}=splitInvocationArgs(E);D.info(`tool start`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},...j?.sessionId?{transportSessionId:j.sessionId}:{},...S.identityRef?.current?{agent:summarizeIdentityForLog(S.identityRef.current)}:{},...k===void 0?{}:{args:summarizeArgsForLog(e,k)}});try{let S=await runWithMcpLogger(D,async()=>await t(...E));return D.info(`tool finish`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O,result:summarizeToolResultForLog(S)}),S}catch(t){throw D.error(`tool error`,t,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let S=e.tool.bind(e),w=e.registerTool,E=typeof w==`function`?w.bind(e):void 0,D=Object.create(e);return D.tool=((...e)=>{let w=String(e[0]),E=e.at(-1);if(typeof E!=`function`)return S(...e);let D=[...e];return D[D.length-1]=wrapToolHandlerForLogging(w,E,t),S(...D)}),E&&(D.registerTool=((e,S,w)=>typeof w==`function`?E(e,S,wrapToolHandlerForLogging(e,w,t)):E(e,S,w))),D}function buildBody$2(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
2245
2245
 
2246
2246
  Topic: ${e}
@@ -3365,4 +3365,4 @@ In headless mode, write the recap into the research article's "Further reading"
3365
3365
  `),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Rt?.pruneFileIndexNowExcluded()??0,t=Rt?.pruneFolderIndexNowExcluded()??0,S=e+t;S>0&&getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] pruned now-excluded entries from file indexes`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We,serializeDoc:at});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Bt,projectDir:S,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
3366
3366
  `))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-BniQ3qki-DjKtnzVr.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ne},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;w!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(e){if(ge)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,j(ne,Te),ge&&updateUiLockPort(ne,Te),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,S)=>{try{await je(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>Y()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(ne)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:ne,contentDir:e.contentDir,port:Te,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
3367
3367
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,GitDirAccessError as $r,initShadowRepo as $t,MissingOkConfigError as A,looseObject as Ai,readSkillInstallStateSnapshot as An,tracedWriteFile as Ar,createTestLogger as At,STARTER_PACK_IDS as B,releaseUiLock as Bn,writeTargetVersion as Br,formatContributors as Bt,LOG_MD_TEMPLATE as C,OK_PROJECT_MARKER as Ci,parseHocuspocusAuthToken as Cn,tracedMkdir as Cr,createLiveDerivedIndexExtension as Ct,MCP_SERVER_NAME as D,array as Di,readAllTargets as Dn,tracedRmSync as Dr,createServer$1 as Dt,MCP_CONNECTION_ID_HEADER as E,any$1 as Ei,planSeed as En,tracedRenameSync as Er,createPersistenceExtension as Et,SERVICE_WRITER as F,_coercedNumber as Fi,reconcile as Fn,validateCloneInputs as Fr,evictStaleTrackerEntries as Ft,StateManifestError as G,resolveCursorBinaryDefault as Gn,isInitializedNotification as Gr,getLogger as Gt,STATE_MANIFEST_FILENAME as H,resetMetrics as Hn,McpServer as Hr,gcCheckpointRefs as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,NEVER as Ii,recordContributor as In,validateSkillZip as Ir,extractWikiLinksFromMarkdown as It,acquireUiLock as J,resolvePack as Jn,atomicWriteFileSync as Jr,getTracer as Jt,TagIndex as K,resolveCursorSpawnInvocation as Kn,isJSONRPCRequest as Kr,getMeter as Kt,STARTER_FOLDERS as L,require_dist$2 as Li,recordSkillInstallEvent as Ln,withSpan as Lr,findEnclosingGitRoot as Lt,PinoLogger as M,object$1 as Mi,readTargetRecordedAt as Mn,updateLastKnownHash as Mr,detectProjectShape as Mt,ProjectGitInitError as N,string$2 as Ni,readTargetVersion as Nn,updateUiLockPort as Nr,ensureProjectGit as Nt,MISSING_OK_CONFIG_MESSAGE as O,boolean$1 as Oi,readBranchFromHead as On,tracedRmdirSync as Or,createServerObserverExtension as Ot,ROLLBACK_ORIGIN as P,url as Pi,readUiLock as Pn,validateAgentId as Pr,errorResponse as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,writeConfigPatch as Qr,incrementServerObserverFire as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,registerAllTools as Rn,withSpanSync as Rr,findEnclosingProjectRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,LOCAL_DIR as Si,parseAuthRejectionWire as Sn,tracedLinkSync as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,ZodNumber$1 as Ti,pathToDocName as Tn,tracedRename as Tr,createOsProbe as Tt,SeedPrerequisiteError as U,resolveBundledSkillDir as Un,JSONRPCMessageSchema as Ur,getCurrentMcpLogger as Ut,STARTER_TEMPLATES as V,removeLastKnownHash as Vn,writeTracker as Vr,formatContributorsFrom as Vt,SeedRootDirError as W,resolveContentDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getLocalDir as Wt,applyExternalChange as X,restoreContributors as Xn,resolveConfigPath as Xr,handleSpawnCursor as Xt,applyAgentMarkdownWrite as Y,resolvePackageVersion as Yn,readConfigSafely as Yr,handleCollabSocketError as Yt,applySeed as Z,restoreLifecycleFromConflictsJson as Zn,withFileLockSync as Zr,incrementCollabSocketFilteredError as Zt,GIT_UPSTREAM_WRITER as _,humanFormat as _i,listStarterPacks as _n,startWatcher as _r,contributorCount as _t,AgentPresenceBroadcaster as a,DEFAULT_SERVER_HOST as ai,isAllowedWorkspaceHostHeader as an,safeContentPath as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,isOrphanMode as bi,mountMcpAndApi as bn,toBroadcasterKey as br,createContentFilter as bt,BacklinkIndex as c,EXECUTABLE_BLOCKLIST_EXTENSIONS as ci,isKnownPackId as cn,sanitizeClientName as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,ProblemDetailsSchema as di,isPathWithinDir as dn,seedBasenameIndex as dr,coercePackId as dt,MalformedGitPointerError as ei,initTelemetry as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,SKILL_STATE_TARGETS as fi,isProjectRoot as fn,setActiveSpanAttributes as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,defaultScheduler as gi,listRescueCheckpoints as gn,splitMarkdownBlocks as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,colorFromSeed as hi,lastKnownHash as hn,spawnDetached as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ii,isAllowedApiOrigin as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,number$1 as ji,readStateManifest as jn,tracedWriteFileSync as jr,detectClaudeDesktopPresence as jt,McpLogger as k,literal as ki,readServerPackageVersion as kn,tracedUnlinkSync as kr,createStreamingErrorWriter as kt,CC1Broadcaster as l,INLINE_RENDERABLE_EXTENSIONS as li,isLoopbackAddress as ln,saveInMemoryCheckpoint as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,SYSTEM_DOC_NAME as mi,isSystemDoc as mn,shutdownTelemetry as mr,commitWipFromTree as mt,AGENT_ID_RE as n,ASSET_EXTENSIONS as ni,installTestLoggers as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,DEFAULT_SIGTERM_GRACE_MS as oi,isConfigDoc as on,safeSubdir as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,SPAWN_ERROR_LOG as pi,isSelfWrite as pn,shadowGit as pr,commitWip as pt,UiLockCollisionError as q,resolveLockDir as qn,isJSONRPCResultResponse as qr,getMetrics as qt,AGENT_WRITE_ORIGIN as r,CC1_CONTRACT_VERSION as ri,installUserSkill as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,EDITOR_LABELS as si,isHocuspocusAuthRejectionReason as sn,safetyCheckpoint as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,ALL_EDITOR_IDS as ti,installPrettyZodErrors as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,ORPHAN_MODES as ui,isPairedWriteOrigin as un,saveVersion as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,iconFromClientName as vi,loadPrincipal as vn,streamingProblemEvent as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,locateIssue as wi,parseKeepaliveConnectionId as wn,tracedMkdirSync as wr,createMcpHttpHandler as wt,INSTALLED_AGENTS_SCHEMES as x,CONFIG_SCHEMA_MAJOR_PATH as xi,normalizeFsPath as xn,tracedAppendFileSync as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,isBranchNotFoundGitError as yi,loggerFactory as yn,swapContributors as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,registerWrite as zn,writeStateManifest as zr,formatAuthRejectionWire as zt};
3368
- //# sourceMappingURL=dist-D-D0ROxy.mjs.map
3368
+ //# sourceMappingURL=dist-DFP-WbfQ.mjs.map