@inkeep/open-knowledge 0.5.0-beta.36 → 0.5.0-beta.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/open-knowledge/SKILL.md +3 -3
- package/dist/cli.mjs +4 -4
- package/dist/constants-BQBAXbs5.mjs +2 -0
- package/dist/{dist-B4nknkyx.mjs → dist-CbduW4FE.mjs} +1 -1
- package/dist/{dist-GJE8NgVb.mjs → dist-DCWvlpSX.mjs} +29 -46
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +1 -1
- package/dist/init-Bvw8bx-P.mjs +1 -0
- package/dist/{init-mO3B7tHj.mjs → init-C57KrVEH.mjs} +5 -5
- package/dist/loader-BXskK-Ri.mjs +1 -0
- package/dist/{loader-BvNa-UGH.mjs → loader-DWVk5dKT.mjs} +2 -2
- package/dist/preview-BDdAhx0k.mjs +1 -0
- package/dist/{preview-I_sZoeGy.mjs → preview-BxinqEO0.mjs} +2 -2
- package/dist/public/assets/ActivityModeContent-2deVHdD3.js +2 -0
- package/dist/public/assets/ConsentDialogBody-Cxq7nXrG.js +2 -0
- package/dist/public/assets/DocumentContext-BjeAJh62.js +52 -0
- package/dist/public/assets/{GraphPanel-DfJ5QIY-.js → GraphPanel-Dwwq-qad.js} +3 -3
- package/dist/public/assets/McpConsentDialogBody-_DJeXfdC.js +1 -0
- package/dist/public/assets/SettingsDialog-CP0rUjSB.js +11 -0
- package/dist/public/assets/SourceEditor-AUZVv0sp.js +2 -0
- package/dist/public/assets/{_baseFor-Dewzr4ka.js → _baseFor-BQ6FmUXQ.js} +1 -1
- package/dist/public/assets/{arc-DA-_Qgty.js → arc-BTYHqK6I.js} +1 -1
- package/dist/public/assets/architecture-YZFGNWBL-haHjZ-W1.js +1 -0
- package/dist/public/assets/{architectureDiagram-Q4EWVU46-Wd0Ua0Z1.js → architectureDiagram-Q4EWVU46-CAw8ZTI6.js} +1 -1
- package/dist/public/assets/{blockDiagram-DXYQGD6D-B_z4vCOg.js → blockDiagram-DXYQGD6D-D4mfoScz.js} +1 -1
- package/dist/public/assets/{c4Diagram-AHTNJAMY-CXNX0C7S.js → c4Diagram-AHTNJAMY-g4PJwhMw.js} +1 -1
- package/dist/public/assets/channel-CDgNg08A.js +1 -0
- package/dist/public/assets/{chunk-2KRD3SAO-QHu6lS2z.js → chunk-2KRD3SAO-C0VEmSSK.js} +1 -1
- package/dist/public/assets/{chunk-336JU56O-D77Rj_75.js → chunk-336JU56O-CWe4KlcJ.js} +2 -2
- package/dist/public/assets/chunk-426QAEUC-C43TcIY5.js +1 -0
- package/dist/public/assets/{chunk-4BX2VUAB-CDjfF5mJ.js → chunk-4BX2VUAB-CqFQlA48.js} +1 -1
- package/dist/public/assets/{chunk-4TB4RGXK-DgzpC1RW.js → chunk-4TB4RGXK-B9HnNhjS.js} +1 -1
- package/dist/public/assets/chunk-55IACEB6-mJDPihNE.js +1 -0
- package/dist/public/assets/{chunk-5FUZZQ4R-pDx0Wde8.js → chunk-5FUZZQ4R-HtBbmyzC.js} +1 -1
- package/dist/public/assets/{chunk-5PVQY5BW-kcWn_d-_.js → chunk-5PVQY5BW-BsQqu9Pz.js} +1 -1
- package/dist/public/assets/{chunk-67CJDMHE-DlS8iVRi.js → chunk-67CJDMHE-DaOHFcoK.js} +1 -1
- package/dist/public/assets/{chunk-7N4EOEYR-BhSQn_oU.js → chunk-7N4EOEYR-DxJSpCGX.js} +1 -1
- package/dist/public/assets/{chunk-AA7GKIK3-C1CcYx5B.js → chunk-AA7GKIK3-Ck4Wrqot.js} +1 -1
- package/dist/public/assets/{chunk-BSJP7CBP-B5xN369R.js → chunk-BSJP7CBP-c353z_ln.js} +1 -1
- package/dist/public/assets/{chunk-CIAEETIT-ecxKAxUb.js → chunk-CIAEETIT-fgTeYGb2.js} +1 -1
- package/dist/public/assets/{chunk-EDXVE4YY-Bm2-fU6x.js → chunk-EDXVE4YY-D_b3pVvT.js} +1 -1
- package/dist/public/assets/{chunk-ENJZ2VHE-1bYQNnwE.js → chunk-ENJZ2VHE-DVMAmZ6-.js} +1 -1
- package/dist/public/assets/{chunk-FMBD7UC4-Da7gMLWx.js → chunk-FMBD7UC4-c2vVGInH.js} +1 -1
- package/dist/public/assets/{chunk-FOC6F5B3-CHF5QCPz.js → chunk-FOC6F5B3-CH9dNZl0.js} +1 -1
- package/dist/public/assets/{chunk-ICPOFSXX-rmT7ehAO.js → chunk-ICPOFSXX-D9mDZSHP.js} +1 -1
- package/dist/public/assets/{chunk-K5T4RW27-CHoEPFOL.js → chunk-K5T4RW27-DPAjYSpe.js} +1 -1
- package/dist/public/assets/{chunk-KGLVRYIC-DRtjGHKV.js → chunk-KGLVRYIC-BKUgXOPp.js} +1 -1
- package/dist/public/assets/{chunk-LIHQZDEY-GDhBbkMd.js → chunk-LIHQZDEY-CWn5kZJ_.js} +1 -1
- package/dist/public/assets/{chunk-ORNJ4GCN-C9FrQ4Hp.js → chunk-ORNJ4GCN-BETATk1q.js} +1 -1
- package/dist/public/assets/{chunk-OYMX7WX6-CAW2HwTq.js → chunk-OYMX7WX6-B2DjYZXs.js} +1 -1
- package/dist/public/assets/chunk-QZHKN3VN-B5CMAE_s.js +1 -0
- package/dist/public/assets/{chunk-U2HBQHQK-Cg7rxXd1.js → chunk-U2HBQHQK-bod_LD7f.js} +1 -1
- package/dist/public/assets/{chunk-X2U36JSP-Z4V8etFJ.js → chunk-X2U36JSP-fL9reWIe.js} +1 -1
- package/dist/public/assets/{chunk-XPW4576I-Ci37cmyJ.js → chunk-XPW4576I-BQtjckSw.js} +1 -1
- package/dist/public/assets/{chunk-YZCP3GAM-BlAQKShJ.js → chunk-YZCP3GAM-D-UepLeD.js} +1 -1
- package/dist/public/assets/{chunk-ZZ45TVLE-CKHp-exc.js → chunk-ZZ45TVLE-Z9LUwvvb.js} +1 -1
- package/dist/public/assets/classDiagram-6PBFFD2Q-B7OZyD7f.js +1 -0
- package/dist/public/assets/classDiagram-v2-HSJHXN6E-ByLnm7iZ.js +1 -0
- package/dist/public/assets/clone-DomZ2GAK.js +1 -0
- package/dist/public/assets/config-validation-events-DvohYZ-O.js +10 -0
- package/dist/public/assets/{cose-bilkent-S5V4N54A-CzOLOBap.js → cose-bilkent-S5V4N54A-D7YGD8wq.js} +1 -1
- package/dist/public/assets/{dagre-CbTJGa51.js → dagre-BZr05USh.js} +1 -1
- package/dist/public/assets/{dagre-KV5264BT-CzrIWBHi.js → dagre-KV5264BT-uIcBsxoB.js} +1 -1
- package/dist/public/assets/{diagram-5BDNPKRD-DDHvw5SM.js → diagram-5BDNPKRD-CRnuX3SM.js} +1 -1
- package/dist/public/assets/{diagram-G4DWMVQ6-DiQx8aIN.js → diagram-G4DWMVQ6-CwcP8j6L.js} +1 -1
- package/dist/public/assets/{diagram-MMDJMWI5-CJELLr4J.js → diagram-MMDJMWI5-7Eyc42Ou.js} +1 -1
- package/dist/public/assets/{diagram-TYMM5635-BHwicR15.js → diagram-TYMM5635-Bwhd6MAt.js} +1 -1
- package/dist/public/assets/{dialog-CbHo1eZD.js → dialog-B6Yo4QtX.js} +1 -1
- package/dist/public/assets/{dist-Dwop2AD8.js → dist-BOZuiab_.js} +1 -1
- package/dist/public/assets/{dist-BiYnsAMa.js → dist-BTf6on8c.js} +1 -1
- package/dist/public/assets/{dist-CATLRngz.js → dist-CHvMoypJ.js} +1 -1
- package/dist/public/assets/{dist-BMooy-F_.js → dist-CyhQWHfo.js} +1 -1
- package/dist/public/assets/{dist-B3L7cm0M.js → dist-DDFRxG7H.js} +1 -1
- package/dist/public/assets/{dist-Cp-iTcML.js → dist-Duryk2cE.js} +1 -1
- package/dist/public/assets/doc-hash-lBuGHVBB.js +423 -0
- package/dist/public/assets/{erDiagram-SMLLAGMA-DdltplqB.js → erDiagram-SMLLAGMA-DlCYmXsw.js} +1 -1
- package/dist/public/assets/{flatten-BdgTwKTr.js → flatten-ptFIxnDZ.js} +1 -1
- package/dist/public/assets/{flowDiagram-DWJPFMVM-CQHlOxjR.js → flowDiagram-DWJPFMVM-BaUE7X8U.js} +1 -1
- package/dist/public/assets/{ganttDiagram-T4ZO3ILL-CNDOT9hb.js → ganttDiagram-T4ZO3ILL-Q1QCHTKl.js} +1 -1
- package/dist/public/assets/gitGraph-7Q5UKJZL-EPtzLtdn.js +1 -0
- package/dist/public/assets/{gitGraphDiagram-UUTBAWPF-BgXxQBs9.js → gitGraphDiagram-UUTBAWPF-CG07jTjK.js} +1 -1
- package/dist/public/assets/{graphlib-CrrIJ98S.js → graphlib-B9f9FmLr.js} +1 -1
- package/dist/public/assets/index-D-CH5Wp_.js +1918 -0
- package/dist/public/assets/index-Dgr6gLuG.css +1 -0
- package/dist/public/assets/info-OMHHGYJF-DhGHQOTJ.js +1 -0
- package/dist/public/assets/{infoDiagram-42DDH7IO-BNSprTvD.js → infoDiagram-42DDH7IO-DNa5xg8m.js} +1 -1
- package/dist/public/assets/{isEmpty-XlV2b3kS.js → isEmpty-Dff4GQVw.js} +1 -1
- package/dist/public/assets/isSymbol-DIRIUNhN.js +1 -0
- package/dist/public/assets/{ishikawaDiagram-UXIWVN3A-COSeJVOI.js → ishikawaDiagram-UXIWVN3A-CCIU9fS9.js} +1 -1
- package/dist/public/assets/{journeyDiagram-VCZTEJTY-sGfNXUrs.js → journeyDiagram-VCZTEJTY-BAQyhz-O.js} +1 -1
- package/dist/public/assets/{kanban-definition-6JOO6SKY-DknMinG3.js → kanban-definition-6JOO6SKY-B7n3dFDX.js} +1 -1
- package/dist/public/assets/{line-BI6r6-S8.js → line-CVYKAp-t.js} +1 -1
- package/dist/public/assets/{linear-1aKBO-v1.js → linear-B5hCL-s4.js} +1 -1
- package/dist/public/assets/{mermaid-parser.core-BrufKICx.js → mermaid-parser.core-DfyX5Z2V.js} +2 -2
- package/dist/public/assets/{mermaid.core-hgzeX18g.js → mermaid.core--fhVTWBk.js} +3 -3
- package/dist/public/assets/{mindmap-definition-QFDTVHPH-X4KQZFdB.js → mindmap-definition-QFDTVHPH-BLm_6XTS.js} +1 -1
- package/dist/public/assets/{now--RAZR_wd.js → now-y3Cm704C.js} +1 -1
- package/dist/public/assets/{ordinal-C6wHcby9.js → ordinal-CdtiT3iH.js} +1 -1
- package/dist/public/assets/packet-4T2RLAQJ-dOkbaGJi.js +1 -0
- package/dist/public/assets/pie-ZZUOXDRM-7mxWmZMD.js +1 -0
- package/dist/public/assets/{pieDiagram-DEJITSTG-5kceM3o3.js → pieDiagram-DEJITSTG-BvfCwbBk.js} +1 -1
- package/dist/public/assets/{quadrantDiagram-34T5L4WZ-CQehowKY.js → quadrantDiagram-34T5L4WZ-DUtci3Wz.js} +1 -1
- package/dist/public/assets/radar-PYXPWWZC-CYrvwt0c.js +1 -0
- package/dist/public/assets/{reduce-C4NH7ua9.js → reduce-C8tvPXVb.js} +1 -1
- package/dist/public/assets/{requirementDiagram-MS252O5E-DySfGFfG.js → requirementDiagram-MS252O5E-DzkgPeTh.js} +1 -1
- package/dist/public/assets/{sankeyDiagram-XADWPNL6-CMU0uGgr.js → sankeyDiagram-XADWPNL6-BIuEcRVf.js} +1 -1
- package/dist/public/assets/{sequenceDiagram-FGHM5R23-BlnukeK1.js → sequenceDiagram-FGHM5R23-XhnGy5pc.js} +1 -1
- package/dist/public/assets/{src-BXk72DrU.js → src-BqeO7p9A.js} +1 -1
- package/dist/public/assets/{stateDiagram-FHFEXIEX-B7C4fJw1.js → stateDiagram-FHFEXIEX-lEHzf3FW.js} +1 -1
- package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-BsIimsLv.js +1 -0
- package/dist/public/assets/target-navigation-intent-DV20b6hl.js +1 -0
- package/dist/public/assets/{telemetry-impl-IWNN1g1D.js → telemetry-impl-DQsr_8J4.js} +2 -2
- package/dist/public/assets/{timeline-definition-GMOUNBTQ-DAcQtRlS.js → timeline-definition-GMOUNBTQ-_uHiIDjf.js} +1 -1
- package/dist/public/assets/{toggle-group-DaO2tdZq.js → toggle-group-CMlQ6Riv.js} +1 -1
- package/dist/public/assets/treeView-SZITEDCU-bf7fN5vg.js +1 -0
- package/dist/public/assets/treemap-W4RFUUIX-DeijdxYt.js +1 -0
- package/dist/public/assets/{typing-burst-detector-rlH8kimG.js → typing-burst-detector-g2N_ZxQ0.js} +2 -2
- package/dist/public/assets/{vennDiagram-DHZGUBPP-D5QpqXSc.js → vennDiagram-DHZGUBPP-BwneE_Sg.js} +1 -1
- package/dist/public/assets/wardley-RL74JXVD-XbGOizT8.js +1 -0
- package/dist/public/assets/{wardleyDiagram-NUSXRM2D-CV74dN2L.js → wardleyDiagram-NUSXRM2D-D1AodqH_.js} +1 -1
- package/dist/public/assets/{xychartDiagram-5P7HB3ND-VYAkLjyv.js → xychartDiagram-5P7HB3ND-9zuC0eMC.js} +1 -1
- package/dist/public/index.html +18 -19
- package/dist/{repair-launch-json-CIWa8qxg.mjs → repair-launch-json-DlEdkrKh.mjs} +2 -2
- package/dist/{repair-mcp-configs-2kPz8OcL.mjs → repair-mcp-configs-BHPoI1uy.mjs} +2 -2
- package/dist/{src-BxHt_W7H.mjs → src-I01t3f3s.mjs} +2 -2
- package/dist/start-Cd7Dm65u.mjs +3 -0
- package/dist/start-Ddvj38aH.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-0DGajs0S.mjs +0 -2
- package/dist/init-DJPy7j-l.mjs +0 -1
- package/dist/loader-5BoR7yfI.mjs +0 -1
- package/dist/preview-CS6d-INQ.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-D4mJve47.js +0 -2
- package/dist/public/assets/ConsentDialogBody-DmBVz-Q3.js +0 -2
- package/dist/public/assets/DocumentContext-DlKhIM1r.js +0 -52
- package/dist/public/assets/McpConsentDialogBody-nfOIAtwG.js +0 -1
- package/dist/public/assets/SettingsDialog-BmYi4srd.js +0 -11
- package/dist/public/assets/SourceEditor-FcRXzF2H.js +0 -2
- package/dist/public/assets/architecture-YZFGNWBL-ii1DMScC.js +0 -1
- package/dist/public/assets/channel-BsgewBDI.js +0 -1
- package/dist/public/assets/chunk-426QAEUC-b3iWz8H-.js +0 -1
- package/dist/public/assets/chunk-55IACEB6-DLoy8CmX.js +0 -1
- package/dist/public/assets/chunk-QZHKN3VN-XrJADtWP.js +0 -1
- package/dist/public/assets/classDiagram-6PBFFD2Q-Bt8hJVX9.js +0 -1
- package/dist/public/assets/classDiagram-v2-HSJHXN6E-BTPIteVB.js +0 -1
- package/dist/public/assets/clone-B_tH2FKO.js +0 -1
- package/dist/public/assets/config-validation-events-DYeWLZ7O.js +0 -10
- package/dist/public/assets/doc-hash-BZGAbwgw.js +0 -423
- package/dist/public/assets/gitGraph-7Q5UKJZL-CIz9LX1B.js +0 -1
- package/dist/public/assets/index-CNH2e6Vb.js +0 -1918
- package/dist/public/assets/index-DquyxBKM.css +0 -1
- package/dist/public/assets/info-OMHHGYJF-CIFsXa-y.js +0 -1
- package/dist/public/assets/isSymbol-CiN6ou2H.js +0 -1
- package/dist/public/assets/packet-4T2RLAQJ-BaGTVTK6.js +0 -1
- package/dist/public/assets/pie-ZZUOXDRM-BlBm3k_7.js +0 -1
- package/dist/public/assets/radar-PYXPWWZC-DcDFZeKR.js +0 -1
- package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-BjMTOSSV.js +0 -1
- package/dist/public/assets/target-navigation-intent-DHgrhl0F.js +0 -1
- package/dist/public/assets/tooltip-DS7NYbjB.js +0 -1
- package/dist/public/assets/treeView-SZITEDCU-DT6-aoa9.js +0 -1
- package/dist/public/assets/treemap-W4RFUUIX-JWBoWOdi.js +0 -1
- package/dist/public/assets/wardley-RL74JXVD-GxyzoOqN.js +0 -1
- package/dist/start-DeC-wai5.mjs +0 -1
- package/dist/start-f0mu1iQf.mjs +0 -3
- /package/dist/public/assets/{ActivityPanelDiffView-EaCFURAu.js → ActivityPanelDiffView-DwtPYJgT.js} +0 -0
- /package/dist/public/assets/{__vite-browser-external-mvD4HPu0.js → __vite-browser-external-CCyf2WTU.js} +0 -0
- /package/dist/public/assets/{array-o2rfyIz3.js → array-B4rubdDx.js} +0 -0
- /package/dist/public/assets/{colors-BbIH8S-B.js → colors-DTkp5rhC.js} +0 -0
- /package/dist/public/assets/{cytoscape.esm-xzkCxEpv.js → cytoscape.esm-lL68JtBB.js} +0 -0
- /package/dist/public/assets/{defaultLocale-D3xTVDt1.js → defaultLocale-VDKImYxX.js} +0 -0
- /package/dist/public/assets/{dist-D2RGH7XO.js → dist-8vOhMUNR.js} +0 -0
- /package/dist/public/assets/{dist-TlK-S7KL.js → dist-Df8SLnPf.js} +0 -0
- /package/dist/public/assets/{go-e6pdpn6U.js → go-D1ad2i41.js} +0 -0
- /package/dist/public/assets/{init-gbiKrEzm.js → init-B4uw1rya.js} +0 -0
- /package/dist/public/assets/{input-BHythLXk.js → input-jeOsxRL6.js} +0 -0
- /package/dist/public/assets/{isObjectLike-BNNgtFA6.js → isObjectLike-DkPsJ8ZC.js} +0 -0
- /package/dist/public/assets/{min-VayDM1tY.js → min-DTUJKQNu.js} +0 -0
- /package/dist/public/assets/{path-DFpIsaqN.js → path-flVp2dgl.js} +0 -0
- /package/dist/public/assets/{pdf-w2KBoLit.js → pdf-zy6UKR6F.js} +0 -0
- /package/dist/public/assets/{pdf.worker-BpRoOtgY.js → pdf.worker-CETvIAHl.js} +0 -0
- /package/dist/public/assets/{project-paths-hiY0fNWB.js → project-paths-CsGHlmFh.js} +0 -0
- /package/dist/public/assets/{rough.esm-BgPNbngg.js → rough.esm-pmFy2cex.js} +0 -0
- /package/dist/public/assets/{shell-BkCD5kyH.js → shell-FUK9YCOo.js} +0 -0
- /package/dist/public/assets/{src-BYmEUJ3I.js → src-CdWhPaRj.js} +0 -0
- /package/dist/public/assets/{stex-J8UMaf7u.js → stex-BUy0wSq4.js} +0 -0
- /package/dist/public/assets/{textarea-Cw3uXUVc.js → textarea-DECT2x7b.js} +0 -0
|
@@ -296,7 +296,8 @@ Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#pl
|
|
|
296
296
|
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
|
|
297
297
|
Please provide a chat model before proceeding with creating an answer session.
|
|
298
298
|
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
|
|
299
|
-
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function createError(e,...t){let S=Error(sprintf(errors[e]??`Unsupported Orama Error code: ${e}`,...t));return S.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(S),S}function formatElapsedTime(e){return{raw:Number(e),formatted:formatNanoseconds(e)}}function getDocumentIndexId(e){if(e.id){if(typeof e.id!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return uniqueId()}function validateSchema(e,t){for(let[S,w]of Object.entries(t)){let t=e[S];if(t!==void 0&&!(w===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(w===`enum`&&(typeof t==`string`||typeof t==`number`))){if(w===`enum[]`&&Array.isArray(t)){let e=t.length;for(let w=0;w<e;w++)if(typeof t[w]!=`string`&&typeof t[w]!=`number`)return S+`.`+w;continue}if(isVectorType(w)){let e=getVectorSize(w);if(!Array.isArray(t)||t.length!==e)throw createError(`INVALID_INPUT_VECTOR`,S,e,t.length);continue}if(isArrayType(w)){if(!Array.isArray(t))return S;let e=getInnerType(w),E=t.length;for(let w=0;w<E;w++)if(typeof t[w]!==e)return S+`.`+w;continue}if(typeof w==`object`){if(!t||typeof t!=`object`)return S;let e=validateSchema(t,w);if(e)return S+`.`+e;continue}if(typeof t!==w)return S}}}const IS_ARRAY_TYPE={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},INNER_TYPE={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function isGeoPointType(e){return e===`geopoint`}function isVectorType(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function isArrayType(e){return typeof e==`string`&&IS_ARRAY_TYPE[e]}function getInnerType(e){return INNER_TYPE[e]}function getVectorSize(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw createError(`INVALID_VECTOR_VALUE`,e);case t<=0:throw createError(`INVALID_VECTOR_SIZE`,e);default:return t}}function createInternalDocumentIDStore(){return{idToInternalId:new Map,internalIdToId:[],save:save$4,load:load$4}}function save$4(e){return{internalIdToId:e.internalIdToId}}function load$4(e,t){let{internalIdToId:S}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let w=S.length;for(let t=0;t<w;t++){let w=S[t];e.internalDocumentIDStore.idToInternalId.set(w,t+1),e.internalDocumentIDStore.internalIdToId.push(w)}}function getInternalDocumentId(e,t){if(typeof t==`string`){let S=e.idToInternalId.get(t);if(S)return S;let w=e.idToInternalId.size+1;return e.idToInternalId.set(t,w),e.internalIdToId.push(t),w}return t>e.internalIdToId.length?getInternalDocumentId(e,t.toString()):t}function getDocumentIdFromInternalId(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function create$13(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function get(e,t){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t);return e.docs[S]}function getMultiple(e,t){let S=t.length,w=Array.from({length:S});for(let E=0;E<S;E++){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t[E]);w[E]=e.docs[S]}return w}function getAll(e){return e.docs}function store(e,t,S,w){return e.docs[S]===void 0?(e.docs[S]=w,e.count++,!0):!1}function remove$2(e,t){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t);return e.docs[S]===void 0?!1:(delete e.docs[S],e.count--,!0)}function count$1(e){return e.count}function load$3(e,t){let S=t;return{docs:S.docs,count:S.count,sharedInternalDocumentStore:e}}function save$3(e){return{docs:e.docs,count:e.count}}function createDocumentsStore(){return{create:create$13,get,getMultiple,getAll,store,remove:remove$2,count:count$1,load:load$3,save:save$3}}const AVAILABLE_PLUGIN_HOOKS=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function getAllPluginsByHook(e,t){let S=[],w=e.plugins?.length;if(!w)return S;for(let E=0;E<w;E++)try{let w=e.plugins[E];typeof w[t]==`function`&&S.push(w[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),createError(`PLUGIN_CRASHED`)}return S}const OBJECT_COMPONENTS=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],FUNCTION_COMPONENTS=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function runSingleHook(e,t,S,w){if(e.some(isAsyncFunction))return(async()=>{for(let E of e)await E(t,S,w)})();for(let E of e)E(t,S,w)}function runMultipleHook(e,t,S){if(e.some(isAsyncFunction))return(async()=>{for(let w of e)await w(t,S)})();for(let w of e)w(t,S)}function runAfterSearch(e,t,S,w,E){if(e.some(isAsyncFunction))return(async()=>{for(let D of e)await D(t,S,w,E)})();for(let D of e)D(t,S,w,E)}function runBeforeSearch(e,t,S,w){if(e.some(isAsyncFunction))return(async()=>{for(let E of e)await E(t,S,w)})();for(let E of e)E(t,S,w)}function runAfterCreate(e,t){if(e.some(isAsyncFunction))return(async()=>{for(let S of e)await S(t)})();for(let S of e)S(t)}var AVLNode=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let S=new e(t.k,t.v);return S.l=t.l?e.fromJSON(t.l):null,S.r=t.r?e.fromJSON(t.r):null,S.h=t.h,S}},AVLTree=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new AVLNode(e,t))}insert(e,t,S=1e3){this.root=this.insertNode(this.root,e,t,S)}insertMultiple(e,t,S=1e3){for(let w of t)this.insert(e,w,S)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let S=new e;return S.root=t.root?AVLNode.fromJSON(t.root):null,S.insertCount=t.insertCount||0,S}insertNode(e,t,S,w){if(e===null)return new AVLNode(t,[S]);let E=[],D=e,O=null;for(;D!==null;)if(E.push({parent:O,node:D}),t<D.k)if(D.l===null){D.l=new AVLNode(t,[S]),E.push({parent:D,node:D.l});break}else O=D,D=D.l;else if(t>D.k)if(D.r===null){D.r=new AVLNode(t,[S]),E.push({parent:D,node:D.r});break}else O=D,D=D.r;else return D.v.add(S),e;let k=!1;this.insertCount++%w===0&&(k=!0);for(let t=E.length-1;t>=0;t--){let{parent:S,node:w}=E[t];if(w.updateHeight(),k){let t=this.rebalanceNode(w);S?S.l===w?S.l=t:S.r===w&&(S.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],S=this.root;for(;S||t.length>0;){for(;S;)t.push(S),S=S.l;S=t.pop(),e++,S=S.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),S=t.getBalanceFactor();if(Math.abs(S)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let S=this.findNodeByKey(e);S&&(S.v.size===1?this.root=this.removeNode(this.root,e):S.v=new Set([...S.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let S=[],w=e;for(;w!==null&&w.k!==t;)S.push(w),w=t<w.k?w.l:w.r;if(w===null)return e;if(w.l===null||w.r===null){let t=w.l?w.l:w.r;if(S.length===0)e=t;else{let e=S[S.length-1];e.l===w?e.l=t:e.r=t}}else{let e=w,t=w.r;for(;t.l!==null;)e=t,t=t.l;w.k=t.k,w.v=t.v,e.l===t?e.l=t.r:e.r=t.r,w=e}S.push(w);for(let t=S.length-1;t>=0;t--){let w=S[t];w.updateHeight();let E=this.rebalanceNode(w);if(t>0){let e=S[t-1];e.l===w?e.l=E:e.r===w&&(e.r=E)}else e=E}return e}rangeSearch(e,t){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.l;if(E=w.pop(),E.k>=e&&E.k<=t)for(let e of E.v)S.add(e);if(E.k>t)break;E=E.r}return S}greaterThan(e,t=!1){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.r;if(E=w.pop(),t&&E.k>=e||!t&&E.k>e)for(let e of E.v)S.add(e);else if(E.k<=e)break;E=E.l}return S}lessThan(e,t=!1){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.l;if(E=w.pop(),t&&E.k<=e||!t&&E.k<e)for(let e of E.v)S.add(e);else if(E.k>e)break;E=E.r}return S}},FlatTree=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let S=this.numberToDocumentId.get(t);S&&(S.delete(e),S.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let S=t[0];switch(S){case`eq`:{let t=e[S],w=this.numberToDocumentId.get(t);return w?Array.from(w):[]}case`in`:{let t=e[S],w=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)w.add(e)}return Array.from(w)}case`nin`:{let t=new Set(e[S]),w=new Set;for(let[e,S]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of S)w.add(e);return Array.from(w)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let S=t[0];switch(S){case`containsAll`:{let t=e[S].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let w=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(w)}case`containsAny`:{let t=e[S].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let w=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(w)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let S=new e;for(let[e,w]of t.numberToDocumentId)S.numberToDocumentId.set(e,new Set(w));return S}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function _boundedLevenshtein(e,t,S){if(S<0)return-1;if(e===t)return 0;let w=e.length,E=t.length;if(w===0)return E<=S?E:-1;if(E===0)return w<=S?w:-1;let D=Math.abs(w-E);if(e.startsWith(t))return D<=S?D:-1;if(t.startsWith(e))return 0;if(D>S)return-1;let O=[];for(let e=0;e<=w;e++){O[e]=[e];for(let t=1;t<=E;t++)O[e][t]=e===0?t:0}for(let D=1;D<=w;D++){let w=1/0;for(let S=1;S<=E;S++)e[D-1]===t[S-1]?O[D][S]=O[D-1][S-1]:O[D][S]=Math.min(O[D-1][S]+1,O[D][S-1]+1,O[D-1][S-1]+1),w=Math.min(w,O[D][S]);if(w>S)return-1}return O[w][E]<=S?O[w][E]:-1}function syncBoundedLevenshtein(e,t,S){let w=_boundedLevenshtein(e,t,S);return{distance:w,isBounded:w>=0}}var RadixNode=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,S){this.k=e,this.s=t,this.e=S}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,S,w){let E=[this];for(;E.length>0;){let D=E.pop();if(D.e){let{w:E,d:O}=D;if(S&&E!==t)continue;if(getOwnProperty(e,E)!==null)if(w)if(Math.abs(t.length-E.length)<=w&&syncBoundedLevenshtein(t,E,w).isBounded)e[E]=[];else continue;else e[E]=[];if(getOwnProperty(e,E)!=null&&O.size>0){let t=e[E];for(let e of O)t.includes(e)||t.push(e)}}D.c.size>0&&E.push(...D.c.values())}return e}insert(t,S){let w=this,E=0,D=t.length;for(;E<D;){let O=t[E],k=w.c.get(O);if(k){let O=k.s,j=O.length,F=0;for(;F<j&&E+F<D&&O[F]===t[E+F];)F++;if(F===j){if(w=k,E+=F,E===D){k.e||=!0,k.addDocument(S);return}continue}let L=O.slice(0,F),B=O.slice(F),H=t.slice(E+F),q=new e(L[0],L,!1);if(w.c.set(L[0],q),q.updateParent(w),k.s=B,k.k=B[0],q.c.set(B[0],k),k.updateParent(q),H){let t=new e(H[0],H,!0);t.addDocument(S),q.c.set(H[0],t),t.updateParent(q)}else q.e=!0,q.addDocument(S);return}else{let D=new e(O,t.slice(E),!0);D.addDocument(S),w.c.set(O,D),D.updateParent(w);return}}w.e||=!0,w.addDocument(S)}_findLevenshtein(e,t,S,w,E){let D=[{node:this,index:t,tolerance:S}];for(;D.length>0;){let{node:t,index:S,tolerance:O}=D.pop();if(t.w.startsWith(e)){t.findAllWords(E,e,!1,0);continue}if(O<0)continue;if(t.e){let{w:S,d:D}=t;if(S&&(syncBoundedLevenshtein(e,S,w).isBounded&&(E[S]=[]),getOwnProperty(E,S)!==void 0&&D.size>0)){let e=new Set(E[S]);for(let t of D)e.add(t);E[S]=Array.from(e)}}if(S>=e.length)continue;let k=e[S];if(t.c.has(k)){let e=t.c.get(k);D.push({node:e,index:S+1,tolerance:O})}D.push({node:t,index:S+1,tolerance:O-1});for(let[e,w]of t.c)D.push({node:w,index:S,tolerance:O-1}),e!==k&&D.push({node:w,index:S+1,tolerance:O-1})}}find(e){let{term:t,exact:S,tolerance:w}=e;if(w&&!S){let e={};return this._findLevenshtein(t,0,w,w,e),e}else{let e=this,E=0,D=t.length;for(;E<D;){let O=t[E],k=e.c.get(O);if(k){let O=k.s,j=O.length,F=0;for(;F<j&&E+F<D&&O[F]===t[E+F];)F++;if(F===j)e=k,E+=F;else if(E+F===D)if(F===D-E){if(S)return{};{let e={};return k.findAllWords(e,t,S,w),e}}else return{};else return{}}else return{}}let O={};return e.findAllWords(O,t,S,w),O}}contains(e){let t=this,S=0,w=e.length;for(;S<w;){let E=e[S],D=t.c.get(E);if(D){let E=D.s,O=E.length,k=0;for(;k<O&&S+k<w&&E[k]===e[S+k];)k++;if(k<O)return!1;S+=O,t=D}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,S=e.length,w=[];for(let E=0;E<S;E++){let S=e[E];if(t.c.has(S)){let e=t.c.get(S);w.push({parent:t,character:S}),E+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;w.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:S}=w.pop();e.c.delete(S),t=e}return!0}removeDocumentByWord(e,t,S=!0){if(!e)return!0;let w=this,E=e.length;for(let D=0;D<E;D++){let E=e[D];if(w.c.has(E)){let O=w.c.get(E);D+=O.s.length-1,w=O,S&&w.w!==e||w.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let S=Math.min(e.length,t.length),w=0;for(;w<S&&e.charCodeAt(w)===t.charCodeAt(w);)w++;return e.slice(0,w)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let S=new e(t.k,t.s,t.e);return S.w=t.w,S.d=new Set(t.d),S.c=new Map(t?.c?.map(([t,S])=>[t,e.fromJSON(S)])||[]),S}},RadixTree=class e extends RadixNode{constructor(){super(``,``,!1)}static fromJSON(t){let S=new e;return S.w=t.w,S.s=t.s,S.e=t.e,S.k=t.k,S.d=new Set(t.d),S.c=new Map(t?.c?.map(([e,t])=>[e,RadixNode.fromJSON(t)])||[]),S}toJSON(){return super.toJSON()}};const K$1=2,EARTH_RADIUS=6371e3;var BKDNode=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,S=null){let w=new e(t.point,t.docIDs);return w.parent=S,t.left&&(w.left=e.fromJSON(t.left,w)),t.right&&(w.right=e.fromJSON(t.right,w)),w}},BKDTree=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let S=this.getPointKey(e),w=this.nodeMap.get(S);if(w){t.forEach(e=>w.docIDs.add(e));return}let E=new BKDNode(e,t);if(this.nodeMap.set(S,E),this.root==null){this.root=E;return}let D=this.root,O=0;for(;;){if(O%K$1===0)if(e.lon<D.point.lon){if(D.left==null){D.left=E,E.parent=D;return}D=D.left}else{if(D.right==null){D.right=E,E.parent=D;return}D=D.right}else if(e.lat<D.point.lat){if(D.left==null){D.left=E,E.parent=D;return}D=D.left}else{if(D.right==null){D.right=E,E.parent=D;return}D=D.right}O++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),S=this.nodeMap.get(t);return S?Array.from(S.docIDs):null}removeDocByID(e,t){let S=this.getPointKey(e),w=this.nodeMap.get(S);w&&(w.docIDs.delete(t),w.docIDs.size===0&&(this.nodeMap.delete(S),this.deleteNode(w)))}deleteNode(e){let t=e.parent,S=e.left?e.left:e.right;S&&(S.parent=t),t?t.left===e?t.left=S:t.right===e&&(t.right=S):(this.root=S,this.root&&(this.root.parent=null))}searchByRadius(t,S,w=!0,E=`asc`,D=!1){let O=D?e.vincentyDistance:e.haversineDistance,k=[{node:this.root,depth:0}],j=[];for(;k.length>0;){let{node:e,depth:E}=k.pop();if(e==null)continue;let D=O(t,e.point);(w?D<=S:D>S)&&j.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&k.push({node:e.left,depth:E+1}),e.right!=null&&k.push({node:e.right,depth:E+1})}return E&&j.sort((e,S)=>{let w=O(t,e.point),D=O(t,S.point);return E.toLowerCase()===`asc`?w-D:D-w}),j}searchByPolygon(t,S=!0,w=null,E=!1){let D=[{node:this.root,depth:0}],O=[];for(;D.length>0;){let{node:w,depth:E}=D.pop();if(w==null)continue;w.left!=null&&D.push({node:w.left,depth:E+1}),w.right!=null&&D.push({node:w.right,depth:E+1});let k=e.isPointInPolygon(t,w.point);(k&&S||!k&&!S)&&O.push({point:w.point,docIDs:Array.from(w.docIDs)})}let k=e.calculatePolygonCentroid(t);if(w){let t=E?e.vincentyDistance:e.haversineDistance;O.sort((e,S)=>{let E=t(k,e.point),D=t(k,S.point);return w.toLowerCase()===`asc`?E-D:D-E})}return O}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let S=new e;return t.root&&(S.root=BKDNode.fromJSON(t.root),S.buildNodeMap(S.root)),S}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,S=0,w=0,E=e.length;for(let D=0,O=E-1;D<E;O=D++){let E=e[D].lon,k=e[D].lat,j=e[O].lon,F=e[O].lat,L=E*F-j*k;t+=L,S+=(E+j)*L,w+=(k+F)*L}t/=2;let D=6*t;return S/=D,w/=D,{lon:S,lat:w}}static isPointInPolygon(e,t){let S=!1,w=t.lon,E=t.lat,D=e.length;for(let t=0,O=D-1;t<D;O=t++){let D=e[t].lon,k=e[t].lat,j=e[O].lon,F=e[O].lat;k>E!=F>E&&w<(j-D)*(E-k)/(F-k)+D&&(S=!S)}return S}static haversineDistance(e,t){let S=Math.PI/180,w=e.lat*S,E=t.lat*S,D=(t.lat-e.lat)*S,O=(t.lon-e.lon)*S,k=Math.sin(D/2)*Math.sin(D/2)+Math.cos(w)*Math.cos(E)*Math.sin(O/2)*Math.sin(O/2);return EARTH_RADIUS*(2*Math.atan2(Math.sqrt(k),Math.sqrt(1-k)))}static vincentyDistance(e,t){let S=6378137,w=1/298.257223563,E=(1-w)*S,D=Math.PI/180,O=e.lat*D,k=t.lat*D,j=(t.lon-e.lon)*D,F=Math.atan((1-w)*Math.tan(O)),L=Math.atan((1-w)*Math.tan(k)),B=Math.sin(F),H=Math.cos(F),q=Math.sin(L),J=Math.cos(L),Y=j,ee,te=1e3,ne,ae,oe,se,ce,ue;do{let e=Math.sin(Y),t=Math.cos(Y);if(ne=Math.sqrt(J*e*(J*e)+(H*q-B*J*t)*(H*q-B*J*t)),ne===0)return 0;ae=B*q+H*J*t,oe=Math.atan2(ne,ae),se=H*J*e/ne,ce=1-se*se,ue=ae-2*B*q/ce,isNaN(ue)&&(ue=0);let S=w/16*ce*(4+w*(4-3*ce));ee=Y,Y=j+(1-S)*w*se*(oe+S*ne*(ue+S*ae*(-1+2*ue*ue)))}while(Math.abs(Y-ee)>1e-12&&--te>0);if(te===0)return NaN;let de=ce*(S*S-E*E)/(E*E),fe=1+de/16384*(4096+de*(-768+de*(320-175*de))),me=de/1024*(256+de*(-128+de*(74-47*de))),ge=me*ne*(ue+me/4*(ae*(-1+2*ue*ue)-me/6*ue*(-3+4*ne*ne)*(-3+4*ue*ue)));return E*fe*(oe-ge)}},BoolNode=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let S=new e;return S.true=new Set(t.true),S.false=new Set(t.false),S}};function BM25(e,t,S,w,E,{k:D,b:O,d:k}){return Math.log(1+(S-t+.5)/(t+.5))*(k+e*(D+1))/(e+D*(1-O+O*w/E))}const DEFAULT_SIMILARITY=.8;var VectorIndex=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let S=getMagnitude(t,this.size);this.vectors.set(e,[S,t])}remove(e){this.vectors.delete(e)}find(e,t,S){return e instanceof Float32Array||(e=new Float32Array(e)),findSimilarVectors(e,S,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[S,w]]of this.vectors)e.push([t,[S,Array.from(w)]]);return{size:this.size,vectors:e}}static fromJSON(t){let S=t,w=new e(S.size);for(let[e,[t,E]]of S.vectors)w.vectors.set(e,[t,new Float32Array(E)]);return w}};function getMagnitude(e,t){let S=0;for(let w=0;w<t;w++)S+=e[w]*e[w];return Math.sqrt(S)}function findSimilarVectors(e,t,S,w,E){let D=getMagnitude(e,w),O=[],k=t||S.keys();for(let t of k){let k=S.get(t);if(!k)continue;let j=k[0],F=k[1],L=0;for(let t=0;t<w;t++)L+=e[t]*F[t];let B=L/(D*j);B>=E&&O.push([t,B])}return O}function insertDocumentScoreParameters(e,t,S,w,E){let D=getInternalDocumentId(e.sharedInternalDocumentStore,S);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(E-1)+w.length)/E,e.fieldLengths[t][D]=w.length,e.frequencies[t][D]={}}function insertTokenScoreParameters(e,t,S,w,E){let D=0;for(let e of w)e===E&&D++;let O=getInternalDocumentId(e.sharedInternalDocumentStore,S),k=D/w.length;e.frequencies[t][O][E]=k,E in e.tokenOccurrences[t]||(e.tokenOccurrences[t][E]=0),e.tokenOccurrences[t][E]=(e.tokenOccurrences[t][E]??0)+1}function removeDocumentScoreParameters(e,t,S,w){let E=getInternalDocumentId(e.sharedInternalDocumentStore,S);w>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*w-e.fieldLengths[t][E])/(w-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][E]=void 0,e.frequencies[t][E]=void 0}function removeTokenScoreParameters(e,t,S){e.tokenOccurrences[t][S]--}function create$12(e,t,S,w,E=``){w||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[D,O]of Object.entries(S)){let S=`${E}${E?`.`:``}${D}`;if(typeof O==`object`&&!Array.isArray(O)){create$12(e,t,O,w,S);continue}if(isVectorType(O))w.searchableProperties.push(S),w.searchablePropertiesWithTypes[S]=O,w.vectorIndexes[S]={type:`Vector`,node:new VectorIndex(getVectorSize(O)),isArray:!1};else{let e=/\[/.test(O);switch(O){case`boolean`:case`boolean[]`:w.indexes[S]={type:`Bool`,node:new BoolNode,isArray:e};break;case`number`:case`number[]`:w.indexes[S]={type:`AVL`,node:new AVLTree(0,[]),isArray:e};break;case`string`:case`string[]`:w.indexes[S]={type:`Radix`,node:new RadixTree,isArray:e},w.avgFieldLength[S]=0,w.frequencies[S]={},w.tokenOccurrences[S]={},w.fieldLengths[S]={};break;case`enum`:case`enum[]`:w.indexes[S]={type:`Flat`,node:new FlatTree,isArray:e};break;case`geopoint`:w.indexes[S]={type:`BKD`,node:new BKDTree,isArray:e};break;default:throw createError(`INVALID_SCHEMA_TYPE`,Array.isArray(O)?`array`:O,S)}w.searchableProperties.push(S),w.searchablePropertiesWithTypes[S]=O}}return w}function insertScalarBuilder(e,t,S,w,E,D,O,k){return j=>{let{type:F,node:L}=t.indexes[S];switch(F){case`Bool`:L[j?`true`:`false`].add(w);break;case`AVL`:{let e=k?.avlRebalanceThreshold??1;L.insert(j,w,e);break}case`Radix`:{let k=D.tokenize(j,E,S,!1);e.insertDocumentScoreParameters(t,S,w,k,O);for(let E of k)e.insertTokenScoreParameters(t,S,w,k,E),L.insert(E,w);break}case`Flat`:L.insert(j,w);break;case`BKD`:L.insert(j,[w]);break}}}function insert$2(e,t,S,w,E,D,O,k,j,F,L){if(isVectorType(O))return insertVector(t,S,D,w,E);let B=insertScalarBuilder(e,t,S,E,k,j,F,L);if(!isArrayType(O))return B(D);let H=D,q=H.length;for(let e=0;e<q;e++)B(H[e])}function insertVector(e,t,S,w,E){e.vectorIndexes[t].node.add(E,S)}function removeScalar(e,t,S,w,E,D,O,k,j,F){if(isVectorType(O))return t.vectorIndexes[S].node.remove(E),!0;let{type:L,node:B}=t.indexes[S];switch(L){case`AVL`:return B.removeDocument(D,E),!0;case`Bool`:return B[D?`true`:`false`].delete(E),!0;case`Radix`:{let O=j.tokenize(D,k,S);e.removeDocumentScoreParameters(t,S,w,F);for(let w of O)e.removeTokenScoreParameters(t,S,w),B.removeDocumentByWord(w,E);return!0}case`Flat`:return B.removeDocument(E,D),!0;case`BKD`:return B.removeDocByID(D,E),!1}}function remove$1(e,t,S,w,E,D,O,k,j,F){if(!isArrayType(O))return removeScalar(e,t,S,w,E,D,O,k,j,F);let L=getInnerType(O),B=D,H=B.length;for(let D=0;D<H;D++)removeScalar(e,t,S,w,E,B[D],L,k,j,F);return!0}function calculateResultScores(e,t,S,w,E,D,O,k,j,F){let L=Array.from(w),B=e.avgFieldLength[t],H=e.fieldLengths[t],q=e.tokenOccurrences[t],J=e.frequencies[t],Y=typeof q[S]==`number`?q[S]??0:0,ee=L.length;for(let e=0;e<ee;e++){let w=L[e];if(j&&!j.has(w))continue;F.has(w)||F.set(w,new Map);let q=F.get(w);q.set(t,(q.get(t)||0)+1);let ee=BM25(J?.[w]?.[S]??0,Y,E,H[w],B,D);O.has(w)?O.set(w,O.get(w)+ee*k):O.set(w,ee*k)}}function search$1(e,t,S,w,E,D,O,k,j,F,L,B=0){let H=S.tokenize(t,w),q=H.length||1,J=new Map,Y=new Map,ee=new Map;for(let S of E){if(!(S in e.indexes))continue;let w=e.indexes[S],{type:E}=w;if(E!==`Radix`)throw createError(`WRONG_SEARCH_PROPERTY_TYPE`,S);let B=k[S]??1;if(B<=0)throw createError(`INVALID_BOOST_VALUE`,B);H.length===0&&!t&&H.push(``);let q=H.length;for(let t=0;t<q;t++){let E=H[t],k=w.node.find({term:E,exact:D,tolerance:O}),q=Object.keys(k);q.length>0&&Y.set(E,!0);let te=q.length;for(let t=0;t<te;t++){let w=q[t],E=k[w];calculateResultScores(e,S,w,E,F,j,ee,B,L,J)}}}let te=Array.from(ee.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(te.length===0)return[];if(B===1)return te;if(B===0){if(q===1)return te;for(let e of H)if(!Y.get(e))return[];return te.filter(([e])=>{let t=J.get(e);return t?Array.from(t.values()).some(e=>e===q):!1})}let ne=te.filter(([e])=>{let t=J.get(e);return t?Array.from(t.values()).some(e=>e===q):!1});if(ne.length>0){let e=te.filter(([e])=>!ne.some(([t])=>t===e)),t=Math.ceil(e.length*B);return[...ne,...e.slice(0,t)]}return te}function searchByWhereClause(e,t,S,w){if(`and`in S&&S.and&&Array.isArray(S.and)){let E=S.and;return E.length===0?new Set:setIntersection(...E.map(S=>searchByWhereClause(e,t,S,w)))}if(`or`in S&&S.or&&Array.isArray(S.or)){let E=S.or;return E.length===0?new Set:E.map(S=>searchByWhereClause(e,t,S,w)).reduce((e,t)=>setUnion(e,t),new Set)}if(`not`in S&&S.not){let E=S.not,D=new Set,O=e.sharedInternalDocumentStore;for(let e=1;e<=O.internalIdToId.length;e++)D.add(e);return setDifference(D,searchByWhereClause(e,t,E,w))}let E=Object.keys(S),D=E.reduce((e,t)=>({[t]:new Set,...e}),{});for(let O of E){let E=S[O];if(e.indexes[O]===void 0)throw createError(`UNKNOWN_FILTER_PROPERTY`,O);let{node:k,type:j,isArray:F}=e.indexes[O];if(j===`Bool`){let e=k,t=E?e.true:e.false;D[O]=setUnion(D[O],t);continue}if(j===`BKD`){let e;if(`radius`in E)e=`radius`;else if(`polygon`in E)e=`polygon`;else throw Error(`Invalid operation ${E}`);if(e===`radius`){let{value:t,coordinates:S,unit:w=`m`,inside:j=!0,highPrecision:F=!1}=E[e],L=convertDistanceToMeters(t,w),B=k.searchByRadius(S,L,j,void 0,F);D[O]=addGeoResult(D[O],B)}else{let{coordinates:t,inside:S=!0,highPrecision:w=!1}=E[e],j=k.searchByPolygon(t,S,void 0,w);D[O]=addGeoResult(D[O],j)}continue}if(j===`Radix`&&(typeof E==`string`||Array.isArray(E))){for(let e of[E].flat()){let S=t.tokenize(e,w,O);for(let e of S){let t=k.find({term:e,exact:!0});D[O]=addFindResult(D[O],t)}}continue}let L=Object.keys(E);if(L.length>1)throw createError(`INVALID_FILTER_OPERATION`,L.length);if(j===`Flat`){let e=new Set(F?k.filterArr(E):k.filter(E));D[O]=setUnion(D[O],e);continue}if(j===`AVL`){let e=L[0],t=E[e],S;switch(e){case`gt`:S=k.greaterThan(t,!1);break;case`gte`:S=k.greaterThan(t,!0);break;case`lt`:S=k.lessThan(t,!1);break;case`lte`:S=k.lessThan(t,!0);break;case`eq`:S=k.find(t)??new Set;break;case`between`:{let[e,w]=t;S=k.rangeSearch(e,w);break}default:throw createError(`INVALID_FILTER_OPERATION`,e)}D[O]=setUnion(D[O],S)}}return setIntersection(...Object.values(D))}function getSearchableProperties(e){return e.searchableProperties}function getSearchablePropertiesWithTypes(e){return e.searchablePropertiesWithTypes}function load$2(e,t){let{indexes:S,vectorIndexes:w,searchableProperties:E,searchablePropertiesWithTypes:D,frequencies:O,tokenOccurrences:k,avgFieldLength:j,fieldLengths:F}=t,L={},B={};for(let e of Object.keys(S)){let{node:t,type:w,isArray:E}=S[e];switch(w){case`Radix`:L[e]={type:`Radix`,node:RadixTree.fromJSON(t),isArray:E};break;case`Flat`:L[e]={type:`Flat`,node:FlatTree.fromJSON(t),isArray:E};break;case`AVL`:L[e]={type:`AVL`,node:AVLTree.fromJSON(t),isArray:E};break;case`BKD`:L[e]={type:`BKD`,node:BKDTree.fromJSON(t),isArray:E};break;case`Bool`:L[e]={type:`Bool`,node:BoolNode.fromJSON(t),isArray:E};break;default:L[e]=S[e]}}for(let e of Object.keys(w))B[e]={type:`Vector`,isArray:!1,node:VectorIndex.fromJSON(w[e])};return{sharedInternalDocumentStore:e,indexes:L,vectorIndexes:B,searchableProperties:E,searchablePropertiesWithTypes:D,frequencies:O,tokenOccurrences:k,avgFieldLength:j,fieldLengths:F}}function save$2(e){let{indexes:t,vectorIndexes:S,searchableProperties:w,searchablePropertiesWithTypes:E,frequencies:D,tokenOccurrences:O,avgFieldLength:k,fieldLengths:j}=e,F={};for(let e of Object.keys(S))F[e]=S[e].node.toJSON();let L={};for(let e of Object.keys(t)){let{type:S,node:w,isArray:E}=t[e];S===`Flat`||S===`Radix`||S===`AVL`||S===`BKD`||S===`Bool`?L[e]={type:S,node:w.toJSON(),isArray:E}:(L[e]=t[e],L[e].node=L[e].node.toJSON())}return{indexes:L,vectorIndexes:F,searchableProperties:w,searchablePropertiesWithTypes:E,frequencies:D,tokenOccurrences:O,avgFieldLength:k,fieldLengths:j}}function createIndex(){return{create:create$12,insert:insert$2,remove:remove$1,insertDocumentScoreParameters,insertTokenScoreParameters,removeDocumentScoreParameters,removeTokenScoreParameters,calculateResultScores,search:search$1,searchByWhereClause,getSearchableProperties,getSearchablePropertiesWithTypes,load:load$2,save:save$2}}function addGeoResult(e,t){e||=new Set;let S=t.length;for(let w=0;w<S;w++){let S=t[w].docIDs,E=S.length;for(let t=0;t<E;t++)e.add(S[t])}return e}function createGeoTokenScores(e,t,S=!1){let w=S?BKDTree.vincentyDistance:BKDTree.haversineDistance,E=[],D=[];for(let{point:S}of e)D.push(w(t,S));let O=Math.max(...D),k=0;for(let{docIDs:t}of e){let e=O-D[k]+1;for(let S of t)E.push([S,e]);k++}return E.sort((e,t)=>t[1]-e[1]),E}function isGeosearchOnlyQuery(e,t){let S=Object.keys(e);if(S.length!==1)return{isGeoOnly:!1};let w=S[0],E=e[w];if(t.indexes[w]===void 0)return{isGeoOnly:!1};let{type:D}=t.indexes[w];return D===`BKD`&&E&&(`radius`in E||`polygon`in E)?{isGeoOnly:!0,geoProperty:w,geoOperation:E}:{isGeoOnly:!1}}function searchByGeoWhereClause(e,t){let S=e,w=isGeosearchOnlyQuery(t,S);if(!w.isGeoOnly||!w.geoProperty||!w.geoOperation)return null;let{node:E}=S.indexes[w.geoProperty],D=w.geoOperation,O=E,k;if(`radius`in D){let{value:e,coordinates:t,unit:S=`m`,inside:w=!0,highPrecision:E=!1}=D.radius,j=t,F=convertDistanceToMeters(e,S);return k=O.searchByRadius(j,F,w,`asc`,E),createGeoTokenScores(k,j,E)}else if(`polygon`in D){let{coordinates:e,inside:t=!0,highPrecision:S=!1}=D.polygon;k=O.searchByPolygon(e,t,`asc`,S);let w=BKDTree.calculatePolygonCentroid(e);return createGeoTokenScores(k,w,S)}return null}function addFindResult(e,t){e||=new Set;let S=Object.keys(t),w=S.length;for(let E=0;E<w;E++){let w=t[S[E]],D=w.length;for(let t=0;t<D;t++)e.add(w[t])}return e}function innerCreate(e,t,S,w,E){let D={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[O,k]of Object.entries(S)){let S=`${E}${E?`.`:``}${O}`;if(!w.includes(S)){if(typeof k==`object`&&!Array.isArray(k)){let E=innerCreate(e,t,k,w,S);safeArrayPush(D.sortableProperties,E.sortableProperties),D.sorts={...D.sorts,...E.sorts},D.sortablePropertiesWithTypes={...D.sortablePropertiesWithTypes,...E.sortablePropertiesWithTypes};continue}if(!isVectorType(k))switch(k){case`boolean`:case`number`:case`string`:D.sortableProperties.push(S),D.sortablePropertiesWithTypes[S]=k,D.sorts[S]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:k};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw createError(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(k)?`array`:k,S)}}}return D}function create$11(e,t,S,w){return w?.enabled===!1?{disabled:!0}:innerCreate(e,t,S,(w||{}).unsortableProperties||[],``)}function insert$1(e,t,S,w){if(!e.enabled)return;e.isSorted=!1;let E=getInternalDocumentId(e.sharedInternalDocumentStore,S),D=e.sorts[t];D.orderedDocsToRemove.has(E)&&ensureOrderedDocsAreDeletedByProperty(e,t),D.docs.set(E,D.orderedDocs.length),D.orderedDocs.push([E,w])}function ensureIsSorted(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let S of t)ensurePropertyIsSorted(e,S);e.isSorted=!0}function stringSort(e,t,S){return t[1].localeCompare(S[1],getLocale(e))}function numberSort(e,t){return e[1]-t[1]}function booleanSort(e,t){return t[1]?-1:1}function ensurePropertyIsSorted(e,t){let S=e.sorts[t],w;switch(S.type){case`string`:w=stringSort.bind(null,e.language);break;case`number`:w=numberSort.bind(null);break;case`boolean`:w=booleanSort.bind(null);break}S.orderedDocs.sort(w);let E=S.orderedDocs.length;for(let e=0;e<E;e++){let t=S.orderedDocs[e][0];S.docs.set(t,e)}}function ensureOrderedDocsAreDeleted(e){let t=Object.keys(e.sorts);for(let S of t)ensureOrderedDocsAreDeletedByProperty(e,S)}function ensureOrderedDocsAreDeletedByProperty(e,t){let S=e.sorts[t];S.orderedDocsToRemove.size&&(S.orderedDocs=S.orderedDocs.filter(e=>!S.orderedDocsToRemove.has(e[0])),S.orderedDocsToRemove.clear())}function remove(e,t,S){if(!e.enabled)return;let w=e.sorts[t],E=getInternalDocumentId(e.sharedInternalDocumentStore,S);w.docs.get(E)&&(w.docs.delete(E),w.orderedDocsToRemove.set(E,!0))}function sortBy(e,t,S){if(!e.enabled)throw createError(`SORT_DISABLED`);let w=S.property,E=S.order===`DESC`,D=e.sorts[w];if(!D)throw createError(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,w,e.sortableProperties.join(`, `));return ensureOrderedDocsAreDeletedByProperty(e,w),ensureIsSorted(e),t.sort((t,S)=>{let w=D.docs.get(getInternalDocumentId(e.sharedInternalDocumentStore,t[0])),O=D.docs.get(getInternalDocumentId(e.sharedInternalDocumentStore,S[0])),k=w!==void 0,j=O!==void 0;return!k&&!j?0:k?j?E?O-w:w-O:-1:1}),t}function getSortableProperties(e){return e.enabled?e.sortableProperties:[]}function getSortablePropertiesWithTypes(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function load$1(e,t){let S=t;if(!S.enabled)return{enabled:!1};let w=Object.keys(S.sorts).reduce((e,t)=>{let{docs:w,orderedDocs:E,type:D}=S.sorts[t];return e[t]={docs:new Map(Object.entries(w).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:E,type:D},e},{});return{sharedInternalDocumentStore:e,language:S.language,sortableProperties:S.sortableProperties,sortablePropertiesWithTypes:S.sortablePropertiesWithTypes,sorts:w,enabled:!0,isSorted:S.isSorted}}function save$1(e){if(!e.enabled)return{enabled:!1};ensureOrderedDocsAreDeleted(e),ensureIsSorted(e);let t=Object.keys(e.sorts).reduce((t,S)=>{let{docs:w,orderedDocs:E,type:D}=e.sorts[S];return t[S]={docs:Object.fromEntries(w.entries()),orderedDocs:E,type:D},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function createSorter(){return{create:create$11,insert:insert$1,remove,save:save$1,load:load$1,sortBy,getSortableProperties,getSortablePropertiesWithTypes}}const DIACRITICS_CHARCODE_START=192,DIACRITICS_CHARCODE_END=383,CHARCODE_REPLACE_MAPPING=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function replaceChar(e){return e<DIACRITICS_CHARCODE_START||e>DIACRITICS_CHARCODE_END?e:CHARCODE_REPLACE_MAPPING[e-DIACRITICS_CHARCODE_START]||e}function replaceDiacritics(e){let t=[];for(let S=0;S<e.length;S++)t[S]=replaceChar(e.charCodeAt(S));return String.fromCharCode(...t)}const step2List={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},step3List={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},c=`[^aeiou]`,v=`[aeiouy]`,C=c+`[^aeiouy]*`;v+``;const mgr0=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,meq1=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`,mgr1=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,s_v=`^(`+C+`)?[aeiouy]`;function stemmer(e){let t,S,w,E,D,O;if(e.length<3)return e;let k=e.substring(0,1);if(k==`y`&&(e=k.toUpperCase()+e.substring(1)),w=/^(.+?)(ss|i)es$/,E=/^(.+?)([^s])s$/,w.test(e)?e=e.replace(w,`$1$2`):E.test(e)&&(e=e.replace(E,`$1$2`)),w=/^(.+?)eed$/,E=/^(.+?)(ed|ing)$/,w.test(e)){let t=w.exec(e);w=new RegExp(mgr0),w.test(t[1])&&(w=/.$/,e=e.replace(w,``))}else E.test(e)&&(t=E.exec(e)[1],E=new RegExp(s_v),E.test(t)&&(e=t,E=/(at|bl|iz)$/,D=RegExp(`([^aeiouylsz])\\1$`),O=RegExp(`^`+C+v+`[^aeiouwxy]$`),E.test(e)?e+=`e`:D.test(e)?(w=/.$/,e=e.replace(w,``)):O.test(e)&&(e+=`e`)));if(w=/^(.+?)y$/,w.test(e)&&(t=w.exec(e)?.[1],w=new RegExp(s_v),t&&w.test(t)&&(e=t+`i`)),w=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,w.test(e)){let E=w.exec(e);t=E?.[1],S=E?.[2],w=new RegExp(mgr0),t&&w.test(t)&&(e=t+step2List[S])}if(w=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,w.test(e)){let E=w.exec(e);t=E?.[1],S=E?.[2],w=new RegExp(mgr0),t&&w.test(t)&&(e=t+step3List[S])}if(w=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,E=/^(.+?)(s|t)(ion)$/,w.test(e))t=w.exec(e)?.[1],w=new RegExp(mgr1),t&&w.test(t)&&(e=t);else if(E.test(e)){let S=E.exec(e);t=S?.[1]??``+S?.[2]??``,E=new RegExp(mgr1),E.test(t)&&(e=t)}return w=/^(.+?)e$/,w.test(e)&&(t=w.exec(e)?.[1],w=new RegExp(mgr1),E=new RegExp(meq1),D=RegExp(`^`+C+v+`[^aeiouwxy]$`),t&&(w.test(t)||E.test(t)&&!D.test(t))&&(e=t)),w=/ll$/,E=new RegExp(mgr1),w.test(e)&&E.test(e)&&(w=/.$/,e=e.replace(w,``)),k==`y`&&(e=k.toLowerCase()+e.substring(1)),e}function normalizeToken(e,t,S=!0){let w=`${this.language}:${e}:${t}`;return S&&this.normalizationCache.has(w)?this.normalizationCache.get(w):this.stopWords?.includes(t)?(S&&this.normalizationCache.set(w,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=replaceDiacritics(t),S&&this.normalizationCache.set(w,t),t)}function trim(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function tokenize(e,t,S,w=!0){if(t&&t!==this.language)throw createError(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let E=this.normalizeToken.bind(this,S??``),D;if(S&&this.tokenizeSkipProperties.has(S))D=[E(e,w)];else{let t=SPLITTERS[this.language];D=e.toLowerCase().split(t).map(e=>E(e,w)).filter(Boolean)}let O=trim(D);return this.allowDuplicates?O:Array.from(new Set(O))}function createTokenizer(e={}){if(!e.language)e.language=`english`;else if(!SUPPORTED_LANGUAGES.includes(e.language))throw createError(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw createError(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=stemmer;else throw createError(`MISSING_STEMMER`,e.language);let S;if(e.stopWords!==!1){if(S=[],Array.isArray(e.stopWords))S=e.stopWords;else if(typeof e.stopWords==`function`)S=e.stopWords(S);else if(e.stopWords)throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(S))throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of S)if(typeof e!=`string`)throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let w={tokenize,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:S,allowDuplicates:!!e.allowDuplicates,normalizeToken,normalizationCache:new Map};return w.tokenize=tokenize.bind(w),w.normalizeToken=normalizeToken,w}function create$10(e){return{sharedInternalDocumentStore:e,rules:new Map}}function addRule(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function updateRule(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function removeRule(e,t){return e.rules.delete(t)}function getRule(e,t){return e.rules.get(t)}function getAllRules(e){return Array.from(e.rules.values())}function matchesCondition(e,t){let S=e.toLowerCase().trim(),w=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return S===w;case`starts_with`:return S.startsWith(w);case`contains`:return S.includes(w);default:return!1}}function matchesRule(e,t){return e?t.conditions.every(t=>matchesCondition(e,t)):!1}function getMatchingRules(e,t){if(!t)return[];let S=[];for(let w of e.rules.values())matchesRule(t,w)&&S.push(w);return S}function load(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function save(e){return{rules:Array.from(e.rules.entries())}}function createPinning(){return{create:create$10,addRule,updateRule,removeRule,getRule,getAllRules,getMatchingRules,load,save}}function validateComponents(e){let t={formatElapsedTime,getDocumentIndexId,getDocumentProperties,validateSchema};for(let S of FUNCTION_COMPONENTS){let w=S;if(e[w]){if(typeof e[w]!=`function`)throw createError(`COMPONENT_MUST_BE_FUNCTION`,w)}else e[w]=t[w]}for(let t of Object.keys(e))if(!OBJECT_COMPONENTS.includes(t)&&!FUNCTION_COMPONENTS.includes(t))throw createError(`UNSUPPORTED_COMPONENT`,t)}function create$9({schema:e,sort:t,language:S,components:w,id:E,plugins:D}){w||={};for(let t of D??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let S=t.getComponents(e),E=Object.keys(S);for(let e of E)if(w[e])throw createError(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);w={...w,...S}}E||=uniqueId();let O=w.tokenizer,k=w.index,j=w.documentsStore,F=w.sorter,L=w.pinning;if(O=O?O.tokenize?O:createTokenizer(O):createTokenizer({language:S??`english`}),w.tokenizer&&S)throw createError(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let B=createInternalDocumentIDStore();k||=createIndex(),F||=createSorter(),j||=createDocumentsStore(),L||=createPinning(),validateComponents(w);let{getDocumentProperties:H,getDocumentIndexId:q,validateSchema:J,formatElapsedTime:Y}=w,ee={data:{},caches:{},schema:e,tokenizer:O,index:k,sorter:F,documentsStore:j,pinning:L,internalDocumentIDStore:B,getDocumentProperties:H,getDocumentIndexId:q,validateSchema:J,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:Y,id:E,plugins:D,version:getVersion()};ee.data={index:ee.index.create(ee,B,e),docs:ee.documentsStore.create(ee,B),sorting:ee.sorter.create(ee,B,e,t),pinning:ee.pinning.create(B)};for(let e of AVAILABLE_PLUGIN_HOOKS)ee[e]=(ee[e]??[]).concat(getAllPluginsByHook(ee,e));let te=ee.afterCreate;return te&&runAfterCreate(te,ee),ee}function getVersion(){return`{{VERSION}}`}function count(e){return e.documentsStore.count(e.data.docs)}function insert(e,t,S,w,E){let D=e.validateSchema(t,e.schema);if(D)throw createError(`SCHEMA_VALIDATION_FAILURE`,D);return isAsyncFunction(e.beforeInsert)||isAsyncFunction(e.afterInsert)||isAsyncFunction(e.index.beforeInsert)||isAsyncFunction(e.index.insert)||isAsyncFunction(e.index.afterInsert)?innerInsertAsync(e,t,S,w,E):innerInsertSync(e,t,S,w,E)}const ENUM_TYPE=new Set([`enum`,`enum[]`]),STRING_NUMBER_TYPE=new Set([`string`,`number`]);async function innerInsertAsync(e,t,S,w,E){let{index:D,docs:O}=e.data,k=e.getDocumentIndexId(t);if(typeof k!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof k);let j=getInternalDocumentId(e.internalDocumentIDStore,k);if(w||await runSingleHook(e.beforeInsert,e,k,t),!e.documentsStore.store(O,k,j,t))throw createError(`DOCUMENT_ALREADY_EXISTS`,k);let F=e.documentsStore.count(O),L=e.index.getSearchableProperties(D),B=e.index.getSearchablePropertiesWithTypes(D),H=e.getDocumentProperties(t,L);for(let[e,t]of Object.entries(H)){if(t===void 0)continue;let S=typeof t,w=B[e];validateDocumentProperty(S,w,e,t)}return await indexAndSortDocument(e,k,L,H,F,S,t,E),w||await runSingleHook(e.afterInsert,e,k,t),k}function innerInsertSync(e,t,S,w,E){let{index:D,docs:O}=e.data,k=e.getDocumentIndexId(t);if(typeof k!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof k);let j=getInternalDocumentId(e.internalDocumentIDStore,k);if(w||runSingleHook(e.beforeInsert,e,k,t),!e.documentsStore.store(O,k,j,t))throw createError(`DOCUMENT_ALREADY_EXISTS`,k);let F=e.documentsStore.count(O),L=e.index.getSearchableProperties(D),B=e.index.getSearchablePropertiesWithTypes(D),H=e.getDocumentProperties(t,L);for(let[e,t]of Object.entries(H)){if(t===void 0)continue;let S=typeof t,w=B[e];validateDocumentProperty(S,w,e,t)}return indexAndSortDocumentSync(e,k,L,H,F,S,t,E),w||runSingleHook(e.afterInsert,e,k,t),k}function validateDocumentProperty(e,t,S,w){if(!(isGeoPointType(t)&&typeof w==`object`&&typeof w.lon==`number`&&typeof w.lat==`number`)&&!(isVectorType(t)&&Array.isArray(w))&&!(isArrayType(t)&&Array.isArray(w))&&!(ENUM_TYPE.has(t)&&STRING_NUMBER_TYPE.has(e))&&e!==t)throw createError(`INVALID_DOCUMENT_PROPERTY`,S,t,e)}async function indexAndSortDocument(e,t,S,w,E,D,O,k){for(let O of S){let S=w[O];if(S===void 0)continue;let j=e.index.getSearchablePropertiesWithTypes(e.data.index)[O];await e.index.beforeInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E);let F=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,O,t,F,S,j,D,e.tokenizer,E,k),await e.index.afterInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E)}let j=e.sorter.getSortableProperties(e.data.sorting),F=e.getDocumentProperties(O,j);for(let S of j){let w=F[S];if(w===void 0)continue;let E=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[S];e.sorter.insert(e.data.sorting,S,t,w,E,D)}}function indexAndSortDocumentSync(e,t,S,w,E,D,O,k){for(let O of S){let S=w[O];if(S===void 0)continue;let j=e.index.getSearchablePropertiesWithTypes(e.data.index)[O],F=getInternalDocumentId(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E),e.index.insert(e.index,e.data.index,O,t,F,S,j,D,e.tokenizer,E,k),e.index.afterInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E)}let j=e.sorter.getSortableProperties(e.data.sorting),F=e.getDocumentProperties(O,j);for(let S of j){let w=F[S];if(w===void 0)continue;let E=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[S];e.sorter.insert(e.data.sorting,S,t,w,E,D)}}function insertMultiple(e,t,S,w,E,D){return isAsyncFunction(e.afterInsertMultiple)||isAsyncFunction(e.beforeInsertMultiple)||isAsyncFunction(e.index.beforeInsert)||isAsyncFunction(e.index.insert)||isAsyncFunction(e.index.afterInsert)?innerInsertMultipleAsync(e,t,S,w,E,D):innerInsertMultipleSync(e,t,S,w,E,D)}async function innerInsertMultipleAsync(e,t,S=1e3,w,E,D=0){let O=[],k=async D=>{let k=Math.min(D+S,t.length),j=t.slice(D,k);for(let t of j){let S=await insert(e,t,w,E,{avlRebalanceThreshold:j.length});O.push(S)}return k};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await k(e),D>0){let e=D-(Date.now()-t);e>0&&sleep$1(e)}}})(),E||await runMultipleHook(e.afterInsertMultiple,e,t),O}function innerInsertMultipleSync(e,t,S=1e3,w,E,D=0){let O=[],k=0;function j(){let D=t.slice(k*S,(k+1)*S);if(D.length===0)return!1;for(let t of D){let S=insert(e,t,w,E,{avlRebalanceThreshold:D.length});O.push(S)}return k++,!0}function F(){let e=Date.now();for(;j();)if(D>0){let t=Date.now()-e;if(t>=D){let e=D-t%D;e>0&&sleep$1(e)}}}return F(),E||runMultipleHook(e.afterInsertMultiple,e,t),O}const MODE_FULLTEXT_SEARCH=`fulltext`,MODE_HYBRID_SEARCH=`hybrid`,MODE_VECTOR_SEARCH=`vector`;function sortAsc(e,t){return e[1]-t[1]}function sortDesc(e,t){return t[1]-e[1]}function sortingPredicateBuilder(e=`desc`){return e.toLowerCase()===`asc`?sortAsc:sortDesc}function getFacets(e,t,S){let w={},E=t.map(([e])=>e),D=e.documentsStore.getMultiple(e.data.docs,E),O=Object.keys(S),k=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of O){let t;if(k[e]===`number`){let{ranges:w}=S[e],E=w.length,D=Array.from({length:E});for(let e=0;e<E;e++){let t=w[e];D[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(D)}w[e]={count:0,values:t??{}}}let j=D.length;for(let e=0;e<j;e++){let t=D[e];for(let e of O){let E=e.includes(`.`)?getNested(t,e):t[e],D=k[e],O=w[e].values;switch(D){case`number`:{let t=S[e].ranges;calculateNumberFacetBuilder(t,O)(E);break}case`number[]`:{let t=new Set,w=S[e].ranges,D=calculateNumberFacetBuilder(w,O,t);for(let e of E)D(e);break}case`boolean`:case`enum`:case`string`:calculateBooleanStringOrEnumFacetBuilder(O,D)(E);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=calculateBooleanStringOrEnumFacetBuilder(O,D===`boolean[]`?`boolean`:`string`,new Set);for(let t of E)e(t);break}default:throw createError(`FACET_NOT_SUPPORTED`,D)}}}for(let e of O){let t=w[e];if(t.count=Object.keys(t.values).length,k[e]===`string`){let w=S[e],E=sortingPredicateBuilder(w.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(E).slice(w.offset??0,w.limit??10))}}return w}function calculateNumberFacetBuilder(e,t,S){return w=>{for(let E of e){let e=`${E.from}-${E.to}`;S?.has(e)||w>=E.from&&w<=E.to&&(t[e]===void 0?t[e]=1:(t[e]++,S?.add(e)))}}}function calculateBooleanStringOrEnumFacetBuilder(e,t,S){let w=t===`boolean`?`false`:``;return t=>{let E=t?.toString()??w;S?.has(E)||(e[E]=(e[E]??0)+1,S?.add(E))}}const DEFAULT_REDUCE={reducer:(e,t,S,w)=>(t[w]=S,t),getInitialValue:e=>Array.from({length:e})},ALLOWED_TYPES=[`string`,`number`,`boolean`];function getGroups(e,t,S){let w=S.properties,E=w.length,D=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<E;e++){let t=w[e];if(D[t]===void 0)throw createError(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!ALLOWED_TYPES.includes(D[t]))throw createError(`INVALID_GROUP_BY_PROPERTY`,t,ALLOWED_TYPES.join(`, `),D[t])}let O=t.map(([t])=>getDocumentIdFromInternalId(e.internalDocumentIDStore,t)),k=e.documentsStore.getMultiple(e.data.docs,O),j=k.length,F=S.maxResult||2**53-1,L=[],B={};for(let e=0;e<E;e++){let t=w[e],S={property:t,perValue:{}},E=new Set;for(let e=0;e<j;e++){let w=k[e],D=getNested(w,t);if(D===void 0)continue;let O=typeof D==`boolean`?``+D:D,j=S.perValue[O]??{indexes:[],count:0};j.count>=F||(j.indexes.push(e),j.count++,S.perValue[O]=j,E.add(D))}L.push(Array.from(E)),B[t]=S}let H=calculateCombination(L),q=H.length,J=[];for(let e=0;e<q;e++){let t=H[e],S=t.length,E={values:[],indexes:[]},D=[];for(let e=0;e<S;e++){let S=t[e],O=w[e];D.push(B[O].perValue[typeof S==`boolean`?``+S:S].indexes),E.values.push(S)}E.indexes=intersect(D).sort((e,t)=>e-t),E.indexes.length!==0&&J.push(E)}let Y=J.length,ee=Array.from({length:Y});for(let e=0;e<Y;e++){let w=J[e],E=S.reduce||DEFAULT_REDUCE,D=w.indexes.map(e=>({id:O[e],score:t[e][1],document:k[e]})),j=E.reducer.bind(null,w.values),F=E.getInitialValue(w.indexes.length),L=D.reduce(j,F);ee[e]={values:w.values,result:L}}return ee}function calculateCombination(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let S=e[t],w=calculateCombination(e,t+1),E=[];for(let e of S)for(let t of w){let S=[e];safeArrayPush(S,t),E.push(S)}return E}function applyPinningRules(e,t,S,w){let E=getMatchingRules(t,w);if(E.length===0)return S;let D=E.flatMap(e=>e.consequence.promote);D.sort((e,t)=>e.position-t.position);let O=new Set,k=new Map,j=new Set;for(let t of D){let S=getInternalDocumentId(e.internalDocumentIDStore,t.doc_id);if(S!==void 0){if(k.has(S)){let e=k.get(S);t.position<e&&k.set(S,t.position);continue}j.has(t.position)||(O.add(S),k.set(S,t.position),j.add(t.position))}}if(k.size===0)return S;let F=S.filter(([e])=>!O.has(e)),L=1e6,B=[];for(let[t,w]of k.entries())S.find(([e])=>e===t)?B.push([t,1e6-w]):e.documentsStore.get(e.data.docs,t)&&B.push([t,0]);B.sort((e,t)=>(k.get(e[0])??1/0)-(k.get(t[0])??1/0));let H=[],q=new Map;for(let e of B){let t=k.get(e[0]);q.set(t,e)}let J=0,Y=0;for(;Y<F.length+B.length;)if(q.has(Y))H.push(q.get(Y)),Y++;else if(J<F.length)H.push(F[J]),J++,Y++;else break;for(let[e,t]of q.entries())e>=H.length&&H.push(t);return H}function innerFullTextSearch(e,t,S){let{term:w,properties:E}=t,D=e.data.index,O=e.caches.propertiesToSearch;if(!O){let t=e.index.getSearchablePropertiesWithTypes(D);O=e.index.getSearchableProperties(D),O=O.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=O}if(E&&E!==`*`){for(let e of E)if(!O.includes(e))throw createError(`UNKNOWN_INDEX`,e,O.join(`, `));O=O.filter(e=>E.includes(e))}let k=Object.keys(t.where??{}).length>0,j;k&&(j=e.index.searchByWhereClause(D,e.tokenizer,t.where,S));let F,L=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(w||E){let E=count(e);if(F=e.index.search(D,w||``,e.tokenizer,S,O,t.exact||!1,t.tolerance||0,t.boost||{},applyDefault(t.relevance),E,j,L),t.exact&&w){let t=w.trim().split(/\s+/);F=F.filter(([S])=>{let w=e.documentsStore.get(e.data.docs,S);if(!w)return!1;for(let e of O){let S=getPropValue(w,e);if(typeof S==`string`&&t.every(e=>RegExp(`\\b${escapeRegex(e)}\\b`).test(S)))return!0}return!1})}}else F=k?searchByGeoWhereClause(D,t.where)||(j?Array.from(j):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return F}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function getPropValue(e,t){let S=t.split(`.`),w=e;for(let e of S)if(w&&typeof w==`object`&&e in w)w=w[e];else return;return w}function fullTextSearch(e,t,S){let w=getNanosecondsTime();function E(){let E=Object.keys(e.data.index.vectorIndexes),D=t.facets&&Object.keys(t.facets).length>0,{limit:O=10,offset:k=0,distinctOn:j,includeVectors:F=!1}=t,L=t.preflight===!0,B=innerFullTextSearch(e,t,S);if(t.sortBy)if(typeof t.sortBy==`function`){let S=B.map(([e])=>e),w=e.documentsStore.getMultiple(e.data.docs,S).map((e,t)=>[B[t][0],B[t][1],e]);w.sort(t.sortBy),B=w.map(([e,t])=>[e,t])}else B=e.sorter.sortBy(e.data.sorting,B,t.sortBy).map(([t,S])=>[getInternalDocumentId(e.internalDocumentIDStore,t),S]);else B=B.sort(sortTokenScorePredicate);B=applyPinningRules(e,e.data.pinning,B,t.term);let H;L||(H=j?fetchDocumentsWithDistinct(e,B,k,O,j):fetchDocuments(e,B,k,O));let q={elapsed:{formatted:``,raw:0},hits:[],count:B.length};return H!==void 0&&(q.hits=H.filter(Boolean),F||removeVectorsFromHits(q,E)),D&&(q.facets=getFacets(e,B,t.facets)),t.groupBy&&(q.groups=getGroups(e,B,t.groupBy)),q.elapsed=e.formatElapsedTime(getNanosecondsTime()-w),q}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}const defaultBM25Params={k:1.2,b:.75,d:.5};function applyDefault(e){let t=e??{};return t.k=t.k??defaultBM25Params.k,t.b=t.b??defaultBM25Params.b,t.d=t.d??defaultBM25Params.d,t}function innerVectorSearch(e,t,S){let w=t.vector;if(w&&(!(`value`in w)||!(`property`in w)))throw createError(`INVALID_VECTOR_INPUT`,Object.keys(w).join(`, `));let E=e.data.index.vectorIndexes[w.property];if(!E)throw createError(`UNKNOWN_VECTOR_PROPERTY`,w.property);let D=E.node.size;if(w?.value.length!==D)throw w?.property===void 0||w?.value.length===void 0?createError(`INVALID_INPUT_VECTOR`,`undefined`,D,`undefined`):createError(`INVALID_INPUT_VECTOR`,w.property,D,w.value.length);let O=e.data.index,k;return Object.keys(t.where??{}).length>0&&(k=e.index.searchByWhereClause(O,e.tokenizer,t.where,S)),E.node.find(w.value,t.similarity??.8,k)}function searchVector(e,t,S=`english`){let w=getNanosecondsTime();function E(){let E=innerVectorSearch(e,t,S).sort(sortTokenScorePredicate);E=applyPinningRules(e,e.data.pinning,E,void 0);let D=[];t.facets&&Object.keys(t.facets).length>0&&(D=getFacets(e,E,t.facets));let O=t.vector.property,k=t.includeVectors??!1,j=t.limit??10,F=t.offset??0,L=Array.from({length:j});for(let t=0;t<j;t++){let S=E[t+F];if(!S)break;let w=e.data.docs.docs[S[0]];w&&(k||(w[O]=null),L[t]={id:getDocumentIdFromInternalId(e.internalDocumentIDStore,S[0]),score:S[1],document:w})}let B=[];t.groupBy&&(B=getGroups(e,E,t.groupBy));let H=getNanosecondsTime()-w;return{count:E.length,hits:L.filter(Boolean),elapsed:{raw:Number(H),formatted:formatNanoseconds(H)},...D?{facets:D}:{},...B?{groups:B}:{}}}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}function innerHybridSearch(e,t,S){let w=minMaxScoreNormalization(innerFullTextSearch(e,t,S)),E=innerVectorSearch(e,t,S),D=t.hybridWeights;return mergeAndRankResults(w,E,t.term??``,D)}function hybridSearch(e,t,S){let w=getNanosecondsTime();function E(){let E=innerHybridSearch(e,t,S);E=applyPinningRules(e,e.data.pinning,E,t.term);let D;t.facets&&Object.keys(t.facets).length>0&&(D=getFacets(e,E,t.facets));let O;t.groupBy&&(O=getGroups(e,E,t.groupBy));let k=t.offset??0,j=t.limit??10,F=fetchDocuments(e,E,k,j).filter(Boolean),L=getNanosecondsTime(),B={count:E.length,elapsed:{raw:Number(L-w),formatted:formatNanoseconds(L-w)},hits:F,...D?{facets:D}:{},...O?{groups:O}:{}};return(t.includeVectors??!1)||removeVectorsFromHits(B,Object.keys(e.data.index.vectorIndexes)),B}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}function extractScore(e){return e[1]}function minMaxScoreNormalization(e){let t=Math.max.apply(Math,e.map(extractScore));return e.map(([e,S])=>[e,S/t])}function normalizeScore(e,t){return e/t}function hybridScoreBuilder(e,t){return(S,w)=>S*e+w*t}function mergeAndRankResults(e,t,S,w){let E=Math.max.apply(Math,e.map(extractScore)),D=Math.max.apply(Math,t.map(extractScore)),{text:O,vector:k}=w&&w.text&&w.vector?w:getQueryWeights(S),j=new Map,F=e.length,L=hybridScoreBuilder(O,k);for(let t=0;t<F;t++){let[S,w]=e[t],D=L(normalizeScore(w,E),0);j.set(S,D)}let B=t.length;for(let e=0;e<B;e++){let[S,w]=t[e],E=normalizeScore(w,D),O=j.get(S)??0;j.set(S,O+L(0,E))}return[...j].sort((e,t)=>t[1]-e[1])}function getQueryWeights(e){return{text:.5,vector:.5}}function search(e,t,S){let w=t.mode??`fulltext`;if(w===`fulltext`)return fullTextSearch(e,t,S);if(w===`vector`)return searchVector(e,t);if(w===`hybrid`)return hybridSearch(e,t);throw createError(`INVALID_SEARCH_MODE`,w)}function fetchDocumentsWithDistinct(e,t,S,w,E){let D=e.data.docs,O=new Map,k=[],j=new Set,F=t.length,L=0;for(let B=0;B<F;B++){let F=t[B];if(F===void 0)continue;let[H,q]=F;if(j.has(H))continue;let J=e.documentsStore.get(D,H),Y=getNested(J,E);if(!(Y===void 0||O.has(Y))&&(O.set(Y,!0),L++,!(L<=S)&&(k.push({id:getDocumentIdFromInternalId(e.internalDocumentIDStore,H),score:q,document:J}),j.add(H),L>=S+w)))break}return k}function fetchDocuments(e,t,S,w){let E=e.data.docs,D=Array.from({length:w}),O=new Set;for(let k=S;k<w+S;k++){let S=t[k];if(S===void 0)break;let[w,j]=S;if(!O.has(w)){let t=e.documentsStore.get(E,w);D[k]={id:getDocumentIdFromInternalId(e.internalDocumentIDStore,w),score:j,document:t},O.add(w)}}return D}var import_diff_match_patch=__toESM$1(require_diff_match_patch(),1);const dmp$1=new import_diff_match_patch.default;function diffLinesFast(e,t){if(e===t)return[{value:e}];let{chars1:S,chars2:w,lineArray:E}=dmp$1.diff_linesToChars_(e,t),D=dmp$1.diff_main(S,w,!1);dmp$1.diff_charsToLines_(D,E),dmp$1.diff_cleanupSemantic(D);let O=[];for(let[e,t]of D)e===import_diff_match_patch.default.DIFF_DELETE?O.push({value:t,removed:!0}):e===import_diff_match_patch.default.DIFF_INSERT?O.push({value:t,added:!0}):O.push({value:t});return O}const dmpDiff=new import_diff_match_patch.default;dmpDiff.Diff_Timeout=.25;const APPLY_FAST_DIFF_MAX_BYTES=256*1024;function applyIncrementalDiff(e,t,S){if(t===S)return;let w=diffLinesFast(t,S),E=0;for(let S=0;S<w.length;S++){let D=w[S],O=w[S+1];if(D.removed&&O?.added){if(t.substring(E,E+O.value.length)===O.value){E+=O.value.length,S++;continue}e.delete(E,D.value.length),e.insert(E,O.value),E+=O.value.length,S++}else D.removed?e.delete(E,D.value.length):(D.added&&e.insert(E,D.value),E+=D.value.length)}}function applyFastDiff(e,t,S){if(t===S)return;if(t.length>APPLY_FAST_DIFF_MAX_BYTES||S.length>APPLY_FAST_DIFF_MAX_BYTES){applyByPrefixSuffixMiddleReplace(e,t,S);return}let w=dmpDiff.diff_main(t,S);dmpDiff.diff_cleanupSemantic(w);let E=0;for(let[t,S]of w)t===0?E+=S.length:t===-1?e.delete(E,S.length):t===1&&(e.insert(E,S),E+=S.length)}function applyByPrefixSuffixMiddleReplace(e,t,S){let w=0,E=Math.min(t.length,S.length);for(;w<E&&t.charCodeAt(w)===S.charCodeAt(w);)w++;let D=0;for(;D<E-w&&t.charCodeAt(t.length-1-D)===S.charCodeAt(S.length-1-D);)D++;let O=t.length-w-D,k=S.slice(w,S.length-D);O>0&&e.delete(w,O),k.length>0&&e.insert(w,k)}const FrontmatterIssueSchema=object$1({path:array(union([string$2(),number$1()])),message:string$2(),issueCode:string$2()}),FrontmatterValidationErrorSchema=discriminatedUnion(`code`,[object$1({code:literal(`SCHEMA_INVALID`),issues:array(FrontmatterIssueSchema)}),object$1({code:literal(`WRITE_ERROR`),detail:string$2()})]),FRONTMATTER_TYPES=[`text`,`number`,`boolean`,`date`,`list`],FrontmatterTypeSchema=_enum(FRONTMATTER_TYPES),FrontmatterValueSchema=union([string$2(),number$1(),boolean$1(),array(union([string$2(),number$1(),boolean$1()]).transform(e=>String(e)))]),FrontmatterMapSchema=record(string$2(),FrontmatterValueSchema),FrontmatterPatchSchema=record(string$2(),union([FrontmatterValueSchema,_null()])),FRONTMATTER_RE$1=/^---\r?\n([\s\S]*?\r?\n)?---(\r?\n|$)/;function stripFrontmatter(e){let t=e.match(FRONTMATTER_RE$1);return t?{frontmatter:t[0],body:e.slice(t[0].length)}:{frontmatter:``,body:e}}function prependFrontmatter(e,t){return e?e+t:t}function unwrapFrontmatterFences(e){if(e===``)return``;let t=e.match(FRONTMATTER_RE$1);return t?(t[1]??``).replace(/\r?\n$/,``):e}function parseFrontmatterYaml(e){if(e.trim()===``)return{doc:new import_dist$1.Document({}),map:{}};let t;try{t=(0,import_dist$1.parseDocument)(e)}catch(e){let t=e instanceof Error?e.message:String(e);return{doc:new import_dist$1.Document({}),map:null,parseError:`parse threw: ${t}`}}if(t.errors.length>0)return{doc:t,map:null,parseError:t.errors[0]?.message??`yaml parse errors`};let S;try{S=t.toJS()}catch(e){let S=e instanceof Error?e.message:String(e);return{doc:t,map:null,parseError:`toJS threw: ${S}`}}if(typeof S!=`object`||!S||Array.isArray(S))return{doc:t,map:null,parseError:`top-level value is not a mapping`};let w=FrontmatterMapSchema.safeParse(S);if(!w.success){let e=w.error.issues[0],S=e&&Array.isArray(e.path)?e.path.join(`.`):``,E=e?.message??`unknown`;return{doc:t,map:null,parseError:S?`value at "${S}" failed schema: ${E}`:`schema validation failed: ${E}`}}return{doc:t,map:w.data}}function detectFmRegion(e){let t=e.match(FRONTMATTER_RE$1);return t?{fenced:t[0],body:e.slice(t[0].length)}:{fenced:``,body:e}}function parseFmRegion(e){if(e.trim()===``)return{doc:new import_dist$1.Document({}),map:{}};let t;try{t=(0,import_dist$1.parseDocument)(e,{uniqueKeys:!1})}catch(e){let t=e instanceof Error?e.message:String(e);return{doc:new import_dist$1.Document({}),map:null,parseError:`parse threw: ${t}`}}if(t.errors.length>0)return{doc:t,map:null,parseError:t.errors[0]?.message??`yaml parse errors`};let S;try{S=t.toJS()}catch(e){let S=e instanceof Error?e.message:String(e);return{doc:t,map:null,parseError:`toJS threw: ${S}`}}if(typeof S!=`object`||!S||Array.isArray(S))return{doc:t,map:null,parseError:`top-level value is not a mapping`};let w=FrontmatterMapSchema.safeParse(S);if(!w.success){let e=w.error.issues[0],S=e&&Array.isArray(e.path)?e.path.join(`.`):``,E=e?.message??`unknown`;return{doc:t,map:null,parseError:S?`value at "${S}" failed schema: ${E}`:`schema validation failed: ${E}`}}return{doc:t,map:w.data}}function parseFencedFmRegion(e){return e===``?{doc:new import_dist$1.Document({}),map:{}}:parseFmRegion(unwrapFrontmatterFences(e))}function readFmMap(e){let{fenced:t}=detectFmRegion(e),{map:S}=parseFencedFmRegion(t);return S??{}}const FORM_WRITE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!1,context:Object.freeze({origin:`form-write`})});function fnv1aDigest(e){let t=2166136261;for(let S=0;S<e.length;S++)t^=e.charCodeAt(S),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function toBridgeInvariantLog(e,t){let S=t?.verbose===!0,w=t?.nowMs===void 0?new Date().toISOString():new Date(t.nowMs).toISOString(),E={event:`bridge-invariant-violation`,site:e.site,"doc.name":e.docName??null,"tolerance-class-attempted":`untracked`,"normalize-equal-modulo-tolerance":!1,ytextLen:e.ytextSnapshot.length,fragmentLen:e.fragmentMdSnapshot.length,ytextHash:fnv1aDigest(e.ytextSnapshot),fragmentHash:fnv1aDigest(e.fragmentMdSnapshot),redacted:!S,timestamp:w};return S?{...E,diff:e.unifiedDiff}:E}var BridgeInvariantViolationError=class extends Error{violation;constructor(e){let t=typeof e.origin==`string`?e.origin:e.origin?.context?.origin??`unknown-object`,S=e.docName?` doc='${e.docName}'`:``;super(`Bridge invariant violated [site='${e.site}'${S}, origin='${t}'].\n Y.Text (${e.ytextSnapshot.length} chars): ${e.ytextSnapshot.slice(0,200)}...\n Fragment (${e.fragmentMdSnapshot.length} chars): ${e.fragmentMdSnapshot.slice(0,200)}...\n Diff:\n${e.unifiedDiff}`),this.name=`BridgeInvariantViolationError`,this.violation=e}};const dmp=new import_diff_match_patch.default;dmp.Match_Threshold=.5;function mergeThreeWay(e,t,S){let w=mergeThreeWayImpl(e,t,S);return assertContentPreservation(e,t,S,w),w}function mergeThreeWayImpl(e,t,S){if(e===t)return S;if(e===S||t===S)return t;let w=diff3Merge(t.split(`
|
|
299
|
+
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function createError(e,...t){let S=Error(sprintf(errors[e]??`Unsupported Orama Error code: ${e}`,...t));return S.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(S),S}function formatElapsedTime(e){return{raw:Number(e),formatted:formatNanoseconds(e)}}function getDocumentIndexId(e){if(e.id){if(typeof e.id!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return uniqueId()}function validateSchema(e,t){for(let[S,w]of Object.entries(t)){let t=e[S];if(t!==void 0&&!(w===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(w===`enum`&&(typeof t==`string`||typeof t==`number`))){if(w===`enum[]`&&Array.isArray(t)){let e=t.length;for(let w=0;w<e;w++)if(typeof t[w]!=`string`&&typeof t[w]!=`number`)return S+`.`+w;continue}if(isVectorType(w)){let e=getVectorSize(w);if(!Array.isArray(t)||t.length!==e)throw createError(`INVALID_INPUT_VECTOR`,S,e,t.length);continue}if(isArrayType(w)){if(!Array.isArray(t))return S;let e=getInnerType(w),E=t.length;for(let w=0;w<E;w++)if(typeof t[w]!==e)return S+`.`+w;continue}if(typeof w==`object`){if(!t||typeof t!=`object`)return S;let e=validateSchema(t,w);if(e)return S+`.`+e;continue}if(typeof t!==w)return S}}}const IS_ARRAY_TYPE={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},INNER_TYPE={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function isGeoPointType(e){return e===`geopoint`}function isVectorType(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function isArrayType(e){return typeof e==`string`&&IS_ARRAY_TYPE[e]}function getInnerType(e){return INNER_TYPE[e]}function getVectorSize(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw createError(`INVALID_VECTOR_VALUE`,e);case t<=0:throw createError(`INVALID_VECTOR_SIZE`,e);default:return t}}function createInternalDocumentIDStore(){return{idToInternalId:new Map,internalIdToId:[],save:save$4,load:load$4}}function save$4(e){return{internalIdToId:e.internalIdToId}}function load$4(e,t){let{internalIdToId:S}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let w=S.length;for(let t=0;t<w;t++){let w=S[t];e.internalDocumentIDStore.idToInternalId.set(w,t+1),e.internalDocumentIDStore.internalIdToId.push(w)}}function getInternalDocumentId(e,t){if(typeof t==`string`){let S=e.idToInternalId.get(t);if(S)return S;let w=e.idToInternalId.size+1;return e.idToInternalId.set(t,w),e.internalIdToId.push(t),w}return t>e.internalIdToId.length?getInternalDocumentId(e,t.toString()):t}function getDocumentIdFromInternalId(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function create$13(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function get(e,t){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t);return e.docs[S]}function getMultiple(e,t){let S=t.length,w=Array.from({length:S});for(let E=0;E<S;E++){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t[E]);w[E]=e.docs[S]}return w}function getAll(e){return e.docs}function store(e,t,S,w){return e.docs[S]===void 0?(e.docs[S]=w,e.count++,!0):!1}function remove$2(e,t){let S=getInternalDocumentId(e.sharedInternalDocumentStore,t);return e.docs[S]===void 0?!1:(delete e.docs[S],e.count--,!0)}function count$1(e){return e.count}function load$3(e,t){let S=t;return{docs:S.docs,count:S.count,sharedInternalDocumentStore:e}}function save$3(e){return{docs:e.docs,count:e.count}}function createDocumentsStore(){return{create:create$13,get,getMultiple,getAll,store,remove:remove$2,count:count$1,load:load$3,save:save$3}}const AVAILABLE_PLUGIN_HOOKS=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function getAllPluginsByHook(e,t){let S=[],w=e.plugins?.length;if(!w)return S;for(let E=0;E<w;E++)try{let w=e.plugins[E];typeof w[t]==`function`&&S.push(w[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),createError(`PLUGIN_CRASHED`)}return S}const OBJECT_COMPONENTS=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],FUNCTION_COMPONENTS=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function runSingleHook(e,t,S,w){if(e.some(isAsyncFunction))return(async()=>{for(let E of e)await E(t,S,w)})();for(let E of e)E(t,S,w)}function runMultipleHook(e,t,S){if(e.some(isAsyncFunction))return(async()=>{for(let w of e)await w(t,S)})();for(let w of e)w(t,S)}function runAfterSearch(e,t,S,w,E){if(e.some(isAsyncFunction))return(async()=>{for(let D of e)await D(t,S,w,E)})();for(let D of e)D(t,S,w,E)}function runBeforeSearch(e,t,S,w){if(e.some(isAsyncFunction))return(async()=>{for(let E of e)await E(t,S,w)})();for(let E of e)E(t,S,w)}function runAfterCreate(e,t){if(e.some(isAsyncFunction))return(async()=>{for(let S of e)await S(t)})();for(let S of e)S(t)}var AVLNode=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let S=new e(t.k,t.v);return S.l=t.l?e.fromJSON(t.l):null,S.r=t.r?e.fromJSON(t.r):null,S.h=t.h,S}},AVLTree=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new AVLNode(e,t))}insert(e,t,S=1e3){this.root=this.insertNode(this.root,e,t,S)}insertMultiple(e,t,S=1e3){for(let w of t)this.insert(e,w,S)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let S=new e;return S.root=t.root?AVLNode.fromJSON(t.root):null,S.insertCount=t.insertCount||0,S}insertNode(e,t,S,w){if(e===null)return new AVLNode(t,[S]);let E=[],D=e,O=null;for(;D!==null;)if(E.push({parent:O,node:D}),t<D.k)if(D.l===null){D.l=new AVLNode(t,[S]),E.push({parent:D,node:D.l});break}else O=D,D=D.l;else if(t>D.k)if(D.r===null){D.r=new AVLNode(t,[S]),E.push({parent:D,node:D.r});break}else O=D,D=D.r;else return D.v.add(S),e;let k=!1;this.insertCount++%w===0&&(k=!0);for(let t=E.length-1;t>=0;t--){let{parent:S,node:w}=E[t];if(w.updateHeight(),k){let t=this.rebalanceNode(w);S?S.l===w?S.l=t:S.r===w&&(S.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],S=this.root;for(;S||t.length>0;){for(;S;)t.push(S),S=S.l;S=t.pop(),e++,S=S.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),S=t.getBalanceFactor();if(Math.abs(S)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let S=this.findNodeByKey(e);S&&(S.v.size===1?this.root=this.removeNode(this.root,e):S.v=new Set([...S.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let S=[],w=e;for(;w!==null&&w.k!==t;)S.push(w),w=t<w.k?w.l:w.r;if(w===null)return e;if(w.l===null||w.r===null){let t=w.l?w.l:w.r;if(S.length===0)e=t;else{let e=S[S.length-1];e.l===w?e.l=t:e.r=t}}else{let e=w,t=w.r;for(;t.l!==null;)e=t,t=t.l;w.k=t.k,w.v=t.v,e.l===t?e.l=t.r:e.r=t.r,w=e}S.push(w);for(let t=S.length-1;t>=0;t--){let w=S[t];w.updateHeight();let E=this.rebalanceNode(w);if(t>0){let e=S[t-1];e.l===w?e.l=E:e.r===w&&(e.r=E)}else e=E}return e}rangeSearch(e,t){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.l;if(E=w.pop(),E.k>=e&&E.k<=t)for(let e of E.v)S.add(e);if(E.k>t)break;E=E.r}return S}greaterThan(e,t=!1){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.r;if(E=w.pop(),t&&E.k>=e||!t&&E.k>e)for(let e of E.v)S.add(e);else if(E.k<=e)break;E=E.l}return S}lessThan(e,t=!1){let S=new Set,w=[],E=this.root;for(;E||w.length>0;){for(;E;)w.push(E),E=E.l;if(E=w.pop(),t&&E.k<=e||!t&&E.k<e)for(let e of E.v)S.add(e);else if(E.k>e)break;E=E.r}return S}},FlatTree=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let S=this.numberToDocumentId.get(t);S&&(S.delete(e),S.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let S=t[0];switch(S){case`eq`:{let t=e[S],w=this.numberToDocumentId.get(t);return w?Array.from(w):[]}case`in`:{let t=e[S],w=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)w.add(e)}return Array.from(w)}case`nin`:{let t=new Set(e[S]),w=new Set;for(let[e,S]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of S)w.add(e);return Array.from(w)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let S=t[0];switch(S){case`containsAll`:{let t=e[S].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let w=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(w)}case`containsAny`:{let t=e[S].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let w=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(w)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let S=new e;for(let[e,w]of t.numberToDocumentId)S.numberToDocumentId.set(e,new Set(w));return S}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function _boundedLevenshtein(e,t,S){if(S<0)return-1;if(e===t)return 0;let w=e.length,E=t.length;if(w===0)return E<=S?E:-1;if(E===0)return w<=S?w:-1;let D=Math.abs(w-E);if(e.startsWith(t))return D<=S?D:-1;if(t.startsWith(e))return 0;if(D>S)return-1;let O=[];for(let e=0;e<=w;e++){O[e]=[e];for(let t=1;t<=E;t++)O[e][t]=e===0?t:0}for(let D=1;D<=w;D++){let w=1/0;for(let S=1;S<=E;S++)e[D-1]===t[S-1]?O[D][S]=O[D-1][S-1]:O[D][S]=Math.min(O[D-1][S]+1,O[D][S-1]+1,O[D-1][S-1]+1),w=Math.min(w,O[D][S]);if(w>S)return-1}return O[w][E]<=S?O[w][E]:-1}function syncBoundedLevenshtein(e,t,S){let w=_boundedLevenshtein(e,t,S);return{distance:w,isBounded:w>=0}}var RadixNode=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,S){this.k=e,this.s=t,this.e=S}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,S,w){let E=[this];for(;E.length>0;){let D=E.pop();if(D.e){let{w:E,d:O}=D;if(S&&E!==t)continue;if(getOwnProperty(e,E)!==null)if(w)if(Math.abs(t.length-E.length)<=w&&syncBoundedLevenshtein(t,E,w).isBounded)e[E]=[];else continue;else e[E]=[];if(getOwnProperty(e,E)!=null&&O.size>0){let t=e[E];for(let e of O)t.includes(e)||t.push(e)}}D.c.size>0&&E.push(...D.c.values())}return e}insert(t,S){let w=this,E=0,D=t.length;for(;E<D;){let O=t[E],k=w.c.get(O);if(k){let O=k.s,j=O.length,F=0;for(;F<j&&E+F<D&&O[F]===t[E+F];)F++;if(F===j){if(w=k,E+=F,E===D){k.e||=!0,k.addDocument(S);return}continue}let L=O.slice(0,F),B=O.slice(F),H=t.slice(E+F),q=new e(L[0],L,!1);if(w.c.set(L[0],q),q.updateParent(w),k.s=B,k.k=B[0],q.c.set(B[0],k),k.updateParent(q),H){let t=new e(H[0],H,!0);t.addDocument(S),q.c.set(H[0],t),t.updateParent(q)}else q.e=!0,q.addDocument(S);return}else{let D=new e(O,t.slice(E),!0);D.addDocument(S),w.c.set(O,D),D.updateParent(w);return}}w.e||=!0,w.addDocument(S)}_findLevenshtein(e,t,S,w,E){let D=[{node:this,index:t,tolerance:S}];for(;D.length>0;){let{node:t,index:S,tolerance:O}=D.pop();if(t.w.startsWith(e)){t.findAllWords(E,e,!1,0);continue}if(O<0)continue;if(t.e){let{w:S,d:D}=t;if(S&&(syncBoundedLevenshtein(e,S,w).isBounded&&(E[S]=[]),getOwnProperty(E,S)!==void 0&&D.size>0)){let e=new Set(E[S]);for(let t of D)e.add(t);E[S]=Array.from(e)}}if(S>=e.length)continue;let k=e[S];if(t.c.has(k)){let e=t.c.get(k);D.push({node:e,index:S+1,tolerance:O})}D.push({node:t,index:S+1,tolerance:O-1});for(let[e,w]of t.c)D.push({node:w,index:S,tolerance:O-1}),e!==k&&D.push({node:w,index:S+1,tolerance:O-1})}}find(e){let{term:t,exact:S,tolerance:w}=e;if(w&&!S){let e={};return this._findLevenshtein(t,0,w,w,e),e}else{let e=this,E=0,D=t.length;for(;E<D;){let O=t[E],k=e.c.get(O);if(k){let O=k.s,j=O.length,F=0;for(;F<j&&E+F<D&&O[F]===t[E+F];)F++;if(F===j)e=k,E+=F;else if(E+F===D)if(F===D-E){if(S)return{};{let e={};return k.findAllWords(e,t,S,w),e}}else return{};else return{}}else return{}}let O={};return e.findAllWords(O,t,S,w),O}}contains(e){let t=this,S=0,w=e.length;for(;S<w;){let E=e[S],D=t.c.get(E);if(D){let E=D.s,O=E.length,k=0;for(;k<O&&S+k<w&&E[k]===e[S+k];)k++;if(k<O)return!1;S+=O,t=D}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,S=e.length,w=[];for(let E=0;E<S;E++){let S=e[E];if(t.c.has(S)){let e=t.c.get(S);w.push({parent:t,character:S}),E+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;w.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:S}=w.pop();e.c.delete(S),t=e}return!0}removeDocumentByWord(e,t,S=!0){if(!e)return!0;let w=this,E=e.length;for(let D=0;D<E;D++){let E=e[D];if(w.c.has(E)){let O=w.c.get(E);D+=O.s.length-1,w=O,S&&w.w!==e||w.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let S=Math.min(e.length,t.length),w=0;for(;w<S&&e.charCodeAt(w)===t.charCodeAt(w);)w++;return e.slice(0,w)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let S=new e(t.k,t.s,t.e);return S.w=t.w,S.d=new Set(t.d),S.c=new Map(t?.c?.map(([t,S])=>[t,e.fromJSON(S)])||[]),S}},RadixTree=class e extends RadixNode{constructor(){super(``,``,!1)}static fromJSON(t){let S=new e;return S.w=t.w,S.s=t.s,S.e=t.e,S.k=t.k,S.d=new Set(t.d),S.c=new Map(t?.c?.map(([e,t])=>[e,RadixNode.fromJSON(t)])||[]),S}toJSON(){return super.toJSON()}};const K$1=2,EARTH_RADIUS=6371e3;var BKDNode=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,S=null){let w=new e(t.point,t.docIDs);return w.parent=S,t.left&&(w.left=e.fromJSON(t.left,w)),t.right&&(w.right=e.fromJSON(t.right,w)),w}},BKDTree=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let S=this.getPointKey(e),w=this.nodeMap.get(S);if(w){t.forEach(e=>w.docIDs.add(e));return}let E=new BKDNode(e,t);if(this.nodeMap.set(S,E),this.root==null){this.root=E;return}let D=this.root,O=0;for(;;){if(O%K$1===0)if(e.lon<D.point.lon){if(D.left==null){D.left=E,E.parent=D;return}D=D.left}else{if(D.right==null){D.right=E,E.parent=D;return}D=D.right}else if(e.lat<D.point.lat){if(D.left==null){D.left=E,E.parent=D;return}D=D.left}else{if(D.right==null){D.right=E,E.parent=D;return}D=D.right}O++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),S=this.nodeMap.get(t);return S?Array.from(S.docIDs):null}removeDocByID(e,t){let S=this.getPointKey(e),w=this.nodeMap.get(S);w&&(w.docIDs.delete(t),w.docIDs.size===0&&(this.nodeMap.delete(S),this.deleteNode(w)))}deleteNode(e){let t=e.parent,S=e.left?e.left:e.right;S&&(S.parent=t),t?t.left===e?t.left=S:t.right===e&&(t.right=S):(this.root=S,this.root&&(this.root.parent=null))}searchByRadius(t,S,w=!0,E=`asc`,D=!1){let O=D?e.vincentyDistance:e.haversineDistance,k=[{node:this.root,depth:0}],j=[];for(;k.length>0;){let{node:e,depth:E}=k.pop();if(e==null)continue;let D=O(t,e.point);(w?D<=S:D>S)&&j.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&k.push({node:e.left,depth:E+1}),e.right!=null&&k.push({node:e.right,depth:E+1})}return E&&j.sort((e,S)=>{let w=O(t,e.point),D=O(t,S.point);return E.toLowerCase()===`asc`?w-D:D-w}),j}searchByPolygon(t,S=!0,w=null,E=!1){let D=[{node:this.root,depth:0}],O=[];for(;D.length>0;){let{node:w,depth:E}=D.pop();if(w==null)continue;w.left!=null&&D.push({node:w.left,depth:E+1}),w.right!=null&&D.push({node:w.right,depth:E+1});let k=e.isPointInPolygon(t,w.point);(k&&S||!k&&!S)&&O.push({point:w.point,docIDs:Array.from(w.docIDs)})}let k=e.calculatePolygonCentroid(t);if(w){let t=E?e.vincentyDistance:e.haversineDistance;O.sort((e,S)=>{let E=t(k,e.point),D=t(k,S.point);return w.toLowerCase()===`asc`?E-D:D-E})}return O}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let S=new e;return t.root&&(S.root=BKDNode.fromJSON(t.root),S.buildNodeMap(S.root)),S}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,S=0,w=0,E=e.length;for(let D=0,O=E-1;D<E;O=D++){let E=e[D].lon,k=e[D].lat,j=e[O].lon,F=e[O].lat,L=E*F-j*k;t+=L,S+=(E+j)*L,w+=(k+F)*L}t/=2;let D=6*t;return S/=D,w/=D,{lon:S,lat:w}}static isPointInPolygon(e,t){let S=!1,w=t.lon,E=t.lat,D=e.length;for(let t=0,O=D-1;t<D;O=t++){let D=e[t].lon,k=e[t].lat,j=e[O].lon,F=e[O].lat;k>E!=F>E&&w<(j-D)*(E-k)/(F-k)+D&&(S=!S)}return S}static haversineDistance(e,t){let S=Math.PI/180,w=e.lat*S,E=t.lat*S,D=(t.lat-e.lat)*S,O=(t.lon-e.lon)*S,k=Math.sin(D/2)*Math.sin(D/2)+Math.cos(w)*Math.cos(E)*Math.sin(O/2)*Math.sin(O/2);return EARTH_RADIUS*(2*Math.atan2(Math.sqrt(k),Math.sqrt(1-k)))}static vincentyDistance(e,t){let S=6378137,w=1/298.257223563,E=(1-w)*S,D=Math.PI/180,O=e.lat*D,k=t.lat*D,j=(t.lon-e.lon)*D,F=Math.atan((1-w)*Math.tan(O)),L=Math.atan((1-w)*Math.tan(k)),B=Math.sin(F),H=Math.cos(F),q=Math.sin(L),J=Math.cos(L),Y=j,ee,te=1e3,ne,ae,oe,se,ce,ue;do{let e=Math.sin(Y),t=Math.cos(Y);if(ne=Math.sqrt(J*e*(J*e)+(H*q-B*J*t)*(H*q-B*J*t)),ne===0)return 0;ae=B*q+H*J*t,oe=Math.atan2(ne,ae),se=H*J*e/ne,ce=1-se*se,ue=ae-2*B*q/ce,isNaN(ue)&&(ue=0);let S=w/16*ce*(4+w*(4-3*ce));ee=Y,Y=j+(1-S)*w*se*(oe+S*ne*(ue+S*ae*(-1+2*ue*ue)))}while(Math.abs(Y-ee)>1e-12&&--te>0);if(te===0)return NaN;let de=ce*(S*S-E*E)/(E*E),fe=1+de/16384*(4096+de*(-768+de*(320-175*de))),me=de/1024*(256+de*(-128+de*(74-47*de))),ge=me*ne*(ue+me/4*(ae*(-1+2*ue*ue)-me/6*ue*(-3+4*ne*ne)*(-3+4*ue*ue)));return E*fe*(oe-ge)}},BoolNode=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let S=new e;return S.true=new Set(t.true),S.false=new Set(t.false),S}};function BM25(e,t,S,w,E,{k:D,b:O,d:k}){return Math.log(1+(S-t+.5)/(t+.5))*(k+e*(D+1))/(e+D*(1-O+O*w/E))}const DEFAULT_SIMILARITY=.8;var VectorIndex=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let S=getMagnitude(t,this.size);this.vectors.set(e,[S,t])}remove(e){this.vectors.delete(e)}find(e,t,S){return e instanceof Float32Array||(e=new Float32Array(e)),findSimilarVectors(e,S,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[S,w]]of this.vectors)e.push([t,[S,Array.from(w)]]);return{size:this.size,vectors:e}}static fromJSON(t){let S=t,w=new e(S.size);for(let[e,[t,E]]of S.vectors)w.vectors.set(e,[t,new Float32Array(E)]);return w}};function getMagnitude(e,t){let S=0;for(let w=0;w<t;w++)S+=e[w]*e[w];return Math.sqrt(S)}function findSimilarVectors(e,t,S,w,E){let D=getMagnitude(e,w),O=[],k=t||S.keys();for(let t of k){let k=S.get(t);if(!k)continue;let j=k[0],F=k[1],L=0;for(let t=0;t<w;t++)L+=e[t]*F[t];let B=L/(D*j);B>=E&&O.push([t,B])}return O}function insertDocumentScoreParameters(e,t,S,w,E){let D=getInternalDocumentId(e.sharedInternalDocumentStore,S);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(E-1)+w.length)/E,e.fieldLengths[t][D]=w.length,e.frequencies[t][D]={}}function insertTokenScoreParameters(e,t,S,w,E){let D=0;for(let e of w)e===E&&D++;let O=getInternalDocumentId(e.sharedInternalDocumentStore,S),k=D/w.length;e.frequencies[t][O][E]=k,E in e.tokenOccurrences[t]||(e.tokenOccurrences[t][E]=0),e.tokenOccurrences[t][E]=(e.tokenOccurrences[t][E]??0)+1}function removeDocumentScoreParameters(e,t,S,w){let E=getInternalDocumentId(e.sharedInternalDocumentStore,S);w>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*w-e.fieldLengths[t][E])/(w-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][E]=void 0,e.frequencies[t][E]=void 0}function removeTokenScoreParameters(e,t,S){e.tokenOccurrences[t][S]--}function create$12(e,t,S,w,E=``){w||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[D,O]of Object.entries(S)){let S=`${E}${E?`.`:``}${D}`;if(typeof O==`object`&&!Array.isArray(O)){create$12(e,t,O,w,S);continue}if(isVectorType(O))w.searchableProperties.push(S),w.searchablePropertiesWithTypes[S]=O,w.vectorIndexes[S]={type:`Vector`,node:new VectorIndex(getVectorSize(O)),isArray:!1};else{let e=/\[/.test(O);switch(O){case`boolean`:case`boolean[]`:w.indexes[S]={type:`Bool`,node:new BoolNode,isArray:e};break;case`number`:case`number[]`:w.indexes[S]={type:`AVL`,node:new AVLTree(0,[]),isArray:e};break;case`string`:case`string[]`:w.indexes[S]={type:`Radix`,node:new RadixTree,isArray:e},w.avgFieldLength[S]=0,w.frequencies[S]={},w.tokenOccurrences[S]={},w.fieldLengths[S]={};break;case`enum`:case`enum[]`:w.indexes[S]={type:`Flat`,node:new FlatTree,isArray:e};break;case`geopoint`:w.indexes[S]={type:`BKD`,node:new BKDTree,isArray:e};break;default:throw createError(`INVALID_SCHEMA_TYPE`,Array.isArray(O)?`array`:O,S)}w.searchableProperties.push(S),w.searchablePropertiesWithTypes[S]=O}}return w}function insertScalarBuilder(e,t,S,w,E,D,O,k){return j=>{let{type:F,node:L}=t.indexes[S];switch(F){case`Bool`:L[j?`true`:`false`].add(w);break;case`AVL`:{let e=k?.avlRebalanceThreshold??1;L.insert(j,w,e);break}case`Radix`:{let k=D.tokenize(j,E,S,!1);e.insertDocumentScoreParameters(t,S,w,k,O);for(let E of k)e.insertTokenScoreParameters(t,S,w,k,E),L.insert(E,w);break}case`Flat`:L.insert(j,w);break;case`BKD`:L.insert(j,[w]);break}}}function insert$2(e,t,S,w,E,D,O,k,j,F,L){if(isVectorType(O))return insertVector(t,S,D,w,E);let B=insertScalarBuilder(e,t,S,E,k,j,F,L);if(!isArrayType(O))return B(D);let H=D,q=H.length;for(let e=0;e<q;e++)B(H[e])}function insertVector(e,t,S,w,E){e.vectorIndexes[t].node.add(E,S)}function removeScalar(e,t,S,w,E,D,O,k,j,F){if(isVectorType(O))return t.vectorIndexes[S].node.remove(E),!0;let{type:L,node:B}=t.indexes[S];switch(L){case`AVL`:return B.removeDocument(D,E),!0;case`Bool`:return B[D?`true`:`false`].delete(E),!0;case`Radix`:{let O=j.tokenize(D,k,S);e.removeDocumentScoreParameters(t,S,w,F);for(let w of O)e.removeTokenScoreParameters(t,S,w),B.removeDocumentByWord(w,E);return!0}case`Flat`:return B.removeDocument(E,D),!0;case`BKD`:return B.removeDocByID(D,E),!1}}function remove$1(e,t,S,w,E,D,O,k,j,F){if(!isArrayType(O))return removeScalar(e,t,S,w,E,D,O,k,j,F);let L=getInnerType(O),B=D,H=B.length;for(let D=0;D<H;D++)removeScalar(e,t,S,w,E,B[D],L,k,j,F);return!0}function calculateResultScores(e,t,S,w,E,D,O,k,j,F){let L=Array.from(w),B=e.avgFieldLength[t],H=e.fieldLengths[t],q=e.tokenOccurrences[t],J=e.frequencies[t],Y=typeof q[S]==`number`?q[S]??0:0,ee=L.length;for(let e=0;e<ee;e++){let w=L[e];if(j&&!j.has(w))continue;F.has(w)||F.set(w,new Map);let q=F.get(w);q.set(t,(q.get(t)||0)+1);let ee=BM25(J?.[w]?.[S]??0,Y,E,H[w],B,D);O.has(w)?O.set(w,O.get(w)+ee*k):O.set(w,ee*k)}}function search$1(e,t,S,w,E,D,O,k,j,F,L,B=0){let H=S.tokenize(t,w),q=H.length||1,J=new Map,Y=new Map,ee=new Map;for(let S of E){if(!(S in e.indexes))continue;let w=e.indexes[S],{type:E}=w;if(E!==`Radix`)throw createError(`WRONG_SEARCH_PROPERTY_TYPE`,S);let B=k[S]??1;if(B<=0)throw createError(`INVALID_BOOST_VALUE`,B);H.length===0&&!t&&H.push(``);let q=H.length;for(let t=0;t<q;t++){let E=H[t],k=w.node.find({term:E,exact:D,tolerance:O}),q=Object.keys(k);q.length>0&&Y.set(E,!0);let te=q.length;for(let t=0;t<te;t++){let w=q[t],E=k[w];calculateResultScores(e,S,w,E,F,j,ee,B,L,J)}}}let te=Array.from(ee.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(te.length===0)return[];if(B===1)return te;if(B===0){if(q===1)return te;for(let e of H)if(!Y.get(e))return[];return te.filter(([e])=>{let t=J.get(e);return t?Array.from(t.values()).some(e=>e===q):!1})}let ne=te.filter(([e])=>{let t=J.get(e);return t?Array.from(t.values()).some(e=>e===q):!1});if(ne.length>0){let e=te.filter(([e])=>!ne.some(([t])=>t===e)),t=Math.ceil(e.length*B);return[...ne,...e.slice(0,t)]}return te}function searchByWhereClause(e,t,S,w){if(`and`in S&&S.and&&Array.isArray(S.and)){let E=S.and;return E.length===0?new Set:setIntersection(...E.map(S=>searchByWhereClause(e,t,S,w)))}if(`or`in S&&S.or&&Array.isArray(S.or)){let E=S.or;return E.length===0?new Set:E.map(S=>searchByWhereClause(e,t,S,w)).reduce((e,t)=>setUnion(e,t),new Set)}if(`not`in S&&S.not){let E=S.not,D=new Set,O=e.sharedInternalDocumentStore;for(let e=1;e<=O.internalIdToId.length;e++)D.add(e);return setDifference(D,searchByWhereClause(e,t,E,w))}let E=Object.keys(S),D=E.reduce((e,t)=>({[t]:new Set,...e}),{});for(let O of E){let E=S[O];if(e.indexes[O]===void 0)throw createError(`UNKNOWN_FILTER_PROPERTY`,O);let{node:k,type:j,isArray:F}=e.indexes[O];if(j===`Bool`){let e=k,t=E?e.true:e.false;D[O]=setUnion(D[O],t);continue}if(j===`BKD`){let e;if(`radius`in E)e=`radius`;else if(`polygon`in E)e=`polygon`;else throw Error(`Invalid operation ${E}`);if(e===`radius`){let{value:t,coordinates:S,unit:w=`m`,inside:j=!0,highPrecision:F=!1}=E[e],L=convertDistanceToMeters(t,w),B=k.searchByRadius(S,L,j,void 0,F);D[O]=addGeoResult(D[O],B)}else{let{coordinates:t,inside:S=!0,highPrecision:w=!1}=E[e],j=k.searchByPolygon(t,S,void 0,w);D[O]=addGeoResult(D[O],j)}continue}if(j===`Radix`&&(typeof E==`string`||Array.isArray(E))){for(let e of[E].flat()){let S=t.tokenize(e,w,O);for(let e of S){let t=k.find({term:e,exact:!0});D[O]=addFindResult(D[O],t)}}continue}let L=Object.keys(E);if(L.length>1)throw createError(`INVALID_FILTER_OPERATION`,L.length);if(j===`Flat`){let e=new Set(F?k.filterArr(E):k.filter(E));D[O]=setUnion(D[O],e);continue}if(j===`AVL`){let e=L[0],t=E[e],S;switch(e){case`gt`:S=k.greaterThan(t,!1);break;case`gte`:S=k.greaterThan(t,!0);break;case`lt`:S=k.lessThan(t,!1);break;case`lte`:S=k.lessThan(t,!0);break;case`eq`:S=k.find(t)??new Set;break;case`between`:{let[e,w]=t;S=k.rangeSearch(e,w);break}default:throw createError(`INVALID_FILTER_OPERATION`,e)}D[O]=setUnion(D[O],S)}}return setIntersection(...Object.values(D))}function getSearchableProperties(e){return e.searchableProperties}function getSearchablePropertiesWithTypes(e){return e.searchablePropertiesWithTypes}function load$2(e,t){let{indexes:S,vectorIndexes:w,searchableProperties:E,searchablePropertiesWithTypes:D,frequencies:O,tokenOccurrences:k,avgFieldLength:j,fieldLengths:F}=t,L={},B={};for(let e of Object.keys(S)){let{node:t,type:w,isArray:E}=S[e];switch(w){case`Radix`:L[e]={type:`Radix`,node:RadixTree.fromJSON(t),isArray:E};break;case`Flat`:L[e]={type:`Flat`,node:FlatTree.fromJSON(t),isArray:E};break;case`AVL`:L[e]={type:`AVL`,node:AVLTree.fromJSON(t),isArray:E};break;case`BKD`:L[e]={type:`BKD`,node:BKDTree.fromJSON(t),isArray:E};break;case`Bool`:L[e]={type:`Bool`,node:BoolNode.fromJSON(t),isArray:E};break;default:L[e]=S[e]}}for(let e of Object.keys(w))B[e]={type:`Vector`,isArray:!1,node:VectorIndex.fromJSON(w[e])};return{sharedInternalDocumentStore:e,indexes:L,vectorIndexes:B,searchableProperties:E,searchablePropertiesWithTypes:D,frequencies:O,tokenOccurrences:k,avgFieldLength:j,fieldLengths:F}}function save$2(e){let{indexes:t,vectorIndexes:S,searchableProperties:w,searchablePropertiesWithTypes:E,frequencies:D,tokenOccurrences:O,avgFieldLength:k,fieldLengths:j}=e,F={};for(let e of Object.keys(S))F[e]=S[e].node.toJSON();let L={};for(let e of Object.keys(t)){let{type:S,node:w,isArray:E}=t[e];S===`Flat`||S===`Radix`||S===`AVL`||S===`BKD`||S===`Bool`?L[e]={type:S,node:w.toJSON(),isArray:E}:(L[e]=t[e],L[e].node=L[e].node.toJSON())}return{indexes:L,vectorIndexes:F,searchableProperties:w,searchablePropertiesWithTypes:E,frequencies:D,tokenOccurrences:O,avgFieldLength:k,fieldLengths:j}}function createIndex(){return{create:create$12,insert:insert$2,remove:remove$1,insertDocumentScoreParameters,insertTokenScoreParameters,removeDocumentScoreParameters,removeTokenScoreParameters,calculateResultScores,search:search$1,searchByWhereClause,getSearchableProperties,getSearchablePropertiesWithTypes,load:load$2,save:save$2}}function addGeoResult(e,t){e||=new Set;let S=t.length;for(let w=0;w<S;w++){let S=t[w].docIDs,E=S.length;for(let t=0;t<E;t++)e.add(S[t])}return e}function createGeoTokenScores(e,t,S=!1){let w=S?BKDTree.vincentyDistance:BKDTree.haversineDistance,E=[],D=[];for(let{point:S}of e)D.push(w(t,S));let O=Math.max(...D),k=0;for(let{docIDs:t}of e){let e=O-D[k]+1;for(let S of t)E.push([S,e]);k++}return E.sort((e,t)=>t[1]-e[1]),E}function isGeosearchOnlyQuery(e,t){let S=Object.keys(e);if(S.length!==1)return{isGeoOnly:!1};let w=S[0],E=e[w];if(t.indexes[w]===void 0)return{isGeoOnly:!1};let{type:D}=t.indexes[w];return D===`BKD`&&E&&(`radius`in E||`polygon`in E)?{isGeoOnly:!0,geoProperty:w,geoOperation:E}:{isGeoOnly:!1}}function searchByGeoWhereClause(e,t){let S=e,w=isGeosearchOnlyQuery(t,S);if(!w.isGeoOnly||!w.geoProperty||!w.geoOperation)return null;let{node:E}=S.indexes[w.geoProperty],D=w.geoOperation,O=E,k;if(`radius`in D){let{value:e,coordinates:t,unit:S=`m`,inside:w=!0,highPrecision:E=!1}=D.radius,j=t,F=convertDistanceToMeters(e,S);return k=O.searchByRadius(j,F,w,`asc`,E),createGeoTokenScores(k,j,E)}else if(`polygon`in D){let{coordinates:e,inside:t=!0,highPrecision:S=!1}=D.polygon;k=O.searchByPolygon(e,t,`asc`,S);let w=BKDTree.calculatePolygonCentroid(e);return createGeoTokenScores(k,w,S)}return null}function addFindResult(e,t){e||=new Set;let S=Object.keys(t),w=S.length;for(let E=0;E<w;E++){let w=t[S[E]],D=w.length;for(let t=0;t<D;t++)e.add(w[t])}return e}function innerCreate(e,t,S,w,E){let D={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[O,k]of Object.entries(S)){let S=`${E}${E?`.`:``}${O}`;if(!w.includes(S)){if(typeof k==`object`&&!Array.isArray(k)){let E=innerCreate(e,t,k,w,S);safeArrayPush(D.sortableProperties,E.sortableProperties),D.sorts={...D.sorts,...E.sorts},D.sortablePropertiesWithTypes={...D.sortablePropertiesWithTypes,...E.sortablePropertiesWithTypes};continue}if(!isVectorType(k))switch(k){case`boolean`:case`number`:case`string`:D.sortableProperties.push(S),D.sortablePropertiesWithTypes[S]=k,D.sorts[S]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:k};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw createError(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(k)?`array`:k,S)}}}return D}function create$11(e,t,S,w){return w?.enabled===!1?{disabled:!0}:innerCreate(e,t,S,(w||{}).unsortableProperties||[],``)}function insert$1(e,t,S,w){if(!e.enabled)return;e.isSorted=!1;let E=getInternalDocumentId(e.sharedInternalDocumentStore,S),D=e.sorts[t];D.orderedDocsToRemove.has(E)&&ensureOrderedDocsAreDeletedByProperty(e,t),D.docs.set(E,D.orderedDocs.length),D.orderedDocs.push([E,w])}function ensureIsSorted(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let S of t)ensurePropertyIsSorted(e,S);e.isSorted=!0}function stringSort(e,t,S){return t[1].localeCompare(S[1],getLocale(e))}function numberSort(e,t){return e[1]-t[1]}function booleanSort(e,t){return t[1]?-1:1}function ensurePropertyIsSorted(e,t){let S=e.sorts[t],w;switch(S.type){case`string`:w=stringSort.bind(null,e.language);break;case`number`:w=numberSort.bind(null);break;case`boolean`:w=booleanSort.bind(null);break}S.orderedDocs.sort(w);let E=S.orderedDocs.length;for(let e=0;e<E;e++){let t=S.orderedDocs[e][0];S.docs.set(t,e)}}function ensureOrderedDocsAreDeleted(e){let t=Object.keys(e.sorts);for(let S of t)ensureOrderedDocsAreDeletedByProperty(e,S)}function ensureOrderedDocsAreDeletedByProperty(e,t){let S=e.sorts[t];S.orderedDocsToRemove.size&&(S.orderedDocs=S.orderedDocs.filter(e=>!S.orderedDocsToRemove.has(e[0])),S.orderedDocsToRemove.clear())}function remove(e,t,S){if(!e.enabled)return;let w=e.sorts[t],E=getInternalDocumentId(e.sharedInternalDocumentStore,S);w.docs.get(E)&&(w.docs.delete(E),w.orderedDocsToRemove.set(E,!0))}function sortBy(e,t,S){if(!e.enabled)throw createError(`SORT_DISABLED`);let w=S.property,E=S.order===`DESC`,D=e.sorts[w];if(!D)throw createError(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,w,e.sortableProperties.join(`, `));return ensureOrderedDocsAreDeletedByProperty(e,w),ensureIsSorted(e),t.sort((t,S)=>{let w=D.docs.get(getInternalDocumentId(e.sharedInternalDocumentStore,t[0])),O=D.docs.get(getInternalDocumentId(e.sharedInternalDocumentStore,S[0])),k=w!==void 0,j=O!==void 0;return!k&&!j?0:k?j?E?O-w:w-O:-1:1}),t}function getSortableProperties(e){return e.enabled?e.sortableProperties:[]}function getSortablePropertiesWithTypes(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function load$1(e,t){let S=t;if(!S.enabled)return{enabled:!1};let w=Object.keys(S.sorts).reduce((e,t)=>{let{docs:w,orderedDocs:E,type:D}=S.sorts[t];return e[t]={docs:new Map(Object.entries(w).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:E,type:D},e},{});return{sharedInternalDocumentStore:e,language:S.language,sortableProperties:S.sortableProperties,sortablePropertiesWithTypes:S.sortablePropertiesWithTypes,sorts:w,enabled:!0,isSorted:S.isSorted}}function save$1(e){if(!e.enabled)return{enabled:!1};ensureOrderedDocsAreDeleted(e),ensureIsSorted(e);let t=Object.keys(e.sorts).reduce((t,S)=>{let{docs:w,orderedDocs:E,type:D}=e.sorts[S];return t[S]={docs:Object.fromEntries(w.entries()),orderedDocs:E,type:D},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function createSorter(){return{create:create$11,insert:insert$1,remove,save:save$1,load:load$1,sortBy,getSortableProperties,getSortablePropertiesWithTypes}}const DIACRITICS_CHARCODE_START=192,DIACRITICS_CHARCODE_END=383,CHARCODE_REPLACE_MAPPING=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function replaceChar(e){return e<DIACRITICS_CHARCODE_START||e>DIACRITICS_CHARCODE_END?e:CHARCODE_REPLACE_MAPPING[e-DIACRITICS_CHARCODE_START]||e}function replaceDiacritics(e){let t=[];for(let S=0;S<e.length;S++)t[S]=replaceChar(e.charCodeAt(S));return String.fromCharCode(...t)}const step2List={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},step3List={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},c=`[^aeiou]`,v=`[aeiouy]`,C=c+`[^aeiouy]*`;v+``;const mgr0=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,meq1=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`,mgr1=`^(`+C+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,s_v=`^(`+C+`)?[aeiouy]`;function stemmer(e){let t,S,w,E,D,O;if(e.length<3)return e;let k=e.substring(0,1);if(k==`y`&&(e=k.toUpperCase()+e.substring(1)),w=/^(.+?)(ss|i)es$/,E=/^(.+?)([^s])s$/,w.test(e)?e=e.replace(w,`$1$2`):E.test(e)&&(e=e.replace(E,`$1$2`)),w=/^(.+?)eed$/,E=/^(.+?)(ed|ing)$/,w.test(e)){let t=w.exec(e);w=new RegExp(mgr0),w.test(t[1])&&(w=/.$/,e=e.replace(w,``))}else E.test(e)&&(t=E.exec(e)[1],E=new RegExp(s_v),E.test(t)&&(e=t,E=/(at|bl|iz)$/,D=RegExp(`([^aeiouylsz])\\1$`),O=RegExp(`^`+C+v+`[^aeiouwxy]$`),E.test(e)?e+=`e`:D.test(e)?(w=/.$/,e=e.replace(w,``)):O.test(e)&&(e+=`e`)));if(w=/^(.+?)y$/,w.test(e)&&(t=w.exec(e)?.[1],w=new RegExp(s_v),t&&w.test(t)&&(e=t+`i`)),w=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,w.test(e)){let E=w.exec(e);t=E?.[1],S=E?.[2],w=new RegExp(mgr0),t&&w.test(t)&&(e=t+step2List[S])}if(w=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,w.test(e)){let E=w.exec(e);t=E?.[1],S=E?.[2],w=new RegExp(mgr0),t&&w.test(t)&&(e=t+step3List[S])}if(w=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,E=/^(.+?)(s|t)(ion)$/,w.test(e))t=w.exec(e)?.[1],w=new RegExp(mgr1),t&&w.test(t)&&(e=t);else if(E.test(e)){let S=E.exec(e);t=S?.[1]??``+S?.[2]??``,E=new RegExp(mgr1),E.test(t)&&(e=t)}return w=/^(.+?)e$/,w.test(e)&&(t=w.exec(e)?.[1],w=new RegExp(mgr1),E=new RegExp(meq1),D=RegExp(`^`+C+v+`[^aeiouwxy]$`),t&&(w.test(t)||E.test(t)&&!D.test(t))&&(e=t)),w=/ll$/,E=new RegExp(mgr1),w.test(e)&&E.test(e)&&(w=/.$/,e=e.replace(w,``)),k==`y`&&(e=k.toLowerCase()+e.substring(1)),e}function normalizeToken(e,t,S=!0){let w=`${this.language}:${e}:${t}`;return S&&this.normalizationCache.has(w)?this.normalizationCache.get(w):this.stopWords?.includes(t)?(S&&this.normalizationCache.set(w,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=replaceDiacritics(t),S&&this.normalizationCache.set(w,t),t)}function trim(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function tokenize(e,t,S,w=!0){if(t&&t!==this.language)throw createError(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let E=this.normalizeToken.bind(this,S??``),D;if(S&&this.tokenizeSkipProperties.has(S))D=[E(e,w)];else{let t=SPLITTERS[this.language];D=e.toLowerCase().split(t).map(e=>E(e,w)).filter(Boolean)}let O=trim(D);return this.allowDuplicates?O:Array.from(new Set(O))}function createTokenizer(e={}){if(!e.language)e.language=`english`;else if(!SUPPORTED_LANGUAGES.includes(e.language))throw createError(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw createError(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=stemmer;else throw createError(`MISSING_STEMMER`,e.language);let S;if(e.stopWords!==!1){if(S=[],Array.isArray(e.stopWords))S=e.stopWords;else if(typeof e.stopWords==`function`)S=e.stopWords(S);else if(e.stopWords)throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(S))throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of S)if(typeof e!=`string`)throw createError(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let w={tokenize,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:S,allowDuplicates:!!e.allowDuplicates,normalizeToken,normalizationCache:new Map};return w.tokenize=tokenize.bind(w),w.normalizeToken=normalizeToken,w}function create$10(e){return{sharedInternalDocumentStore:e,rules:new Map}}function addRule(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function updateRule(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function removeRule(e,t){return e.rules.delete(t)}function getRule(e,t){return e.rules.get(t)}function getAllRules(e){return Array.from(e.rules.values())}function matchesCondition(e,t){let S=e.toLowerCase().trim(),w=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return S===w;case`starts_with`:return S.startsWith(w);case`contains`:return S.includes(w);default:return!1}}function matchesRule(e,t){return e?t.conditions.every(t=>matchesCondition(e,t)):!1}function getMatchingRules(e,t){if(!t)return[];let S=[];for(let w of e.rules.values())matchesRule(t,w)&&S.push(w);return S}function load(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function save(e){return{rules:Array.from(e.rules.entries())}}function createPinning(){return{create:create$10,addRule,updateRule,removeRule,getRule,getAllRules,getMatchingRules,load,save}}function validateComponents(e){let t={formatElapsedTime,getDocumentIndexId,getDocumentProperties,validateSchema};for(let S of FUNCTION_COMPONENTS){let w=S;if(e[w]){if(typeof e[w]!=`function`)throw createError(`COMPONENT_MUST_BE_FUNCTION`,w)}else e[w]=t[w]}for(let t of Object.keys(e))if(!OBJECT_COMPONENTS.includes(t)&&!FUNCTION_COMPONENTS.includes(t))throw createError(`UNSUPPORTED_COMPONENT`,t)}function create$9({schema:e,sort:t,language:S,components:w,id:E,plugins:D}){w||={};for(let t of D??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let S=t.getComponents(e),E=Object.keys(S);for(let e of E)if(w[e])throw createError(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);w={...w,...S}}E||=uniqueId();let O=w.tokenizer,k=w.index,j=w.documentsStore,F=w.sorter,L=w.pinning;if(O=O?O.tokenize?O:createTokenizer(O):createTokenizer({language:S??`english`}),w.tokenizer&&S)throw createError(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let B=createInternalDocumentIDStore();k||=createIndex(),F||=createSorter(),j||=createDocumentsStore(),L||=createPinning(),validateComponents(w);let{getDocumentProperties:H,getDocumentIndexId:q,validateSchema:J,formatElapsedTime:Y}=w,ee={data:{},caches:{},schema:e,tokenizer:O,index:k,sorter:F,documentsStore:j,pinning:L,internalDocumentIDStore:B,getDocumentProperties:H,getDocumentIndexId:q,validateSchema:J,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:Y,id:E,plugins:D,version:getVersion()};ee.data={index:ee.index.create(ee,B,e),docs:ee.documentsStore.create(ee,B),sorting:ee.sorter.create(ee,B,e,t),pinning:ee.pinning.create(B)};for(let e of AVAILABLE_PLUGIN_HOOKS)ee[e]=(ee[e]??[]).concat(getAllPluginsByHook(ee,e));let te=ee.afterCreate;return te&&runAfterCreate(te,ee),ee}function getVersion(){return`{{VERSION}}`}function count(e){return e.documentsStore.count(e.data.docs)}function insert(e,t,S,w,E){let D=e.validateSchema(t,e.schema);if(D)throw createError(`SCHEMA_VALIDATION_FAILURE`,D);return isAsyncFunction(e.beforeInsert)||isAsyncFunction(e.afterInsert)||isAsyncFunction(e.index.beforeInsert)||isAsyncFunction(e.index.insert)||isAsyncFunction(e.index.afterInsert)?innerInsertAsync(e,t,S,w,E):innerInsertSync(e,t,S,w,E)}const ENUM_TYPE=new Set([`enum`,`enum[]`]),STRING_NUMBER_TYPE=new Set([`string`,`number`]);async function innerInsertAsync(e,t,S,w,E){let{index:D,docs:O}=e.data,k=e.getDocumentIndexId(t);if(typeof k!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof k);let j=getInternalDocumentId(e.internalDocumentIDStore,k);if(w||await runSingleHook(e.beforeInsert,e,k,t),!e.documentsStore.store(O,k,j,t))throw createError(`DOCUMENT_ALREADY_EXISTS`,k);let F=e.documentsStore.count(O),L=e.index.getSearchableProperties(D),B=e.index.getSearchablePropertiesWithTypes(D),H=e.getDocumentProperties(t,L);for(let[e,t]of Object.entries(H)){if(t===void 0)continue;let S=typeof t,w=B[e];validateDocumentProperty(S,w,e,t)}return await indexAndSortDocument(e,k,L,H,F,S,t,E),w||await runSingleHook(e.afterInsert,e,k,t),k}function innerInsertSync(e,t,S,w,E){let{index:D,docs:O}=e.data,k=e.getDocumentIndexId(t);if(typeof k!=`string`)throw createError(`DOCUMENT_ID_MUST_BE_STRING`,typeof k);let j=getInternalDocumentId(e.internalDocumentIDStore,k);if(w||runSingleHook(e.beforeInsert,e,k,t),!e.documentsStore.store(O,k,j,t))throw createError(`DOCUMENT_ALREADY_EXISTS`,k);let F=e.documentsStore.count(O),L=e.index.getSearchableProperties(D),B=e.index.getSearchablePropertiesWithTypes(D),H=e.getDocumentProperties(t,L);for(let[e,t]of Object.entries(H)){if(t===void 0)continue;let S=typeof t,w=B[e];validateDocumentProperty(S,w,e,t)}return indexAndSortDocumentSync(e,k,L,H,F,S,t,E),w||runSingleHook(e.afterInsert,e,k,t),k}function validateDocumentProperty(e,t,S,w){if(!(isGeoPointType(t)&&typeof w==`object`&&typeof w.lon==`number`&&typeof w.lat==`number`)&&!(isVectorType(t)&&Array.isArray(w))&&!(isArrayType(t)&&Array.isArray(w))&&!(ENUM_TYPE.has(t)&&STRING_NUMBER_TYPE.has(e))&&e!==t)throw createError(`INVALID_DOCUMENT_PROPERTY`,S,t,e)}async function indexAndSortDocument(e,t,S,w,E,D,O,k){for(let O of S){let S=w[O];if(S===void 0)continue;let j=e.index.getSearchablePropertiesWithTypes(e.data.index)[O];await e.index.beforeInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E);let F=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,O,t,F,S,j,D,e.tokenizer,E,k),await e.index.afterInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E)}let j=e.sorter.getSortableProperties(e.data.sorting),F=e.getDocumentProperties(O,j);for(let S of j){let w=F[S];if(w===void 0)continue;let E=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[S];e.sorter.insert(e.data.sorting,S,t,w,E,D)}}function indexAndSortDocumentSync(e,t,S,w,E,D,O,k){for(let O of S){let S=w[O];if(S===void 0)continue;let j=e.index.getSearchablePropertiesWithTypes(e.data.index)[O],F=getInternalDocumentId(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E),e.index.insert(e.index,e.data.index,O,t,F,S,j,D,e.tokenizer,E,k),e.index.afterInsert?.(e.data.index,O,t,S,j,D,e.tokenizer,E)}let j=e.sorter.getSortableProperties(e.data.sorting),F=e.getDocumentProperties(O,j);for(let S of j){let w=F[S];if(w===void 0)continue;let E=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[S];e.sorter.insert(e.data.sorting,S,t,w,E,D)}}function insertMultiple(e,t,S,w,E,D){return isAsyncFunction(e.afterInsertMultiple)||isAsyncFunction(e.beforeInsertMultiple)||isAsyncFunction(e.index.beforeInsert)||isAsyncFunction(e.index.insert)||isAsyncFunction(e.index.afterInsert)?innerInsertMultipleAsync(e,t,S,w,E,D):innerInsertMultipleSync(e,t,S,w,E,D)}async function innerInsertMultipleAsync(e,t,S=1e3,w,E,D=0){let O=[],k=async D=>{let k=Math.min(D+S,t.length),j=t.slice(D,k);for(let t of j){let S=await insert(e,t,w,E,{avlRebalanceThreshold:j.length});O.push(S)}return k};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await k(e),D>0){let e=D-(Date.now()-t);e>0&&sleep$1(e)}}})(),E||await runMultipleHook(e.afterInsertMultiple,e,t),O}function innerInsertMultipleSync(e,t,S=1e3,w,E,D=0){let O=[],k=0;function j(){let D=t.slice(k*S,(k+1)*S);if(D.length===0)return!1;for(let t of D){let S=insert(e,t,w,E,{avlRebalanceThreshold:D.length});O.push(S)}return k++,!0}function F(){let e=Date.now();for(;j();)if(D>0){let t=Date.now()-e;if(t>=D){let e=D-t%D;e>0&&sleep$1(e)}}}return F(),E||runMultipleHook(e.afterInsertMultiple,e,t),O}const MODE_FULLTEXT_SEARCH=`fulltext`,MODE_HYBRID_SEARCH=`hybrid`,MODE_VECTOR_SEARCH=`vector`;function sortAsc(e,t){return e[1]-t[1]}function sortDesc(e,t){return t[1]-e[1]}function sortingPredicateBuilder(e=`desc`){return e.toLowerCase()===`asc`?sortAsc:sortDesc}function getFacets(e,t,S){let w={},E=t.map(([e])=>e),D=e.documentsStore.getMultiple(e.data.docs,E),O=Object.keys(S),k=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of O){let t;if(k[e]===`number`){let{ranges:w}=S[e],E=w.length,D=Array.from({length:E});for(let e=0;e<E;e++){let t=w[e];D[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(D)}w[e]={count:0,values:t??{}}}let j=D.length;for(let e=0;e<j;e++){let t=D[e];for(let e of O){let E=e.includes(`.`)?getNested(t,e):t[e],D=k[e],O=w[e].values;switch(D){case`number`:{let t=S[e].ranges;calculateNumberFacetBuilder(t,O)(E);break}case`number[]`:{let t=new Set,w=S[e].ranges,D=calculateNumberFacetBuilder(w,O,t);for(let e of E)D(e);break}case`boolean`:case`enum`:case`string`:calculateBooleanStringOrEnumFacetBuilder(O,D)(E);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=calculateBooleanStringOrEnumFacetBuilder(O,D===`boolean[]`?`boolean`:`string`,new Set);for(let t of E)e(t);break}default:throw createError(`FACET_NOT_SUPPORTED`,D)}}}for(let e of O){let t=w[e];if(t.count=Object.keys(t.values).length,k[e]===`string`){let w=S[e],E=sortingPredicateBuilder(w.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(E).slice(w.offset??0,w.limit??10))}}return w}function calculateNumberFacetBuilder(e,t,S){return w=>{for(let E of e){let e=`${E.from}-${E.to}`;S?.has(e)||w>=E.from&&w<=E.to&&(t[e]===void 0?t[e]=1:(t[e]++,S?.add(e)))}}}function calculateBooleanStringOrEnumFacetBuilder(e,t,S){let w=t===`boolean`?`false`:``;return t=>{let E=t?.toString()??w;S?.has(E)||(e[E]=(e[E]??0)+1,S?.add(E))}}const DEFAULT_REDUCE={reducer:(e,t,S,w)=>(t[w]=S,t),getInitialValue:e=>Array.from({length:e})},ALLOWED_TYPES=[`string`,`number`,`boolean`];function getGroups(e,t,S){let w=S.properties,E=w.length,D=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<E;e++){let t=w[e];if(D[t]===void 0)throw createError(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!ALLOWED_TYPES.includes(D[t]))throw createError(`INVALID_GROUP_BY_PROPERTY`,t,ALLOWED_TYPES.join(`, `),D[t])}let O=t.map(([t])=>getDocumentIdFromInternalId(e.internalDocumentIDStore,t)),k=e.documentsStore.getMultiple(e.data.docs,O),j=k.length,F=S.maxResult||2**53-1,L=[],B={};for(let e=0;e<E;e++){let t=w[e],S={property:t,perValue:{}},E=new Set;for(let e=0;e<j;e++){let w=k[e],D=getNested(w,t);if(D===void 0)continue;let O=typeof D==`boolean`?``+D:D,j=S.perValue[O]??{indexes:[],count:0};j.count>=F||(j.indexes.push(e),j.count++,S.perValue[O]=j,E.add(D))}L.push(Array.from(E)),B[t]=S}let H=calculateCombination(L),q=H.length,J=[];for(let e=0;e<q;e++){let t=H[e],S=t.length,E={values:[],indexes:[]},D=[];for(let e=0;e<S;e++){let S=t[e],O=w[e];D.push(B[O].perValue[typeof S==`boolean`?``+S:S].indexes),E.values.push(S)}E.indexes=intersect(D).sort((e,t)=>e-t),E.indexes.length!==0&&J.push(E)}let Y=J.length,ee=Array.from({length:Y});for(let e=0;e<Y;e++){let w=J[e],E=S.reduce||DEFAULT_REDUCE,D=w.indexes.map(e=>({id:O[e],score:t[e][1],document:k[e]})),j=E.reducer.bind(null,w.values),F=E.getInitialValue(w.indexes.length),L=D.reduce(j,F);ee[e]={values:w.values,result:L}}return ee}function calculateCombination(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let S=e[t],w=calculateCombination(e,t+1),E=[];for(let e of S)for(let t of w){let S=[e];safeArrayPush(S,t),E.push(S)}return E}function applyPinningRules(e,t,S,w){let E=getMatchingRules(t,w);if(E.length===0)return S;let D=E.flatMap(e=>e.consequence.promote);D.sort((e,t)=>e.position-t.position);let O=new Set,k=new Map,j=new Set;for(let t of D){let S=getInternalDocumentId(e.internalDocumentIDStore,t.doc_id);if(S!==void 0){if(k.has(S)){let e=k.get(S);t.position<e&&k.set(S,t.position);continue}j.has(t.position)||(O.add(S),k.set(S,t.position),j.add(t.position))}}if(k.size===0)return S;let F=S.filter(([e])=>!O.has(e)),L=1e6,B=[];for(let[t,w]of k.entries())S.find(([e])=>e===t)?B.push([t,1e6-w]):e.documentsStore.get(e.data.docs,t)&&B.push([t,0]);B.sort((e,t)=>(k.get(e[0])??1/0)-(k.get(t[0])??1/0));let H=[],q=new Map;for(let e of B){let t=k.get(e[0]);q.set(t,e)}let J=0,Y=0;for(;Y<F.length+B.length;)if(q.has(Y))H.push(q.get(Y)),Y++;else if(J<F.length)H.push(F[J]),J++,Y++;else break;for(let[e,t]of q.entries())e>=H.length&&H.push(t);return H}function innerFullTextSearch(e,t,S){let{term:w,properties:E}=t,D=e.data.index,O=e.caches.propertiesToSearch;if(!O){let t=e.index.getSearchablePropertiesWithTypes(D);O=e.index.getSearchableProperties(D),O=O.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=O}if(E&&E!==`*`){for(let e of E)if(!O.includes(e))throw createError(`UNKNOWN_INDEX`,e,O.join(`, `));O=O.filter(e=>E.includes(e))}let k=Object.keys(t.where??{}).length>0,j;k&&(j=e.index.searchByWhereClause(D,e.tokenizer,t.where,S));let F,L=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(w||E){let E=count(e);if(F=e.index.search(D,w||``,e.tokenizer,S,O,t.exact||!1,t.tolerance||0,t.boost||{},applyDefault(t.relevance),E,j,L),t.exact&&w){let t=w.trim().split(/\s+/);F=F.filter(([S])=>{let w=e.documentsStore.get(e.data.docs,S);if(!w)return!1;for(let e of O){let S=getPropValue(w,e);if(typeof S==`string`&&t.every(e=>RegExp(`\\b${escapeRegex(e)}\\b`).test(S)))return!0}return!1})}}else F=k?searchByGeoWhereClause(D,t.where)||(j?Array.from(j):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return F}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function getPropValue(e,t){let S=t.split(`.`),w=e;for(let e of S)if(w&&typeof w==`object`&&e in w)w=w[e];else return;return w}function fullTextSearch(e,t,S){let w=getNanosecondsTime();function E(){let E=Object.keys(e.data.index.vectorIndexes),D=t.facets&&Object.keys(t.facets).length>0,{limit:O=10,offset:k=0,distinctOn:j,includeVectors:F=!1}=t,L=t.preflight===!0,B=innerFullTextSearch(e,t,S);if(t.sortBy)if(typeof t.sortBy==`function`){let S=B.map(([e])=>e),w=e.documentsStore.getMultiple(e.data.docs,S).map((e,t)=>[B[t][0],B[t][1],e]);w.sort(t.sortBy),B=w.map(([e,t])=>[e,t])}else B=e.sorter.sortBy(e.data.sorting,B,t.sortBy).map(([t,S])=>[getInternalDocumentId(e.internalDocumentIDStore,t),S]);else B=B.sort(sortTokenScorePredicate);B=applyPinningRules(e,e.data.pinning,B,t.term);let H;L||(H=j?fetchDocumentsWithDistinct(e,B,k,O,j):fetchDocuments(e,B,k,O));let q={elapsed:{formatted:``,raw:0},hits:[],count:B.length};return H!==void 0&&(q.hits=H.filter(Boolean),F||removeVectorsFromHits(q,E)),D&&(q.facets=getFacets(e,B,t.facets)),t.groupBy&&(q.groups=getGroups(e,B,t.groupBy)),q.elapsed=e.formatElapsedTime(getNanosecondsTime()-w),q}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}const defaultBM25Params={k:1.2,b:.75,d:.5};function applyDefault(e){let t=e??{};return t.k=t.k??defaultBM25Params.k,t.b=t.b??defaultBM25Params.b,t.d=t.d??defaultBM25Params.d,t}function innerVectorSearch(e,t,S){let w=t.vector;if(w&&(!(`value`in w)||!(`property`in w)))throw createError(`INVALID_VECTOR_INPUT`,Object.keys(w).join(`, `));let E=e.data.index.vectorIndexes[w.property];if(!E)throw createError(`UNKNOWN_VECTOR_PROPERTY`,w.property);let D=E.node.size;if(w?.value.length!==D)throw w?.property===void 0||w?.value.length===void 0?createError(`INVALID_INPUT_VECTOR`,`undefined`,D,`undefined`):createError(`INVALID_INPUT_VECTOR`,w.property,D,w.value.length);let O=e.data.index,k;return Object.keys(t.where??{}).length>0&&(k=e.index.searchByWhereClause(O,e.tokenizer,t.where,S)),E.node.find(w.value,t.similarity??.8,k)}function searchVector(e,t,S=`english`){let w=getNanosecondsTime();function E(){let E=innerVectorSearch(e,t,S).sort(sortTokenScorePredicate);E=applyPinningRules(e,e.data.pinning,E,void 0);let D=[];t.facets&&Object.keys(t.facets).length>0&&(D=getFacets(e,E,t.facets));let O=t.vector.property,k=t.includeVectors??!1,j=t.limit??10,F=t.offset??0,L=Array.from({length:j});for(let t=0;t<j;t++){let S=E[t+F];if(!S)break;let w=e.data.docs.docs[S[0]];w&&(k||(w[O]=null),L[t]={id:getDocumentIdFromInternalId(e.internalDocumentIDStore,S[0]),score:S[1],document:w})}let B=[];t.groupBy&&(B=getGroups(e,E,t.groupBy));let H=getNanosecondsTime()-w;return{count:E.length,hits:L.filter(Boolean),elapsed:{raw:Number(H),formatted:formatNanoseconds(H)},...D?{facets:D}:{},...B?{groups:B}:{}}}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}function innerHybridSearch(e,t,S){let w=minMaxScoreNormalization(innerFullTextSearch(e,t,S)),E=innerVectorSearch(e,t,S),D=t.hybridWeights;return mergeAndRankResults(w,E,t.term??``,D)}function hybridSearch(e,t,S){let w=getNanosecondsTime();function E(){let E=innerHybridSearch(e,t,S);E=applyPinningRules(e,e.data.pinning,E,t.term);let D;t.facets&&Object.keys(t.facets).length>0&&(D=getFacets(e,E,t.facets));let O;t.groupBy&&(O=getGroups(e,E,t.groupBy));let k=t.offset??0,j=t.limit??10,F=fetchDocuments(e,E,k,j).filter(Boolean),L=getNanosecondsTime(),B={count:E.length,elapsed:{raw:Number(L-w),formatted:formatNanoseconds(L-w)},hits:F,...D?{facets:D}:{},...O?{groups:O}:{}};return(t.includeVectors??!1)||removeVectorsFromHits(B,Object.keys(e.data.index.vectorIndexes)),B}async function D(){e.beforeSearch&&await runBeforeSearch(e.beforeSearch,e,t,S);let w=E();return e.afterSearch&&await runAfterSearch(e.afterSearch,e,t,S,w),w}return e.beforeSearch?.length||e.afterSearch?.length?D():E()}function extractScore(e){return e[1]}function minMaxScoreNormalization(e){let t=Math.max.apply(Math,e.map(extractScore));return e.map(([e,S])=>[e,S/t])}function normalizeScore(e,t){return e/t}function hybridScoreBuilder(e,t){return(S,w)=>S*e+w*t}function mergeAndRankResults(e,t,S,w){let E=Math.max.apply(Math,e.map(extractScore)),D=Math.max.apply(Math,t.map(extractScore)),{text:O,vector:k}=w&&w.text&&w.vector?w:getQueryWeights(S),j=new Map,F=e.length,L=hybridScoreBuilder(O,k);for(let t=0;t<F;t++){let[S,w]=e[t],D=L(normalizeScore(w,E),0);j.set(S,D)}let B=t.length;for(let e=0;e<B;e++){let[S,w]=t[e],E=normalizeScore(w,D),O=j.get(S)??0;j.set(S,O+L(0,E))}return[...j].sort((e,t)=>t[1]-e[1])}function getQueryWeights(e){return{text:.5,vector:.5}}function search(e,t,S){let w=t.mode??`fulltext`;if(w===`fulltext`)return fullTextSearch(e,t,S);if(w===`vector`)return searchVector(e,t);if(w===`hybrid`)return hybridSearch(e,t);throw createError(`INVALID_SEARCH_MODE`,w)}function fetchDocumentsWithDistinct(e,t,S,w,E){let D=e.data.docs,O=new Map,k=[],j=new Set,F=t.length,L=0;for(let B=0;B<F;B++){let F=t[B];if(F===void 0)continue;let[H,q]=F;if(j.has(H))continue;let J=e.documentsStore.get(D,H),Y=getNested(J,E);if(!(Y===void 0||O.has(Y))&&(O.set(Y,!0),L++,!(L<=S)&&(k.push({id:getDocumentIdFromInternalId(e.internalDocumentIDStore,H),score:q,document:J}),j.add(H),L>=S+w)))break}return k}function fetchDocuments(e,t,S,w){let E=e.data.docs,D=Array.from({length:w}),O=new Set;for(let k=S;k<w+S;k++){let S=t[k];if(S===void 0)break;let[w,j]=S;if(!O.has(w)){let t=e.documentsStore.get(E,w);D[k]={id:getDocumentIdFromInternalId(e.internalDocumentIDStore,w),score:j,document:t},O.add(w)}}return D}var import_diff_match_patch=__toESM$1(require_diff_match_patch(),1);const dmp$1=new import_diff_match_patch.default;function diffLinesFast(e,t){if(e===t)return[{value:e}];let{chars1:S,chars2:w,lineArray:E}=dmp$1.diff_linesToChars_(e,t),D=dmp$1.diff_main(S,w,!1);dmp$1.diff_charsToLines_(D,E),dmp$1.diff_cleanupSemantic(D);let O=[];for(let[e,t]of D)e===import_diff_match_patch.default.DIFF_DELETE?O.push({value:t,removed:!0}):e===import_diff_match_patch.default.DIFF_INSERT?O.push({value:t,added:!0}):O.push({value:t});return O}const dmpDiff=new import_diff_match_patch.default;dmpDiff.Diff_Timeout=.25;const APPLY_FAST_DIFF_MAX_BYTES=256*1024;function applyIncrementalDiff(e,t,S){if(t===S)return;let w=diffLinesFast(t,S),E=0;for(let S=0;S<w.length;S++){let D=w[S],O=w[S+1];if(D.removed&&O?.added){if(t.substring(E,E+O.value.length)===O.value){E+=O.value.length,S++;continue}e.delete(E,D.value.length),e.insert(E,O.value),E+=O.value.length,S++}else D.removed?e.delete(E,D.value.length):(D.added&&e.insert(E,D.value),E+=D.value.length)}}function applyFastDiff(e,t,S){if(t===S)return;if(t.length>APPLY_FAST_DIFF_MAX_BYTES||S.length>APPLY_FAST_DIFF_MAX_BYTES){applyByPrefixSuffixMiddleReplace(e,t,S);return}let w=dmpDiff.diff_main(t,S);dmpDiff.diff_cleanupSemantic(w);let E=0;for(let[t,S]of w)t===0?E+=S.length:t===-1?e.delete(E,S.length):t===1&&(e.insert(E,S),E+=S.length)}function applyByPrefixSuffixMiddleReplace(e,t,S){let w=0,E=Math.min(t.length,S.length);for(;w<E&&t.charCodeAt(w)===S.charCodeAt(w);)w++;let D=0;for(;D<E-w&&t.charCodeAt(t.length-1-D)===S.charCodeAt(S.length-1-D);)D++;let O=t.length-w-D,k=S.slice(w,S.length-D);O>0&&e.delete(w,O),k.length>0&&e.insert(w,k)}const FrontmatterIssueSchema=object$1({path:array(union([string$2(),number$1()])),message:string$2(),issueCode:string$2()}),FrontmatterValidationErrorSchema=discriminatedUnion(`code`,[object$1({code:literal(`SCHEMA_INVALID`),issues:array(FrontmatterIssueSchema)}),object$1({code:literal(`WRITE_ERROR`),detail:string$2()})]),FRONTMATTER_TYPES=[`text`,`number`,`boolean`,`date`,`list`],FrontmatterTypeSchema=_enum(FRONTMATTER_TYPES),FrontmatterValueSchema=union([string$2(),number$1(),boolean$1(),array(union([string$2(),number$1(),boolean$1()]).transform(e=>String(e)))]),FrontmatterMapSchema=record(string$2(),FrontmatterValueSchema),FrontmatterPatchSchema=record(string$2(),union([FrontmatterValueSchema,_null()])),FRONTMATTER_RE$1=/^---\r?\n([\s\S]*?\r?\n)?---(\r?\n|$)/;function stripFrontmatter(e){let t=e.match(FRONTMATTER_RE$1);return t?{frontmatter:t[0],body:e.slice(t[0].length)}:{frontmatter:``,body:e}}function prependFrontmatter(e,t){return e?e+t:t}function unwrapFrontmatterFences(e){if(e===``)return``;let t=e.match(FRONTMATTER_RE$1);return t?(t[1]??``).replace(/\r?\n$/,``):e}const STRINGIFY_OPTIONS={defaultKeyType:`PLAIN`,defaultStringType:`PLAIN`,lineWidth:0};function parseFrontmatterYaml(e){if(e.trim()===``)return{doc:new import_dist$1.Document({}),map:{}};let t;try{t=(0,import_dist$1.parseDocument)(e)}catch(e){let t=e instanceof Error?e.message:String(e);return{doc:new import_dist$1.Document({}),map:null,parseError:`parse threw: ${t}`}}if(t.errors.length>0)return{doc:t,map:null,parseError:t.errors[0]?.message??`yaml parse errors`};let S;try{S=t.toJS()}catch(e){let S=e instanceof Error?e.message:String(e);return{doc:t,map:null,parseError:`toJS threw: ${S}`}}if(typeof S!=`object`||!S||Array.isArray(S))return{doc:t,map:null,parseError:`top-level value is not a mapping`};let w=FrontmatterMapSchema.safeParse(S);if(!w.success){let e=w.error.issues[0],S=e&&Array.isArray(e.path)?e.path.join(`.`):``,E=e?.message??`unknown`;return{doc:t,map:null,parseError:S?`value at "${S}" failed schema: ${E}`:`schema validation failed: ${E}`}}return{doc:t,map:w.data}}function withFences(e){return e===``?``:`---\n${e.endsWith(`
|
|
300
|
+
`)?e.slice(0,-1):e}\n---\n`}const MAX_FM_REGION_BYTES=65536;function detectFmRegion(e){let t=e.match(FRONTMATTER_RE$1);return t?{fenced:t[0],body:e.slice(t[0].length)}:{fenced:``,body:e}}function parseFmRegion(e){if(e.trim()===``)return{doc:new import_dist$1.Document({}),map:{}};let t;try{t=(0,import_dist$1.parseDocument)(e,{uniqueKeys:!1})}catch(e){let t=e instanceof Error?e.message:String(e);return{doc:new import_dist$1.Document({}),map:null,parseError:`parse threw: ${t}`}}if(t.errors.length>0)return{doc:t,map:null,parseError:t.errors[0]?.message??`yaml parse errors`};let S;try{S=t.toJS()}catch(e){let S=e instanceof Error?e.message:String(e);return{doc:t,map:null,parseError:`toJS threw: ${S}`}}if(typeof S!=`object`||!S||Array.isArray(S))return{doc:t,map:null,parseError:`top-level value is not a mapping`};let w=FrontmatterMapSchema.safeParse(S);if(!w.success){let e=w.error.issues[0],S=e&&Array.isArray(e.path)?e.path.join(`.`):``,E=e?.message??`unknown`;return{doc:t,map:null,parseError:S?`value at "${S}" failed schema: ${E}`:`schema validation failed: ${E}`}}return{doc:t,map:w.data}}function parseFencedFmRegion(e){return e===``?{doc:new import_dist$1.Document({}),map:{}}:parseFmRegion(unwrapFrontmatterFences(e))}function readFmMap(e){let{fenced:t}=detectFmRegion(e),{map:S}=parseFencedFmRegion(t);return S??{}}const RESERVED_FRONTMATTER_KEY$1=`frontmatter`;function ensureContents(e){if(e.contents==null||!(`items`in e.contents)){let t=e.createNode({});return e.contents=t,t}return e.contents}function stringify$1(e){let t=e.contents;return!t||!(`items`in t)||(t.items?.length??0)===0?``:withFences(e.toString(STRINGIFY_OPTIONS))}function checkRegionSize(e){let t=new TextEncoder().encode(e).byteLength;return t>65536?{kind:`region_too_large`,bytes:t,limit:MAX_FM_REGION_BYTES}:null}function applyPatchToFm(e,t){if(Object.hasOwn(t,RESERVED_FRONTMATTER_KEY$1))return{ok:!1,error:{kind:`reserved_key`,key:RESERVED_FRONTMATTER_KEY$1}};let{doc:S,map:w}=parseFencedFmRegion(e);if(w===null)return{ok:!1,error:{kind:`parse_failed`,reason:`fm region unparseable`}};try{ensureContents(S);for(let[e,w]of Object.entries(t)){if(w===null){S.delete(e);continue}let t=FrontmatterValueSchema.safeParse(w);if(!t.success)return{ok:!1,error:{kind:`invalid_value`,key:e,reason:t.error.issues[0]?.message??`invalid value`}};if(Array.isArray(t.data)){let w=S.get(e,!0),E=(0,import_dist$1.isSeq)(w)?w.flow:void 0,D=S.createNode(t.data);E!==void 0&&(D.flow=E),S.set(e,D);continue}S.set(e,t.data)}let e=stringify$1(S),w=checkRegionSize(e);return w?{ok:!1,error:w}:{ok:!0,nextFenced:e}}catch(e){return{ok:!1,error:{kind:`parse_failed`,reason:`yaml@2 threw: ${e instanceof Error?e.message:String(e)}`}}}}const FORM_WRITE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!1,context:Object.freeze({origin:`form-write`})});function fnv1aDigest(e){let t=2166136261;for(let S=0;S<e.length;S++)t^=e.charCodeAt(S),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function toBridgeInvariantLog(e,t){let S=t?.verbose===!0,w=t?.nowMs===void 0?new Date().toISOString():new Date(t.nowMs).toISOString(),E={event:`bridge-invariant-violation`,site:e.site,"doc.name":e.docName??null,"tolerance-class-attempted":`untracked`,"normalize-equal-modulo-tolerance":!1,ytextLen:e.ytextSnapshot.length,fragmentLen:e.fragmentMdSnapshot.length,ytextHash:fnv1aDigest(e.ytextSnapshot),fragmentHash:fnv1aDigest(e.fragmentMdSnapshot),redacted:!S,timestamp:w};return S?{...E,diff:e.unifiedDiff}:E}var BridgeInvariantViolationError=class extends Error{violation;constructor(e){let t=typeof e.origin==`string`?e.origin:e.origin?.context?.origin??`unknown-object`,S=e.docName?` doc='${e.docName}'`:``;super(`Bridge invariant violated [site='${e.site}'${S}, origin='${t}'].\n Y.Text (${e.ytextSnapshot.length} chars): ${e.ytextSnapshot.slice(0,200)}...\n Fragment (${e.fragmentMdSnapshot.length} chars): ${e.fragmentMdSnapshot.slice(0,200)}...\n Diff:\n${e.unifiedDiff}`),this.name=`BridgeInvariantViolationError`,this.violation=e}};const dmp=new import_diff_match_patch.default;dmp.Match_Threshold=.5;function mergeThreeWay(e,t,S){let w=mergeThreeWayImpl(e,t,S);return assertContentPreservation(e,t,S,w),w}function mergeThreeWayImpl(e,t,S){if(e===t)return S;if(e===S||t===S)return t;let w=diff3Merge(t.split(`
|
|
300
301
|
`),e.split(`
|
|
301
302
|
`),S.split(`
|
|
302
303
|
`)),E=[];for(let e=0;e<w.length;e++){let t=w[e];if(`ok`in t&&t.ok)E.push(t.ok.join(`
|
|
@@ -323,8 +324,8 @@ $2`).split(`
|
|
|
323
324
|
`)].join(`
|
|
324
325
|
`);case`REMOVED_KEY`:{let t=e.path.join(`.`),S=[`${e.source?`Removed key at ${e.source.file}:${e.source.line}:${e.source.column}`:`Removed key in configuration`}: ${t}`,e.redirect];if(e.source?.snippet&&e.source.snippet.length>0)for(let t of e.source.snippet.split(`
|
|
325
326
|
`))S.push(` ${t}`);return S.join(`
|
|
326
|
-
`)}case`WRITE_ERROR`:return`Failed to write config file: ${e.detail}`;case`OKIGNORE_INVALID`:return e.lineNumber===void 0?`.okignore: ${e.detail}`:`.okignore line ${e.lineNumber}: ${e.detail}`;case`UNKNOWN`:return e.message??`Unknown error.`}}const SYSTEM_DOC_NAME=`__system__`,CC1_CONTRACT_VERSION=1,CONFIG_DOC_NAME_PROJECT=`__config__/project`,CONFIG_DOC_NAME_USER=`__user__/config.yml`,CONFIG_DOC_NAME_PROJECT_LOCAL=`__local__/project`,CONFIG_DOC_NAME_OKIGNORE=`__config__/okignore`,CONFIG_DOC_NAMES=Object.freeze([CONFIG_DOC_NAME_PROJECT,CONFIG_DOC_NAME_PROJECT_LOCAL,CONFIG_DOC_NAME_USER,CONFIG_DOC_NAME_OKIGNORE]),ALL_EDITOR_IDS=[`claude`,`claude-desktop`,`cursor`,`codex`],EDITOR_LABELS={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`},DEFAULT_GITHUB_OAUTH_CLIENT_ID=`Ov23liqlSd0V1MwR6rhI`,ORPHAN_MODES=[`incoming`,`outgoing`,`both`];function isOrphanMode(e){return ORPHAN_MODES.includes(e)}const 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`]),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`.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`.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`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`];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(`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_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_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`: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]}}),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$6.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$4.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$3.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}]}});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.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]}}),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$2.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$1.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$5,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,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: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: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)}).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 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)`},{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},{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`},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`}],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`)"}];function escapeHtmlAttr(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function escapeHtmlText(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}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>
|
|
327
|
-
<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:`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 (``) — read-only compat. Preserves `` 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(`
|
|
327
|
+
`)}case`WRITE_ERROR`:return`Failed to write config file: ${e.detail}`;case`OKIGNORE_INVALID`:return e.lineNumber===void 0?`.okignore: ${e.detail}`:`.okignore line ${e.lineNumber}: ${e.detail}`;case`UNKNOWN`:return e.message??`Unknown error.`}}const SYSTEM_DOC_NAME=`__system__`,CC1_CONTRACT_VERSION=1,CONFIG_DOC_NAME_PROJECT=`__config__/project`,CONFIG_DOC_NAME_USER=`__user__/config.yml`,CONFIG_DOC_NAME_PROJECT_LOCAL=`__local__/project`,CONFIG_DOC_NAME_OKIGNORE=`__config__/okignore`,CONFIG_DOC_NAMES=Object.freeze([CONFIG_DOC_NAME_PROJECT,CONFIG_DOC_NAME_PROJECT_LOCAL,CONFIG_DOC_NAME_USER,CONFIG_DOC_NAME_OKIGNORE]),ALL_EDITOR_IDS=[`claude`,`claude-desktop`,`cursor`,`codex`],EDITOR_LABELS={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`},DEFAULT_GITHUB_OAUTH_CLIENT_ID=`Ov23liqlSd0V1MwR6rhI`,ORPHAN_MODES=[`incoming`,`outgoing`,`both`];function isOrphanMode(e){return ORPHAN_MODES.includes(e)}const 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`]),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`.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`.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`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`];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(`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_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_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`: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]}}),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$6.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$4.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$3.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}]}});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.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]}}),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$2.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$1.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$5,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,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: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)}).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 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)`},{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},{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`},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`}],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,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function escapeHtmlText(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}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>
|
|
328
|
+
<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 (``) — read-only compat. Preserves `` 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(`
|
|
328
329
|
`)}\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(`
|
|
329
330
|
`).slice(0,4).join(`
|
|
330
331
|
`)}:{name:`UnknownError`,message:String(e??`unknown`).slice(0,MAX_ERROR_MESSAGE_LEN)}}function parseRecursive(e,t,S,w){if(S>20)return incrementWholeDocFallback(),console.warn(JSON.stringify({event:`mdx-whole-doc-fallback`,reason:`MAX_SPLIT_DEPTH exceeded`})),wholeDocRawText(e);if(w){if(budgetExhausted(w))return incrementWholeDocFallback(),console.warn(JSON.stringify({event:`mdx-whole-doc-fallback`,reason:`parse budget exhausted`,calls:w.calls})),wholeDocRawText(e);w.calls+=1}try{return t(e)}catch(E){let D=extractErrorOffset(E),O=errorPayload(E);if(D===void 0){if(S===0){let S=tryPerBlockFallback(e,t,E,w);if(S)return S}return incrementWholeDocFallback(),console.warn(JSON.stringify({event:`mdx-whole-doc-fallback`,reason:O.message,error:O})),wholeDocRawText(e)}incrementBlockFallback(),console.warn(JSON.stringify({event:`mdx-block-fallback`,offset:D,reason:O.message,error:O}));try{let E=findFallbackRegion(e,D),k=e.slice(0,E.start),j=e.slice(E.start,E.end),F=e.slice(E.end),L=k.trim()?parseRecursive(k,t,S+1,w):{type:`doc`,content:[]},B=F.trim()?parseRecursive(hoistRefDefs(k)+F,t,S+1,w):{type:`doc`,content:[]},H={type:`rawMdxFallback`,attrs:{reason:O.message,originalSpan:{start:E.start,end:E.end}},content:j?[{type:`text`,text:j}]:[]},q=[...L.content??[],H,...B.content??[]];return{type:`doc`,content:q.length>0?q:[{type:`paragraph`,content:[]}]}}catch(t){incrementWholeDocFallback();let S=errorPayload(t);return console.warn(JSON.stringify({event:`mdx-whole-doc-fallback`,reason:`Recovery failed: ${S.message}`,recoveryPath:`block-split-then-rejoin`,error:S,originalError:O})),wholeDocRawText(e)}}}function extractErrorOffset(e){if(!e||typeof e!=`object`)return;let t=e;if(t.place&&typeof t.place.offset==`number`)return t.place.offset;if(t.place?.start&&typeof t.place.start.offset==`number`)return t.place.start.offset;if(t.position&&typeof t.position.offset==`number`)return t.position.offset;if(t.position?.start&&typeof t.position.start.offset==`number`)return t.position.start.offset}function nearestBlankLineBefore(e,t){let S=/\n\s*\n/g,w=null;for(let E of e.matchAll(S)){if(E.index>=t)break;w=E.index+E[0].length}return w}function nearestBlankLineAfter(e,t){for(let S of e.matchAll(/\n\s*\n/g))if(S.index>=t)return S.index;return null}const MAX_TAG_SCAN_SPAN=32*1024;function scanTagEvents(e,t){let S=[];for(let w of e.matchAll(/<(\/?)([A-Z][A-Za-z0-9.]*)/g)){let E=w.index;if(isInsideFence(E,t))continue;let D=w[1]===`/`,O=w[2],k=E+w[0].length,j=Math.min(e.length,k+MAX_TAG_SCAN_SPAN),F=!1,L=0,B=-1,H=!1;for(let t=k;t<j;t++){let S=e[t];if(F){S===`"`&&(F=!1),S===`\\`&&t+1<j&&t++;continue}if(S===`"`){F=!0;continue}if(S===`{`){L++;continue}if(S===`}`&&L>0){L--;continue}if(!(L>0)&&S===`>`){B=t,t>0&&e[t-1]===`/`&&(H=!0);break}}if(B===-1)continue;let q=B+1;D?S.push({kind:`close`,name:O,start:E,end:q}):H?S.push({kind:`self-close`,name:O,start:E,end:q}):S.push({kind:`open`,name:O,start:E,end:q})}return S}function enumerateFallbackRegions(e){let t=scanTagEvents(e,findFencedRegions(e)),S=[],w=[];for(let E of t){if(E.kind===`self-close`)continue;if(E.kind===`open`){S.push(E);continue}let t=-1;for(let e=S.length-1;e>=0;e--)if(S[e].name===E.name){t=e;break}if(t!==-1){for(let D=S.length-1;D>t;D--){let t=S[D],O=nearestBlankLineAfter(e,t.start)??e.length;w.push({start:t.start,end:Math.min(E.start,O),source:`unmatched`})}w.push({start:S[t].start,end:E.end,source:`pair`}),S.length=t}}for(let t of S){let S=nearestBlankLineAfter(e,t.start)??e.length;w.push({start:t.start,end:Math.min(e.length,S),source:`unmatched`})}return w}function findFallbackRegion(e,t){let S=enumerateFallbackRegions(e),w=null;for(let e of S)e.start<=t&&t<=e.end&&(!w||e.end-e.start<w.end-w.start)&&(w=e);return w?{start:w.start,end:w.end}:{start:nearestBlankLineBefore(e,t)??0,end:nearestBlankLineAfter(e,t)??e.length}}function splitSourceIntoBlocks(e){let t=findFencedRegions(e),S=/\n[ \t]*\n/g,w=[0];for(let E of e.matchAll(S)){let e=E.index;isInsideFence(e,t)||w.push(e+E[0].length)}w.push(e.length);let E=[];for(let t=0;t<w.length-1;t++){let S=w[t],D=w[t+1];if(D<=S)continue;let O=e.slice(S,D);O.trim()&&E.push({src:O,start:S,end:D})}return E}function tryPerBlockFallback(e,t,S,w){let E=splitSourceIntoBlocks(e);if(E.length<2)return null;let D=[],O=!1,k=!1,j=``;for(let e of E){if(w&&budgetExhausted(w))break;w&&(w.calls+=1);let E=j+e.src;try{let S=t(E).content??[];j+=hoistRefDefs(e.src);let w=S.filter(e=>e.type!==`paragraph`||Array.isArray(e.content)&&e.content.length>0);if(w.length===0&&S.length>0){O=!0;continue}D.push(...w),O=!0}catch(t){incrementBlockFallback();let w=t?.message?.slice(0,200)??`unknown block error`,E=S?.message?.slice(0,160)??`unknown`;console.warn(JSON.stringify({event:`mdx-block-fallback`,offset:e.start,reason:`Per-block recovery after position-less error: ${E}`,blockError:w,blockErrorName:t?.name})),D.push({type:`rawMdxFallback`,attrs:{reason:w,originalSpan:{start:e.start,end:e.end}},content:[{type:`text`,text:e.src}]})}}return O?{type:`doc`,content:D.length>0?D:[{type:`paragraph`,content:[]}]}:null}function wholeDocRawText(e){return{type:`doc`,content:[{type:`paragraph`,content:[{type:`text`,text:e}]}]}}const GUARD_OPEN=``,GUARD_CLOSE=``,GUARD_COLON=``,GUARD_AT=``,GUARD_OPEN_BRACE=``,AUTOLINK_RE=/<([a-zA-Z][a-zA-Z0-9+.-]*:[^\s<>]+)>/g,HTML_COMMENT_RE=/<!--[\s\S]*?-->/g,HTML_CLOSE_TAG_RE=/<\/([a-z][a-z0-9]*)\s*>/g,LOWERCASE_HTML_TAG_RE=/<([a-z][a-z0-9]*)(\s[^>]*)?\/?>/g,LOWERCASE_JSX_CANONICAL_TAGS=new Set([`img`,`video`,`audio`]),LOWERCASE_PAIRED_JSX_TAGS=new Set([`mark`]),UPPERCASE_CLOSE_TAG_INDEX_RE=/<\/([A-Z][A-Za-z0-9.]*)>/g;function lowerBound(e,t){let S=0,w=e.length;for(;S<w;){let E=S+w>>>1;e[E]<t?S=E+1:w=E}return S}function indexUppercaseCloseTagsByName(e){let t=new Map,S=new RegExp(UPPERCASE_CLOSE_TAG_INDEX_RE.source,`g`),w=S.exec(e);for(;w!==null;){let E=t.get(w[1]);E?E.push(w.index):t.set(w[1],[w.index]),w=S.exec(e)}return t}function indexParagraphBreaks(e){let t=[],S=/\n\s*\n/g,w=S.exec(e);for(;w!==null;)t.push(w.index),w=S.exec(e);return t}function indexSelfClose(e){let t=[],S=e.indexOf(`/>`);for(;S!==-1;)t.push(S),S=e.indexOf(`/>`,S+2);return t}function protectFromMdx(e){let t=e;t=t.replace(HTML_COMMENT_RE,e=>e.replace(/</g,GUARD_OPEN).replace(/>/g,GUARD_CLOSE)),t=t.replace(AUTOLINK_RE,(e,t)=>`${GUARD_OPEN}${t.replaceAll(`:`,GUARD_COLON).replaceAll(`@`,GUARD_AT)}${GUARD_CLOSE}`),t=t.replace(HTML_CLOSE_TAG_RE,(e,t)=>LOWERCASE_PAIRED_JSX_TAGS.has(t)?e:e.replace(/</g,GUARD_OPEN).replace(/>/g,GUARD_CLOSE)),t=t.replace(LOWERCASE_HTML_TAG_RE,(e,t)=>LOWERCASE_JSX_CANONICAL_TAGS.has(t)&&e.endsWith(`/>`)||LOWERCASE_PAIRED_JSX_TAGS.has(t)?e:t[0]===t[0].toLowerCase()&&t[0]!==t[0].toUpperCase()?e.replace(/</g,GUARD_OPEN).replace(/>/g,GUARD_CLOSE):e),t=t.replace(/<>/g,`${GUARD_OPEN}${GUARD_CLOSE}`);let S=indexUppercaseCloseTagsByName(t),w=indexParagraphBreaks(t),E=indexSelfClose(t);t=t.replace(/</g,(e,D)=>{let O=t.slice(D,D+256);if(O[1]===`/`)return/^<\/[a-zA-Z][a-zA-Z0-9.]*[ \t]*>/.test(O)?e:GUARD_OPEN;let k=/^<([a-z][a-z0-9]*)([^>]*)\/>/.exec(O);if(k&&LOWERCASE_JSX_CANONICAL_TAGS.has(k[1]))return e;let j=/^<([a-z][a-z0-9]*)([\s/>])/.exec(O);if(j&&LOWERCASE_PAIRED_JSX_TAGS.has(j[1])){let S=j[1];return O.startsWith(`<${S}/>`)||t.indexOf(`</${S}>`,D)!==-1?e:GUARD_OPEN}let F=/^<([A-Z][a-zA-Z0-9.]*)[\s/>]/.exec(O);if(!F)return GUARD_OPEN;let L=F[1],B=lowerBound(w,D),H=lowerBound(E,B<w.length?w[B]:t.length);if(H>0){let S=E[H-1];if(S>D){let w=D+F[0].length-1;if(!t.slice(w,S).replace(/"[^"]*"|'[^']*'/g,``).includes(`/`))return e}}let q=S.get(L);return q&&lowerBound(q,D)<q.length?e:GUARD_OPEN});{let e=[],S=[];for(let w=0;w<t.length;w++){if(t[w]===`
|
|
@@ -361,7 +362,7 @@ $2`).split(`
|
|
|
361
362
|
`;return F.join(H)},table(e,t,S,w){let E=` `,D=S.enter(`table`),O=[],k=[],j=e.children??[];for(let e of j){let t=e.children??[],E=[],D=[];for(let e of t){let t=S.enter(`tableCell`),O=S.enter(`phrasing`),k=S.containerPhrasing(e,{...w,before:` `,after:` `});O(),t(),E.push(k);let j=e.data?.sourcePadding;D.push(j&&typeof j.left==`number`&&typeof j.right==`number`?{left:j.left,right:j.right}:null)}O.push(E),k.push(D)}D();let F=e.align??[],L=e.data?.sourceDashCounts,B=O[0]?.length??0,H=O.slice(1).reduce((e,t)=>Math.max(e,t.length),0),q=Math.max(B,H,F.length),J=[];for(let e=0;e<q;e++){let t=F[e],S=``,w=``;t===`center`?(S=`:`,w=`:`):t===`left`?S=`:`:t===`right`&&(w=`:`);let E=L?.[e],D=typeof E==`number`&&E>=1?E:1;J.push(S+`-`.repeat(D)+w)}let Y=(e,t)=>{let S=[];for(let w=0;w<q;w++){let E=e[w]??``,D=t[w]??{left:1,right:1};S.push(` `.repeat(D.left)+E+` `.repeat(D.right))}return`|${S.join(`|`)}|`},ee=Array.from({length:q},()=>null);if(O.length===0)return Y(J,ee);let te=[];te.push(Y(O[0],k[0]??[])),te.push(Y(J,ee));for(let e=1;e<O.length;e++)te.push(Y(O[e],k[e]??[]));return te.join(`
|
|
362
363
|
`)},mdxJsxFlowElement(e,t,S,w){let E=e,D=E.data?.sourceRaw;if(typeof D==`string`)return D;let O=E.data?.htmlBoundary;if(O&&typeof O.opener==`string`&&typeof O.closer==`string`){let e=S.containerFlow({type:`root`,children:E.children??[]},w);return`${O.opener}\n\n${e}\n\n${O.closer}`}let k=E.name??``,j=serializeMdxJsxAttrs(E.attributes??[]);if(!E.children||E.children.length===0)return k?j?`<${k} ${j} />`:`<${k} />`:``;let F=j?`<${k} ${j}>`:`<${k}>`,L=`</${k}>`;return`${F}\n\n${S.containerFlow({type:`root`,children:E.children},w)}\n\n${L}`},mark(e,t,S,w){let E=S.createTracker(w),D=S.enter(`mark`),O=E.move(`==`);return O+=S.containerPhrasing(e,{before:O,after:`==`,...E.current()}),O+=E.move(`==`),D(),O},comment(e,t,S,w){let E=e.data?.sourceForm,D=E===`html`?`<!-- `:`%%`,O=E===`html`?` -->`:`%%`,k=S.createTracker(w),j=S.enter(`comment`),F=k.move(D);return F+=S.containerPhrasing(e,{before:F,after:O,...k.current()}),F+=k.move(O),j(),F},commentBlock(e,t,S,w){let E=S.createTracker(w),D=S.enter(`commentBlock`),O=e.children??[],k=e.data?.sourceForm,j=e.data?.sourceLayout,F=O.length===1&&O[0]?.type===`paragraph`;if(k===`html`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`<!-- `,after:` -->`,...E.current()});return D(),`<!-- ${t} -->`}if(j===`inline`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`%% `,after:` %%`,...E.current()});return D(),`%% ${t} %%`}let L=S.containerFlow(e,E.current());return D(),`%%\n\n${L}\n\n%%`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;if(typeof t==`string`)return t;let S=e.name??``,w=serializeMdxJsxAttrs(e.attributes??[]);return w?`<${S} ${w} />`:`<${S}/>`},rawMdxFallback(e){return e.value??``},blockquote(e,t,S,w){let E=S.enter(`blockquote`),D=S.createTracker(w);D.move(`> `),D.shift(2);let O=S.containerFlow(e,D.current());E();let k=e.data?.sourceMarkerSpacings,j=0;return S.indentLines(O,(e,t,S)=>S?`>`:k?.[j++]===`none`?`>${e}`:`> ${e}`)}};function serializeMdxJsxAttrs(e){let t=[];for(let S of e){if(S.type===`mdxJsxExpressionAttribute`){t.push(`{${S.value}}`);continue}let e=S.name;if(S.value===null||S.value===void 0){t.push(e);continue}if(typeof S.value==`string`){if(S.value.includes(`"`)){let w=S.value.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t.push(`${e}={"${w}"}`)}else t.push(`${e}="${S.value}"`);continue}t.push(`${e}={${S.value.value}}`)}return t.join(` `)}function emitLinkTitle(e,t,S=` `){return t===`single`?`${S}'${e.replace(/'/g,`\\'`)}'`:t===`paren`?`${S}(${e.replace(/[()]/g,`\\$&`)})`:`${S}"${e.replace(/"/g,`\\"`)}"`}function formatLinkUrl(e){if(!e)return``;let t=0,S=!0;for(let w of e)w===`(`?t++:w===`)`&&(t--,t<0&&(S=!1));return t!==0&&(S=!1),S?e:e.replace(/[\\()]/g,`\\$&`)}function escapeEntityAmpersands(e){return e.replace(/(?<!\\)&(?=[A-Za-z][A-Za-z0-9]*;|#[0-9]+;|#[xX][0-9A-Fa-f]+;)/g,`\\&`)}function safeText(e,t,S){let w=e.unsafe;e.unsafe=w.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`||e.character==="`"));let E;try{E=e.safe(t,S)}finally{e.unsafe=w}return escapeEntityAmpersands(E)}function formatFileSize(e){if(!Number.isFinite(e)||e<0)return``;if(e<1024)return`${e} B`;let t=[`KiB`,`MiB`,`GiB`,`TiB`],S=e/1024,w=0;for(;S>=1024&&w<t.length-1;)S/=1024,w+=1;return`${S.toFixed(1).replace(/\.0$/,``)} ${t[w]}`}var MarkdownManager=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;parseCtx={current:{}};constructor(e){this.schema=getSchema(e.extensions),this.handlers=buildMdastToPmHandlers(this.schema,this.parseCtx);let{nodeHandlers:t,markHandlers:S}=buildPmToMdastHandlers(this.schema);this.pmNodeHandlers=t,this.pmMarkHandlers=S,this.parseProcessor=createParseProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=createSerializeProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers,toMarkdownHandlers})}parse(e,t){if(!e.trim())return{type:`doc`,content:[{type:`paragraph`,content:[]}]};this.parseCtx.current=t??{};try{return parseMd(e,this.parseProcessor).toJSON()}finally{this.parseCtx.current={}}}parseToMdast(e){return e.trim()?parseMdToMdast(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e,t){return e.trim()?parseWithFallback(e,{parse:e=>this.parse(e,t)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e){let t;try{t=this.schema.nodeFromJSON(e)}catch(t){let S=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(S,{cause:t})}return serializeMd(t,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}};const registry=createRegistry();function destructureAttrs(e,t){let S=new Map;for(let e of t)S.set(e.name,e);let w={};for(let t of e){if(t.type===`mdxJsxExpressionAttribute`)continue;let e=t.name,E=S.get(e);if(t.value===null||t.value===void 0){w[e]=!0;continue}if(typeof t.value==`string`){if(E?.type===`number`){let S=Number(t.value);w[e]=Number.isNaN(S)?t.value:S}else E?.type===`boolean`?w[e]=t.value===`true`:w[e]=t.value;continue}let D=t.value.value;try{w[e]=JSON.parse(D)}catch{w[e]=D}}return w}function hasDirtyDescendant(e){let t=!1;return e.descendants(e=>t||e.type.name===`jsxInline`?!1:e.type.name===`jsxComponent`&&e.attrs.sourceDirty?(t=!0,!1):!0),t}function effectiveDirty(e){return e.attrs.sourceDirty||hasDirtyDescendant(e)}function isEmptyMdastParagraph(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0?!0:t.every(e=>e.type===`text`&&e.value===``)}function withInlineCodeData(e,t){if(!t)return e;let S={};return t.sourceFenceChar&&(S.sourceFenceChar=t.sourceFenceChar),typeof t.sourceFenceLength==`number`&&(S.sourceFenceLength=t.sourceFenceLength),Object.keys(S).length===0?e:{...e,data:S}}function wrapAsInlineCode(e,t){if(e.length===0)return withInlineCodeData({type:`inlineCode`,value:``},t);if(e.every(e=>e.type===`text`))return withInlineCodeData({type:`inlineCode`,value:e.map(e=>e.value).join(``)},t);if(e.length===1&&`children`in e[0]){let S=e[0];return{...S,children:[wrapAsInlineCode(S.children,t)]}}return withInlineCodeData({type:`inlineCode`,value:extractTextFromMdastNodes(e)},t)}function extractTextFromMdastNodes(e){let t=``;for(let S of e)S.type===`text`?t+=S.value:`children`in S&&Array.isArray(S.children)?t+=extractTextFromMdastNodes(S.children):`value`in S&&typeof S.value==`string`&&(t+=S.value);return t}const WIKI_EMBED_IMAGE_EXTS=IMAGE_EXTENSIONS;function buildMdastToPmHandlers(e,t){let S=e.nodes,w=e.marks,E={};S.paragraph&&(E.paragraph=(e,t,w)=>{let E=w.all(e).flat(),D=E.some(e=>e?.isBlock&&!e?.isInline),O=E.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(D&&!O)return E.length===1?E[0]:E;if(D&&O){let e=E.filter(e=>!e?.isBlock||e?.isInline),t=E.filter(e=>e?.isBlock&&!e?.isInline),w=[],D=S.paragraph.createAndFill(null,e.length>0?e:null);return D&&w.push(D),w.push(...t),w.length===1?w[0]:w}return S.paragraph.createAndFill(null,E.length>0?E:null)}),S.blockquote&&(E.blockquote=toPmNode(S.blockquote,e=>({sourceMarkerSpacings:e.data?.sourceMarkerSpacings??null}))),S.tableCell&&(E.tableCell=(e=>(t,w,E)=>{let D=E.all(t).flat();if(D.length>0&&S.paragraph){let t=S.paragraph.create(null,D);return e.createAndFill(null,[t])}return e.createAndFill(null,null)})(S.tableCell)),S.tableRow&&(E.tableRow=toPmNode(S.tableRow)),S.table&&S.tableRow&&S.tableCell&&(E.table=(e,t,w)=>{let E=e.align??[],D=e.children??[],O=[];for(let e=0;e<D.length;e++){let t=D[e];if(t.type!==`tableRow`)continue;let k=t.children??[],j=[];for(let t=0;t<k.length;t++){let D=k[t];if(D.type!==`tableCell`)continue;let O=w.all(D).flat(),F=O.length>0&&S.paragraph?[S.paragraph.create(null,O)]:null,L=E[t]??null,B=e===0&&S.tableHeader?S.tableHeader:S.tableCell,H=D.data?.sourcePadding??null,q=B.createAndFill({align:L,sourcePadding:H},F);q&&j.push(q)}let F=S.tableRow.createAndFill(null,j.length>0?j:null);F&&O.push(F)}let k=e.data?.sourceDashCounts??null;return S.table.createAndFill({sourceDashCounts:k},O.length>0?O:null)}),S.image&&(E.image=e=>{let w=e.url??``,E=normalizeDocRelativeAssetUrl(w,t.current.sourcePath);return S.image.createAndFill({src:E,alt:e.alt??null,title:e.title??null,sourceUrl:E===w?null:w})},S.imageReference?E.imageReference=e=>S.imageReference.createAndFill({alt:e.alt??``,label:e.label??e.identifier??``,identifier:e.identifier??``,referenceType:e.referenceType??`shortcut`}):E.imageReference=e=>S.image.createAndFill({src:``,alt:e.alt??null,title:null})),w.escapeMark&&(E.text=t=>{let S=t.value??``,E=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!S&&!E)return null;if(E){let t=S.replaceAll(`\xA0`,` `);return w.sourceLiteral?e.text(t,[w.sourceLiteral.create({sourceRaw:E})]):e.text(t)}let D=t.data?.escapedChars,O=t.data?.entityRefSpans;if(!D?.length&&!O?.length)return e.text(S.replaceAll(`\xA0`,` `));let k=[...(D??[]).map(e=>({kind:`escape`,offset:e.offset,length:1})),...(O??[]).map(e=>({kind:`entity`,offset:e.offset,length:e.length,raw:e.raw}))];k.sort((e,t)=>e.offset-t.offset);let j=[],F=0;for(let t of k){if(t.offset>F){let w=S.slice(F,t.offset).replaceAll(`\xA0`,` `);w&&j.push(e.text(w))}if(t.offset<S.length){let E=S.slice(t.offset,t.offset+t.length).replaceAll(`\xA0`,` `);E&&(t.kind===`escape`?j.push(e.text(E,[w.escapeMark.create()])):w.sourceLiteral?j.push(e.text(E,[w.sourceLiteral.create({sourceRaw:t.raw})])):j.push(e.text(E))),F=t.offset+t.length}}if(F<S.length){let t=S.slice(F).replaceAll(`\xA0`,` `);t&&j.push(e.text(t))}return j.length===1?j[0]:j}),w.code&&(E.inlineCode=t=>e.text(t.value,[w.code.create({sourceFenceChar:t.data?.sourceFenceChar??"`",sourceFenceLength:typeof t.data?.sourceFenceLength==`number`?t.data.sourceFenceLength:1})]));let D=w.strike??w.delete;if(D&&(E.delete=toPmMark(D)),w.highlight&&(E.mark=toPmMark(w.highlight)),w.comment&&(E.comment=toPmMark(w.comment,e=>({sourceForm:e.data?.sourceForm??`percent`}))),S.commentBlock&&(E.commentBlock=toPmNode(S.commentBlock,e=>({sourceForm:e.data?.sourceForm??`percent`,sourceLayout:e.data?.sourceLayout??`block`}))),w.emphasis&&(E.emphasis=toPmMark(w.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),w.strong&&(E.strong=toPmMark(w.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),S.heading&&(E.heading=toPmNode(S.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`,sourceTrailingHashes:e.data?.sourceTrailingHashes??null,sourceUnderlineLength:e.data?.sourceUnderlineLength??null,sourceContiguousNext:e.data?.sourceContiguousNext??!1}))),S.codeBlock&&(E.code=t=>{let w=t.value?[e.text(t.value)]:[];return S.codeBlock.createAndFill({language:t.lang??null,meta:t.meta??null,fenceDelimiter:t.data?.sourceFenceChar??"`",fenceLength:t.data?.sourceFenceLength??3,sourceStyle:t.data?.sourceStyle??`fenced`},w)}),S.thematicBreak&&(E.thematicBreak=e=>S.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),S.hardBreak&&(E.break=e=>S.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`})),S.list&&(E.list=toPmNode(S.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),S.listItem&&(E.listItem=toPmNode(S.listItem,e=>({checked:e.checked??null,spread:!!e.spread}))),w.link){let t=w.sourceLiteral;E.link=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[](${S.url??``})`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:S.url??``,title:S.title??null,linkStyle:S.data?.sourceStyle??`inline`,refLabel:null,sourceUrlForm:S.data?.sourceUrlForm??null,sourceTitleMarker:S.data?.sourceTitleMarker??null});return O.map(e=>e.mark(k.addToSet(e.marks)))},E.linkReference=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[${S.label??``}][${S.identifier??``}]`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:``,title:null,linkStyle:S.referenceType??`shortcut`,refLabel:S.label??S.identifier??null});return O.map(e=>e.mark(k.addToSet(e.marks)))}}S.htmlBlock&&(E.html=e=>S.htmlBlock.createAndFill({content:e.value??``}));let O=S.linkDefinition??S.linkRefDef;if(O){let e=!!O.spec.attrs?.url,t=!!O.spec.attrs?.href,S=!!O.spec.attrs?.identifier,w=!!O.spec.attrs?.sourceLayout,D=!!O.spec.attrs?.sourceTitleMarker;E.definition=E=>{let k={title:E.title??null};return S&&(k.identifier=E.identifier??``),k.label=E.label??E.identifier??``,e?k.url=E.url??``:t&&(k.href=E.url??``),w&&(k.sourceLayout=E.data?.sourceLayout??null),D&&(k.sourceTitleMarker=E.data?.sourceTitleMarker??null),O.createAndFill(k)}}if(S.jsxComponent){let w=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};E.mdxJsxFlowElement=(e,E,D)=>{let O=e.name??``,k=registry.getOrWildcard(O),j=destructureAttrs(e.attributes,k.props);if(O===`CommonMarkImage`&&typeof j.src==`string`){let e=j.src,S=normalizeDocRelativeAssetUrl(e,t.current.sourcePath);S!==e&&(j.src=S,j.sourceUrl=e)}let F=D.all(e).flat();return S.jsxComponent.createAndFill({componentName:O,kind:`element`,attributes:e.attributes,sourceRaw:w(e.data)??``,sourceDirty:!1,props:j},F.length?F:void 0)};let D=(e,t)=>{let S=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return S&&typeof S.value==`string`?S.value:null};E.mdxJsxTextElement=t=>{if(t.name===`InlineMath`&&S.mathInline){let e=D(t,`formula`)??``,w=D(t,`id`);return S.mathInline.create({formula:e,id:w??null})}if(t.name===`Tag`&&S.tag){let e=D(t,`value`)??``;return S.tag.create({value:e})}if(S.jsxInline){let E=w(t.data)??``;return S.jsxInline.createAndFill({},E?[e.text(E)]:null)}return S.jsxComponent.createAndFill({sourceRaw:w(t.data)??``})},E.mdxFlowExpression=e=>{let t=w(e.data)??`{${e.value??``}}`;return S.jsxComponent.createAndFill({kind:`expression`,sourceRaw:t,sourceDirty:!1})},E.mdxTextExpression=t=>{let S=w(t.data)??`{${t.value??``}}`;return e.text(S)}}return S.wikiLink&&(E.wikiLink=e=>S.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null})),S.tag&&(E.tag=e=>S.tag.createAndFill({value:e.value})),S.wikiLinkEmbed&&(E.wikiLinkEmbed=(E,D)=>{let O=E.data?.target??``,k=E.data?.alias??null,j=E.data?.anchor??null,F=extensionOf(O),{resolveEmbed:L,sourcePath:B}=t.current,H=L&&B?L(O,B)??null:null,q=H?`/${H}`:O,J=D?.type===`paragraph`&&Array.isArray(D.children)&&D.children.length===1;if(J&&WIKI_EMBED_IMAGE_EXTS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedImage`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedImage`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,alt:k??O,target:O,anchor:j,alias:k}});if(J&&VIDEO_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedVideo`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedVideo`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&AUDIO_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedAudio`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedAudio`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&FILE_ATTACHMENT_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedFile`)){let{resolveSize:e}=t.current,w=e&&B?e(O,B)??null:null,E=w===null?null:formatFileSize(w);return S.jsxComponent.createAndFill({componentName:`WikiEmbedFile`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,target:O,anchor:j,alias:k,size:E}})}let Y=k||(j?`${O}#${j}`:O);if(WIKI_EMBED_EXTENSIONS.has(F)&&w.link){let t=w.link.create({href:q,title:null,linkStyle:`inline`,refLabel:null,sourceForm:`wikiembed`,target:O,anchor:j,alias:k});return e.text(Y,[t])}if(w.link){let t=w.link.create({href:O,title:null,linkStyle:`inline`,refLabel:null});return e.text(Y,[t])}throw Error("[wikiLinkEmbed handler] schema lacks `link` mark — cannot dispatch without violating the STOP rule against emitting PM wikiLinkEmbed server-side")}),S.mathInline&&(E.inlineMath=e=>S.mathInline.create({formula:e.value??``})),E.math||=t=>{let w=t.value==null?`«unknown:${t.type}»`:t.value;return S.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled block mdast: ${t.type}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${t.type}`},w?[e.text(w)]:null)):null},E.inlineMath||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),t.value==null?e.text(`«unknown:${t.type}»`):e.text(t.value)),S.footnoteReference?E.footnoteReference=e=>S.footnoteReference.create({identifier:e.identifier,label:e.label??e.identifier}):E.footnoteReference||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteReference`,reason:`FootnoteReference extension missing — recovering [^id] source`})),e.text(`[^${t.label??t.identifier}]`)),S.footnoteDefinition?E.footnoteDefinition=toPmNode(S.footnoteDefinition,e=>{let t=e;return{identifier:t.identifier,label:t.label??t.identifier}}):E.footnoteDefinition||=t=>{console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteDefinition`,reason:`FootnoteDefinition extension missing — recovering [^id]: marker`}));let w=`[^${t.label??t.identifier}]: `;return S.paragraph?S.paragraph.create(null,e.text(w)):null},E.rawMdxFallbackMdast=t=>{if(!S.rawMdxFallback)return null;let w=t.position?{start:t.position.start?.offset??0,end:t.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.originalType,reason:`Unhandled mdast: ${t.originalType}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${t.originalType}`,originalSpan:w},t.value?[e.text(t.value)]:null)},E}function buildPmToMdastHandlers(e){let t={},S={},w=e.nodes,E=e.marks;w.paragraph&&(t.paragraph=fromPmNode(`paragraph`)),w.blockquote&&(t.blockquote=fromPmNode(`blockquote`,e=>{let t=e.attrs.sourceMarkerSpacings,S={};return Array.isArray(t)&&t.length>0&&(S.sourceMarkerSpacings=t),Object.keys(S).length>0?{data:S}:{}})),w.heading&&(t.heading=fromPmNode(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle,sourceTrailingHashes:e.attrs.sourceTrailingHashes??void 0,sourceUnderlineLength:e.attrs.sourceUnderlineLength??void 0,sourceContiguousNext:e.attrs.sourceContiguousNext===!0?!0:void 0}}))),w.codeBlock&&(t.codeBlock=e=>{let t=e.attrs.sourceStyle===`indented`?`indented`:`fenced`;return{type:`code`,lang:t===`indented`?null:e.attrs.language??null,meta:t===`indented`?null:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength,sourceStyle:t}}}),w.thematicBreak&&(t.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),w.hardBreak&&(t.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle}})),w.list&&(t.list=fromPmNode(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),w.listItem&&(t.listItem=(e,t,S)=>{let w=S.all(e),E=w.length>1&&isEmptyMdastParagraph(w[0])?w.slice(1):w;return{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,children:E}}),w.table&&(t.table=(e,t,S)=>{let w=S.all(e),E=[],D=e.firstChild;D&&D.forEach(e=>{let t=e.attrs.align;E.push(t===`left`||t===`right`||t===`center`?t:null)});let O=w.filter(e=>e.type===`tableRow`),k=e.attrs.sourceDashCounts,j=Array.isArray(k)&&k.length>0?{sourceDashCounts:k}:void 0,F={type:`table`,align:E,children:O};return j&&(F.data=j),F}),w.tableRow&&(t.tableRow=fromPmNode(`tableRow`));let D=e=>{let t=e.attrs.sourcePadding,S={};return typeof t==`object`&&t&&typeof t.left==`number`&&typeof t.right==`number`&&(S.sourcePadding=t),Object.keys(S).length>0?{data:S}:{}};if(w.tableCell&&(t.tableCell=fromPmNode(`tableCell`,D)),w.tableHeader&&(t.tableHeader=fromPmNode(`tableCell`,D)),w.image&&(t.image=e=>({type:`image`,url:e.attrs.sourceUrl??e.attrs.src,alt:e.attrs.alt,title:e.attrs.title})),w.imageReference&&(t.imageReference=e=>{let t=e.attrs.label??``,S=e.attrs.identifier??t;return{type:`imageReference`,alt:e.attrs.alt??``,identifier:S,label:t||S,referenceType:e.attrs.referenceType??`shortcut`}}),w.htmlBlock&&(t.htmlBlock=e=>({type:`html`,value:e.attrs.content})),w.linkDefinition??w.linkRefDef){let e=w.linkDefinition?`linkDefinition`:`linkRefDef`;t[e]=e=>{let t={},S=e.attrs.sourceLayout;(S===`multiline`||S===`inline`)&&(t.sourceLayout=S);let w=e.attrs.sourceTitleMarker;(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w);let E={type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title};return Object.keys(t).length>0&&(E.data=t),E}}if(w.jsxComponent&&(t.jsxComponent=(e,t,S)=>{if(e.attrs.kind===`expression`)return{type:`html`,value:e.attrs.sourceRaw??``};let w=e.attrs.componentName||null,E=Array.isArray(e.attrs.attributes)?e.attrs.attributes:[];return!effectiveDirty(e)&&e.attrs.sourceRaw?{type:`mdxJsxFlowElement`,name:w,attributes:E,children:[],data:{sourceRaw:String(e.attrs.sourceRaw)}}:registry.getOrWildcard(w??`*`).serialize(e,{all:e=>S.all(e),registry,serializeChildren:()=>{throw Error(`SerializeContext.serializeChildren is not available in the PM→mdast handler. Compat descriptors that need markdown-byte body rendering must emit a marker mdast node and let the to-markdown handler render the body via state.containerFlow.`)}})}),w.rawMdxFallback&&(t.rawMdxFallback=e=>{let t=e.textContent??``,S=typeof e.attrs.reason==`string`?e.attrs.reason:``,w=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:S,originalSpan:w&&typeof w==`object`&&`start`in w&&`end`in w?{start:Number(w.start)||0,end:Number(w.end)||0}:{start:0,end:0}}}}),w.jsxInline&&(t.jsxInline=e=>{let t=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(t)}}}),w.mathInline&&(t.mathInline=e=>{let t=e.attrs.formula??``,S=e.attrs.id;return typeof S==`string`&&S.length>0?{type:`mdxJsxTextElement`,name:`InlineMath`,attributes:[{type:`mdxJsxAttribute`,name:`formula`,value:t},{type:`mdxJsxAttribute`,name:`id`,value:S}],children:[]}:{type:`inlineMath`,value:t}}),w.wikiLink&&(t.wikiLink=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLink`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),w.tag&&(t.tag=e=>({type:`tag`,value:String(e.attrs.value??``)})),w.wikiLinkEmbed&&(t.wikiLinkEmbed=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),E.emphasis&&(S.emphasis=fromPmMark(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.strong&&(S.strong=fromPmMark(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.code&&(S.code=(e,t,S)=>{let w=e.attrs.sourceFenceChar,E=e.attrs.sourceFenceLength;return wrapAsInlineCode(S,{sourceFenceChar:w,sourceFenceLength:E})}),E.strike??E.delete){let e=E.strike?`strike`:`delete`;S[e]=fromPmMark(`delete`)}return E.highlight&&(S.highlight=fromPmMark(`mark`)),E.comment&&(S.comment=fromPmMark(`comment`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`}}))),w.commentBlock&&(t.commentBlock=fromPmNode(`commentBlock`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`,sourceLayout:e.attrs.sourceLayout===`inline`?`inline`:`block`}}))),w.footnoteReference&&(t.footnoteReference=e=>{let t=String(e.attrs.identifier??``);return{type:`footnoteReference`,identifier:t,label:e.attrs.label?String(e.attrs.label):t}}),w.footnoteDefinition&&(t.footnoteDefinition=fromPmNode(`footnoteDefinition`,e=>({identifier:String(e.attrs.identifier??``),label:e.attrs.label?String(e.attrs.label):String(e.attrs.identifier??``)}))),E.link&&(S.link=(e,t,S)=>{if(e.attrs.sourceForm===`wikiembed`){let t=typeof e.attrs.target==`string`&&e.attrs.target.length>0?e.attrs.target:e.attrs.href??``,S=typeof e.attrs.anchor==`string`&&e.attrs.anchor.length>0?e.attrs.anchor:null,w=typeof e.attrs.alias==`string`&&e.attrs.alias.length>0?e.attrs.alias:null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}let w=e.attrs.linkStyle;if(w===`autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`autolink`}};if(w===`gfm-autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`gfm-autolink`}};if(w===`inline`||!w){let t={};e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let w=e.attrs.sourceTitleMarker;return(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w),{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:S,...Object.keys(t).length>0?{data:t}:{}}}return{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:w,children:S}}),E.escapeMark&&(S.escapeMark=(e,t,S)=>{for(let e of S)if(e.type===`text`&&e.value){let t=e;t.data=t.data??{},t.data.escapedChars=t.data.escapedChars??[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return S.length===1?S[0]:S}),E.sourceLiteral&&(S.sourceLiteral=(e,t,S)=>{let w=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(S.length===1&&S[0]?.type===`text`){let e=S[0],t=w||e.value;return isValidSourceLiteralRaw(t,e.value)&&(e.data=e.data??{},e.data.sourceRaw=t),e}return{type:`text`,value:S.filter(e=>e.type===`text`).map(e=>e.value??``).join(``)||w}}),{nodeHandlers:t,markHandlers:S}}const COMBINING_MARK_RE=/\p{M}+/gu,NON_LETTER_OR_NUMBER_RE=/[^\p{L}\p{N}]+/gu,EDGE_HYPHENS_RE=/^-+|-+$/g;function toWikiLinkSlug(e){return e.trim().normalize(`NFKD`).replace(COMBINING_MARK_RE,``).toLowerCase().replace(NON_LETTER_OR_NUMBER_RE,`-`).replace(EDGE_HYPHENS_RE,``)}function disambiguateSlug(e,t){let S=t.get(e)??0;return t.set(e,S+1),S===0?e:`${e}-${S}`}function getHeadingSlug(e,t){let S=toWikiLinkSlug(e);return S?disambiguateSlug(S,t):``}const MICROMARK_MDX_EXT=mdx(),FROM_MARKDOWN_MDX_EXT=mdxFromMarkdown(),TO_MARKDOWN_MDX_EXT=mdxToMarkdown(),PLACEHOLDER_BODY=`Body content here.`,PLACEHOLDER_MERMAID_FENCE_BODY=`graph LR
|
|
363
364
|
A --> B`;function getCanonicalDescriptors(){return builtInComponents.filter(e=>e.surface===`canonical`&&e.name!==`*`)}function getAgentCanonicalDescriptors(){return getCanonicalDescriptors().filter(e=>resolveKind(e)!==`fence`)}function resolveKind(e){return e.name===`MermaidFence`?`fence`:e.hasChildren?`jsx-block`:`jsx-void`}function projectLite(e){return{id:e.name,displayName:e.displayName??e.name,description:e.description??``,kind:resolveKind(e)}}function exampleValueFor(e){if(e.hidden!==!0&&e.type!==`reactnode`){if(`defaultValue`in e&&e.defaultValue!==void 0)return e.defaultValue;if(e.type===`enum`)return e.enumValues[0];if(e.type===`string`)return``;if(e.type===`number`)return 0;if(e.type===`boolean`)return!1}}function shouldEmitProp(e,t){return!(e.omitOnDefault===!0&&`defaultValue`in e&&Object.is(e.defaultValue,t)||e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&t===``)}function buildAttributes(e){let t=[];for(let S of e.props){let e=exampleValueFor(S);e!==void 0&&shouldEmitProp(S,e)&&t.push(propToMdxJsxAttribute(S.name,e))}return t}function buildBodyChildren(e){return fromMarkdown(e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_BODY,{extensions:[MICROMARK_MDX_EXT],mdastExtensions:[FROM_MARKDOWN_MDX_EXT]}).children}function synthesizeExample(e){let t=resolveKind(e),S;if(t===`fence`)S={type:`code`,lang:`mermaid`,meta:null,value:e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_MERMAID_FENCE_BODY};else{let w=buildAttributes(e),E=t===`jsx-block`?buildBodyChildren(e):[];S={type:`mdxJsxFlowElement`,name:e.name,attributes:w,children:E}}return toMarkdown({type:`root`,children:[S]},{extensions:[TO_MARKDOWN_MDX_EXT]}).trimEnd()}function projectParams(e){let t=[];for(let S of e.props){if(S.hidden===!0)continue;let e={name:S.name,type:S.type,required:S.required};S.description!==void 0&&(e.description=S.description),S.advanced===!0&&(e.advanced=!0),S.omitOnDefault===!0&&(e.omitOnDefault=!0),S.type===`enum`&&(e.values=S.enumValues,S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue)),S.type===`string`&&(S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.language!==void 0&&(e.language=S.language),S.accept!==void 0&&(e.accept=S.accept)),S.type===`boolean`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.type===`number`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),t.push(e)}return t}function projectFull(e){return{...projectLite(e),example:synthesizeExample(e),params:projectParams(e)}}function renderInventoryFooter(){return[``,"**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `get_components({ ids })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",``,...getAgentCanonicalDescriptors().map(projectLite).map(e=>`- \`${e.id}\` (${e.kind}) — ${e.description}`)].join(`
|
|
364
|
-
`)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionPrincipalSchema=object$1({name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({message:string$2().optional(),writers:array(SaveVersionWriterSchema).optional(),principal:SaveVersionPrincipalSchema.optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1),versionTag:string$2().min(1).optional()}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1)}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),versionTag:string$2().optional(),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),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()]),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),error:string$2().optional(),pausedReason:string$2().optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]??`bot`:`bot`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
365
|
+
`)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionPrincipalSchema=object$1({name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({message:string$2().optional(),writers:array(SaveVersionWriterSchema).optional(),principal:SaveVersionPrincipalSchema.optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1),versionTag:string$2().min(1).optional()}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1)}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),versionTag:string$2().optional(),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),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()]),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),error:string$2().optional(),pausedReason:string$2().optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]??`bot`:`bot`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
365
366
|
`)){let e=S.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let S=JSON.parse(e.slice(17));if(typeof S==`object`&&S&&`id`in S&&typeof S.id==`string`&&`name`in S&&typeof S.name==`string`&&`docs`in S&&Array.isArray(S.docs)&&S.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in S)||typeof S.colorSeed==`string`)){let e=S;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(S)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
|
|
366
367
|
`)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let S;try{S=JSON.parse(e.slice(18))}catch{return null}if(typeof S!=`object`||!S)return null;let w=S,E=w.kind,D=w.metadata;if(typeof D!=`object`||!D)return null;let O=typeof w.docName==`string`?w.docName:null,k=typeof w.size==`number`&&Number.isFinite(w.size)?w.size:null;if(E===`bridge-merge-loss`){let e=D;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:O,size:k,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(E===`external-change-rescue`){let e=D;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:O,size:k,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:S,...w}=e,E={...w};return t&&t.length>0&&(E.summaries=t),S&&S.length>0&&(E.previous_paths=S),`${OK_ACTOR_PREFIX}${JSON.stringify(E)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,S=typeof e.agent_session==`string`?e.agent_session:null,w;if(typeof e.writer_id==`string`&&e.writer_id.length>0)w=e.writer_id;else if(S)w=`agent-${S}`;else if(t)w=t;else switch(e.display_name){case`File System`:w=`file-system`;break;case`Git (upstream)`:w=`git-upstream`;break;default:w=`openknowledge-service`}let E=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,D=parsePreviousPaths(e);return{v:1,writer_id:w,principal:t,agent_session:S,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...E&&E.length>0?{summaries:E}:{},...D&&D.length>0?{previous_paths:D}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let S of e.previous_paths){if(typeof S!=`object`||!S)continue;let e=S;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
367
368
|
`)){let e=S.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let w;try{w=JSON.parse(e.slice(10))}catch{continue}if(typeof w!=`object`||!w)continue;let E=parseOkActorObject(w);E&&t.push(E)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let S=stripLineBreaks(e);if(t.length===0)return S;if(t.length>=2)return`${S} (${t.length} edits)`;let[w]=t;if(w===void 0)return S;let E=stripLineBreaks(w),D=`${S} — ${E}`;if(D.length<=72)return D;let O=`${S} — `,k=72-O.length-1;return k<=0?D.slice(0,72):`${O}${E.slice(0,k)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_err_helpers=__commonJSMin$1(((e,t)=>{let S=e=>e&&typeof e.message==`string`,w=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return S(t)?t:void 0}else return S(t)?t:void 0},E=(e,t)=>{if(!S(e))return``;let D=e.stack||``;if(t.has(e))return D+`
|
|
@@ -1185,7 +1186,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
1185
1186
|
`).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let S=JSON.parse(t[e]);if(S&&typeof S==`object`&&!Array.isArray(S))return S}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let S of e.owners){if(!S||typeof S!=`object`)continue;let e=S,w=typeof e.login==`string`?e.login:null,E=e.kind===`user`||e.kind===`org`?e.kind:null;if(w===null||E===null)continue;let D=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:w,kind:E,...D?{avatarUrl:D}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,S=typeof e.repoName==`string`?e.repoName:null,w=typeof e.cloneUrl==`string`?e.cloneUrl:null,E=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&S!==null&&w!==null&&E!==null?{ok:!0,ownerLogin:t,repoName:S,cloneUrl:w,defaultBranch:E}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,S){let w=[`action=${e}`,`result=${t}`];S?.count!==void 0&&w.push(`count=${S.count}`),S?.available!==void 0&&w.push(`available=${S.available}`),console.log(`[share] ${w.join(` `)}`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let S of e){let e=fileURLToPath(new URL(S,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let S=await readdir(e,{withFileTypes:!0});for(let w of S){let S=join(e,w.name);w.isDirectory()?yield*walkFiles(S,t):w.isFile()&&(yield relative(t,S))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t){let S=computeWrapperFolderName(e),w=new import_yazl.ZipFile;w.addEmptyDirectory(`${S}/`);let E=[];for await(let t of walkFiles(e))E.push(t);E.sort();for(let t of E){let E=join(e,t),D=`${S}/${toPosixZipPath(t)}`;w.addFile(E,D)}w.end(),await new Promise((e,S)=>{let E=createWriteStream(t);w.outputStream.pipe(E),E.on(`close`,()=>e()),E.on(`error`,S),w.outputStream.on(`error`,S)})}async function sha256OfFile(e){return new Promise((t,S)=>{let w=createHash(`sha256`),E=createReadStream(e);E.on(`data`,e=>w.update(e)),E.on(`end`,()=>t(w.digest(`hex`))),E.on(`error`,S)})}function extractMetadataVersion(e){let t=e.indexOf(`
|
|
1186
1187
|
---`,4);if(!e.startsWith(`---
|
|
1187
1188
|
`)||t<0)return;let S=e.slice(4,t),w=S.search(/^metadata:/m);if(w<0)return;let E=S.slice(w).split(`
|
|
1188
|
-
`).slice(1);for(let e of E){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t){let S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(E.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let D=extractMetadataVersion(E);if(t!==void 0){if(!D)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(D!==t)throw Error(`SKILL.md metadata.version (${D}) does not match expected version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:S,sha256:w,skillVersion:D}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),S=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(t,S);let{size:w,sha256:E,skillVersion:D}=await validateSkillZip(S,e.expectedSkillVersion);return{outputPath:S,size:w,sha256:E,skillVersion:D}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let S=t?.homedir??(()=>process.env.HOME??``),w=t?.warn??((e,t)=>{console.warn(t,e)}),E=S();if(!E){w({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let D=join(E,...SKILL_INSTALL_EVENTS_FILE_REL),O=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(D),{recursive:!0})}catch(e){w({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(D,O,{flag:`a`,encoding:`utf-8`})}catch(e){w({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,S)=>tracedWriteFile(e,t,S),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let S=skillStateYamlPath(e),w;try{w=await readFileAsync(S,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let E=(0,import_dist$1.parseDocument)(w);if(E.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:S,errors:E.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let D=SkillStateSchema.safeParse(E.toJSON());if(!D.success){let e=D.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:S,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:S,issues:D.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return D.data}async function writeSkillStateFile(e,t){let S=SkillStateSchema.safeParse(t);if(!S.success)throw Error(`Refusing to write invalid skill-state: ${S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let w=skillStateYamlPath(e);await tracedMkdir(dirname(w),{recursive:!0});let E=(0,import_dist$1.parseDocument)(``);E.contents=E.createNode(S.data),await atomicWriteFile(w,E.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.version??null}async function readTargetRecordedAt(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,S,w,E){if(!SKILL_STATE_VERSION_RE.test(S))throw Error(`Refusing to write invalid version string: ${S}`);let D=await readSkillStateFile(e,E)??emptySkillState(),O=new Date().toISOString(),k=D.targets[t],j=w===void 0?k?.surface??void 0:w,F=j===void 0?{version:S,recordedAt:O}:{version:S,recordedAt:O,surface:j};await writeSkillStateFile(e,{...D,targets:{...D.targets,[t]:F}})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[S,w]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:S,targets:w}}async function readAllTargets(e,t=DEFAULT_LOGGER){let S=null;try{S=await readSkillStateFile(e,t)}catch(w){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(w)},`non-ENOENT error reading skill-state.yml; treating as absent`),S=null}let w=SKILL_STATE_TARGETS.map(e=>{let t=S?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(w)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,S,w,E){return new Promise(D=>{let O;try{O=e(t,S,{env:w,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){D({kind:`spawn-error`,stderr:``,error:e});return}let k=``,j=!1,F=e=>{j||(j=!0,clearTimeout(L),D(e))};O.stderr?.on(`data`,e=>{k+=typeof e==`string`?e:e.toString(`utf-8`)}),O.on(`error`,e=>{F({kind:`spawn-error`,stderr:k,error:e})}),O.on(`exit`,e=>{F(e===0?{kind:`ok`,exitCode:e,stderr:k}:{kind:`nonzero`,exitCode:e,stderr:k})});let L=setTimeout(()=>{try{O.kill(`SIGTERM`)}catch{}F({kind:`timeout`,stderr:k})},E)})}async function installUserSkill(e={}){let t=e.home??homedir(),S=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},w=e.spawn??spawn,E=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,D=e.surface??`cli-npx-skills-add`,O=async(e,w,E)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:D,target:`cli-hosts`,outcome:e,...w===void 0?{}:{version:w},...E===void 0?{}:{reason:E}},{homedir:()=>t,warn:S.warn})},k;try{k=await readServerPackageVersion()}catch(e){return S.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await O(`failed`,void 0,`version-read-failed`),`failed`}let j=await readTargetVersion(t,`cli-hosts`,S).catch(e=>(S.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(j!==null&&j===k){if(await centralSkillExists(t))return S.info?.({event:`skill-install.skip-current`,version:k},`Open Knowledge skill already installed at current version; skipping.`),await O(`skip-current`,k),`skip-current`;S.info?.({event:`skill-install.reinstall-missing`,version:k,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let F;try{F=resolveBundledSkillDir()}catch(e){return S.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await O(`failed`,k,`bundled-asset-missing`),`failed`}let L=await runSpawn(w,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,F,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},E);if(L.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,k,D,S)}catch(e){return S.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await O(`failed`,k,`sidecar-write-failed`),`failed`}return S.info?.({event:`skill-install.installed`,version:k},`Open Knowledge skill installed to detected agent hosts.`),await O(`installed`,k),`installed`}return L.kind===`timeout`?(S.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:E,stderr:L.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`timeout`),`failed`):L.kind===`spawn-error`?(S.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(L.error),stderr:L.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`spawn-error`),`failed`):(S.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:L.exitCode,stderr:L.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`nonzero-exit:${L.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,S){let w={detached:!0,stdio:`ignore`};try{return t===`darwin`?(S(`open`,[e],w).unref(),{ok:!0}):t===`win32`?(S(`cmd`,[`/c`,`start`,`""`,e],w).unref(),{ok:!0}):t===`linux`?(S(`xdg-open`,[e],w).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),S=resolve(e.out??defaultDownloadsPath(t)),w=e.platformName??platform(),E=e.spawnFn??spawn,D=e.logger,O=async(e,S,w)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,outcome:e,...S===void 0?{}:{version:S},...w===void 0?{}:{reason:w}},{homedir:()=>t,warn:D?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){D?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let S=null,w=null;try{[S,w]=await Promise.all([readTargetVersion(t,`claude-cowork`,D),readTargetRecordedAt(t,`claude-cowork`,D)])}catch(e){D?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(S!==null&&S===e)return D?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await O(`skip-current`,e),{status:`skip-current`,skillVersion:e,...w===null?{}:{recordedAt:w}}}}try{await tracedMkdir(dirname(S),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let k;try{k=await buildSkillZip({outputPath:S})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let j={status:`built`,outputPath:k.outputPath,size:k.size,sha256:k.sha256,skillVersion:k.skillVersion};if(k.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,k.skillVersion,`server-build-and-open`,D)}catch(e){D?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:k.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await O(`built`,k.skillVersion),j;let F=invokeFileAssociation(k.outputPath,w,E);return F.ok?(await O(`installed`,k.skillVersion),{...j,status:`installed`}):(await O(`built`,k.skillVersion,`handoff-${F.reason}`),{...j,handoffError:{reason:F.reason,message:F.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$4=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,S){this.hash.update(e),this.bytes+=e.length,S(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,S){let w=extname(S),E=S.slice(0,S.length-w.length),D=[S,...Array.from({length:99},(e,t)=>`${E}-${t+1}${w}`)];for(let S of D){let w=resolve(t,S);try{tracedLinkSync(e,w);try{tracedUnlinkSync(e)}catch{}return S}catch(t){let S=t.code;if(S===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw S===`ENOSPC`||S===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):S===`EROFS`||S===`EACCES`||S===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let S=tmpUploadDir(e),w={scanned:0,deleted:0,errors:0};if(!existsSync(S))return w;let E;try{E=readdirSync(S)}catch(e){return log$4.warn({err:e,dir:S},`[upload-tempfile-sweep] readdir failed`),w.errors++,w}let D=Date.now()-t;for(let e of E){if(!e.startsWith(`upload-`))continue;w.scanned++;let t=resolve(S,e);try{if(statSync(t).mtimeMs>=D)continue;tracedUnlinkSync(t),w.deleted++}catch(e){log$4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),w.errors++}}return(w.deleted>0||w.errors>0)&&log$4.info({dir:S,scanned:w.scanned,deleted:w.deleted,errors:w.errors},`[upload-tempfile-sweep] swept ${w.deleted}/${w.scanned} (errors: ${w.errors})`),w}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{nextIndex:E+S};E+=t}return{nextIndex:w}}function readWikiLink$2(e,t){let S=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function readMarkdownLink$2(e,t){let S=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{text:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function readImageRef(e,t){let S=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{alt:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),S=[];for(let e=0;e<t.length;e+=2)S.push({line:t[e]??``,ending:t[e+1]??``});return S}function rewriteWikiLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let O=readWikiLink$2(e,D);if(O){O.target===t?(w+=`[[${S}${O.anchor?`#${O.anchor}`:``}${O.alias?`|${O.alias}`:``}]]`,E++):w+=e.slice(D,O.nextIndex),D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function recomputeRelativeImageHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D;if(j.startsWith(`/`)||j.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(j))return null;let F=posix.dirname(t),L=posix.dirname(S);if(F===L)return null;let B=F===`.`?`/`:`/${F}/`,H=posix.resolve(B,j).slice(1),q=posix.relative(L===`.`?``:L,H);return q||=posix.basename(H),j.startsWith(`./`)&&!q.startsWith(`./`)&&!q.startsWith(`../`)&&(q=`./${q}`),`${q}${k}${E}`}function recomputeRelativeMarkdownHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D,F=posix.dirname(t),L=posix.relative(F===`.`?``:F,S);return L||=posix.basename(S),j.endsWith(`.mdx`)?L+=`.mdx`:j.endsWith(`.md`)&&(L+=`.md`),j.startsWith(`./`)&&!L.startsWith(`./`)&&!L.startsWith(`../`)&&(L=`./${L}`),`${L}${k}${E}`}function rewriteMarkdownLinksInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`[`&&e[O+1]===`[`){let t=readWikiLink$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=t===S&&S!==w?recomputeRelativeImageHref(k.href,S,w):null;if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=``,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){if(resolveInternalHref(k.href,t)?.docName===S){let e=recomputeRelativeMarkdownHref(k.href,t,w),S=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${e}>`:e;E+=`[${k.text}](${S}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}function rewriteWikiLinksForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteWikiLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteMarkdownLinksForDocumentRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteMarkdownLinksInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteOutboundMarkdownLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let t=readWikiLink$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`!`&&e[D+1]===`[`){let t=readImageRef(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`){let O=readMarkdownLink$2(e,D);if(O){let k=resolveInternalHref(O.href,t);if(k!==null){let t=recomputeRelativeMarkdownHref(O.href,S,k.docName);if(t!==O.href){let e=O.hrefRaw.startsWith(`<`)&&O.hrefRaw.endsWith(`>`)?`<${t}>`:t;w+=`[${O.text}](${e}${O.titleSuffix})`,E++}else w+=e.slice(D,O.nextIndex)}else w+=e.slice(D,O.nextIndex);D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,S){if(posix.dirname(t)===posix.dirname(S))return{markdown:e,rewrites:0};let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteOutboundMarkdownLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,S=[];for(let{from:w,to:E}of e){for(let[e,D]of t)e!==w&&D===E&&S.push({existing:e,incoming:w,to:E});t.set(w,E)}if(S.length>0)throw new ManagedRenameCollisionError(S);return t}function rewriteSupportedLinksForRename(e,t,S,w){let{frontmatter:E,body:D}=stripFrontmatter(e),O=rewriteWikiLinksForDocumentRename(D,S,w),k=rewriteMarkdownLinksForDocumentRename(O.markdown,t,S,w);return{markdown:prependFrontmatter(E,k.markdown),rewrites:O.rewrites+k.rewrites}}function applyRenameMap(e,t,S){let w=e,E=0,D,O=[];for(let[e,w]of S)e!==w&&(e===t?D=w:O.push([e,w]));if(D!==void 0){let e=rewriteSupportedLinksForRename(w,t,t,D);w=e.markdown,E+=e.rewrites;let{frontmatter:S,body:O}=stripFrontmatter(w),k=rewriteOutboundMarkdownLinksForSourceMove(O,t,D);w=prependFrontmatter(S,k.markdown),E+=k.rewrites}let k=D??t,j=new Map;for(let[e,t]of O){let S=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,D=rewriteSupportedLinksForRename(w,k,e,S);D.rewrites>0&&(w=D.markdown,E+=D.rewrites,j.set(S,t))}for(let[e,t]of j)w=rewriteSupportedLinksForRename(w,k,e,t).markdown;return{markdown:w,rewrites:E}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,S){if(!normalizeSnippet$1(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
1189
|
+
`).slice(1);for(let e of E){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t){let S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(E.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let D=extractMetadataVersion(E);if(t!==void 0){if(!D)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(D!==t)throw Error(`SKILL.md metadata.version (${D}) does not match expected version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:S,sha256:w,skillVersion:D}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),S=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(t,S);let{size:w,sha256:E,skillVersion:D}=await validateSkillZip(S,e.expectedSkillVersion);return{outputPath:S,size:w,sha256:E,skillVersion:D}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let S=t?.homedir??(()=>process.env.HOME??``),w=t?.warn??((e,t)=>{console.warn(t,e)}),E=S();if(!E){w({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let D=join(E,...SKILL_INSTALL_EVENTS_FILE_REL),O=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(D),{recursive:!0})}catch(e){w({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(D,O,{flag:`a`,encoding:`utf-8`})}catch(e){w({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,S)=>tracedWriteFile(e,t,S),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let S=skillStateYamlPath(e),w;try{w=await readFileAsync(S,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let E=(0,import_dist$1.parseDocument)(w);if(E.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:S,errors:E.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let D=SkillStateSchema.safeParse(E.toJSON());if(!D.success){let e=D.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:S,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:S,issues:D.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return D.data}async function writeSkillStateFile(e,t){let S=SkillStateSchema.safeParse(t);if(!S.success)throw Error(`Refusing to write invalid skill-state: ${S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let w=skillStateYamlPath(e);await tracedMkdir(dirname(w),{recursive:!0});let E=(0,import_dist$1.parseDocument)(``);E.contents=E.createNode(S.data),await atomicWriteFile(w,E.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.version??null}async function readTargetRecordedAt(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,S,w,E){if(!SKILL_STATE_VERSION_RE.test(S))throw Error(`Refusing to write invalid version string: ${S}`);let D=await readSkillStateFile(e,E)??emptySkillState(),O=new Date().toISOString(),k=D.targets[t],j=w===void 0?k?.surface??void 0:w,F=j===void 0?{version:S,recordedAt:O}:{version:S,recordedAt:O,surface:j};await writeSkillStateFile(e,{...D,targets:{...D.targets,[t]:F}})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[S,w]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:S,targets:w}}async function readAllTargets(e,t=DEFAULT_LOGGER){let S=null;try{S=await readSkillStateFile(e,t)}catch(w){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(w)},`non-ENOENT error reading skill-state.yml; treating as absent`),S=null}let w=SKILL_STATE_TARGETS.map(e=>{let t=S?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(w)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,S,w,E){return new Promise(D=>{let O;try{O=e(t,S,{env:w,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){D({kind:`spawn-error`,stderr:``,error:e});return}let k=``,j=!1,F=e=>{j||(j=!0,clearTimeout(L),D(e))};O.stderr?.on(`data`,e=>{k+=typeof e==`string`?e:e.toString(`utf-8`)}),O.on(`error`,e=>{F({kind:`spawn-error`,stderr:k,error:e})}),O.on(`exit`,e=>{F(e===0?{kind:`ok`,exitCode:e,stderr:k}:{kind:`nonzero`,exitCode:e,stderr:k})});let L=setTimeout(()=>{try{O.kill(`SIGTERM`)}catch{}F({kind:`timeout`,stderr:k})},E)})}async function installUserSkill(e={}){let t=e.home??homedir(),S=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},w=e.spawn??spawn,E=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,D=e.surface??`cli-npx-skills-add`,O=async(e,w,E)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:D,target:`cli-hosts`,outcome:e,...w===void 0?{}:{version:w},...E===void 0?{}:{reason:E}},{homedir:()=>t,warn:S.warn})},k;try{k=await readServerPackageVersion()}catch(e){return S.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await O(`failed`,void 0,`version-read-failed`),`failed`}let j=await readTargetVersion(t,`cli-hosts`,S).catch(e=>(S.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(j!==null&&j===k){if(await centralSkillExists(t))return S.info?.({event:`skill-install.skip-current`,version:k},`Open Knowledge skill already installed at current version; skipping.`),await O(`skip-current`,k),`skip-current`;S.info?.({event:`skill-install.reinstall-missing`,version:k,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let F;try{F=resolveBundledSkillDir()}catch(e){return S.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await O(`failed`,k,`bundled-asset-missing`),`failed`}let L=await runSpawn(w,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,F,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},E);if(L.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,k,D,S)}catch(e){return S.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await O(`failed`,k,`sidecar-write-failed`),`failed`}return S.info?.({event:`skill-install.installed`,version:k},`Open Knowledge skill installed to detected agent hosts.`),await O(`installed`,k),`installed`}return L.kind===`timeout`?(S.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:E,stderr:L.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`timeout`),`failed`):L.kind===`spawn-error`?(S.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(L.error),stderr:L.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`spawn-error`),`failed`):(S.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:L.exitCode,stderr:L.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`nonzero-exit:${L.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,S){let w={detached:!0,stdio:`ignore`};try{return t===`darwin`?(S(`open`,[e],w).unref(),{ok:!0}):t===`win32`?(S(`cmd`,[`/c`,`start`,`""`,e],w).unref(),{ok:!0}):t===`linux`?(S(`xdg-open`,[e],w).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),S=resolve(e.out??defaultDownloadsPath(t)),w=e.platformName??platform(),E=e.spawnFn??spawn,D=e.logger,O=async(e,S,w)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,outcome:e,...S===void 0?{}:{version:S},...w===void 0?{}:{reason:w}},{homedir:()=>t,warn:D?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){D?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let S=null,w=null;try{[S,w]=await Promise.all([readTargetVersion(t,`claude-cowork`,D),readTargetRecordedAt(t,`claude-cowork`,D)])}catch(e){D?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(S!==null&&S===e)return D?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await O(`skip-current`,e),{status:`skip-current`,skillVersion:e,...w===null?{}:{recordedAt:w}}}}try{await tracedMkdir(dirname(S),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let k;try{k=await buildSkillZip({outputPath:S})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let j={status:`built`,outputPath:k.outputPath,size:k.size,sha256:k.sha256,skillVersion:k.skillVersion};if(k.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,k.skillVersion,`server-build-and-open`,D)}catch(e){D?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:k.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await O(`built`,k.skillVersion),j;let F=invokeFileAssociation(k.outputPath,w,E);return F.ok?(await O(`installed`,k.skillVersion),{...j,status:`installed`}):(await O(`built`,k.skillVersion,`handoff-${F.reason}`),{...j,handoffError:{reason:F.reason,message:F.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$4=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,S){this.hash.update(e),this.bytes+=e.length,S(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,S){let w=extname(S),E=S.slice(0,S.length-w.length),D=[S,...Array.from({length:99},(e,t)=>`${E}-${t+1}${w}`)];for(let S of D){let w=resolve(t,S);try{tracedLinkSync(e,w);try{tracedUnlinkSync(e)}catch{}return S}catch(t){let S=t.code;if(S===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw S===`ENOSPC`||S===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):S===`EROFS`||S===`EACCES`||S===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let S=tmpUploadDir(e),w={scanned:0,deleted:0,errors:0};if(!existsSync(S))return w;let E;try{E=readdirSync(S)}catch(e){return log$4.warn({err:e,dir:S},`[upload-tempfile-sweep] readdir failed`),w.errors++,w}let D=Date.now()-t;for(let e of E){if(!e.startsWith(`upload-`))continue;w.scanned++;let t=resolve(S,e);try{if(statSync(t).mtimeMs>=D)continue;tracedUnlinkSync(t),w.deleted++}catch(e){log$4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),w.errors++}}return(w.deleted>0||w.errors>0)&&log$4.info({dir:S,scanned:w.scanned,deleted:w.deleted,errors:w.errors},`[upload-tempfile-sweep] swept ${w.deleted}/${w.scanned} (errors: ${w.errors})`),w}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{nextIndex:E+S};E+=t}return{nextIndex:w}}function readWikiLink$2(e,t){let S=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function readMarkdownLink$2(e,t){let S=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{text:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function readImageRef(e,t){let S=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{alt:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),S=[];for(let e=0;e<t.length;e+=2)S.push({line:t[e]??``,ending:t[e+1]??``});return S}function rewriteWikiLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let O=readWikiLink$2(e,D);if(O){O.target===t?(w+=`[[${S}${O.anchor?`#${O.anchor}`:``}${O.alias?`|${O.alias}`:``}]]`,E++):w+=e.slice(D,O.nextIndex),D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function recomputeRelativeImageHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D;if(j.startsWith(`/`)||j.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(j))return null;let F=posix.dirname(t),L=posix.dirname(S);if(F===L)return null;let B=F===`.`?`/`:`/${F}/`,H=posix.resolve(B,j).slice(1),q=posix.relative(L===`.`?``:L,H);return q||=posix.basename(H),j.startsWith(`./`)&&!q.startsWith(`./`)&&!q.startsWith(`../`)&&(q=`./${q}`),`${q}${k}${E}`}function recomputeRelativeMarkdownHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D,F=posix.dirname(t),L=posix.relative(F===`.`?``:F,S);return L||=posix.basename(S),j.endsWith(`.mdx`)?L+=`.mdx`:j.endsWith(`.md`)&&(L+=`.md`),j.startsWith(`./`)&&!L.startsWith(`./`)&&!L.startsWith(`../`)&&(L=`./${L}`),`${L}${k}${E}`}function rewriteMarkdownLinksInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`[`&&e[O+1]===`[`){let t=readWikiLink$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=t===S&&S!==w?recomputeRelativeImageHref(k.href,S,w):null;if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=``,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){if(resolveInternalHref(k.href,t)?.docName===S){let e=recomputeRelativeMarkdownHref(k.href,t,w),S=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${e}>`:e;E+=`[${k.text}](${S}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,S){let w=``,E=0,D=0;for(;D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`<`){let O=new RegExp(MIRROR_TAG_RE.source),k=e.slice(D),j=O.exec(k);if(j&&j.index===0){let[e,O]=j,k=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),F=O.replace(k,(e,w,D,O)=>O===t?(E++,`${w}${D}${S}${D}`):e);w+=`<Mirror${F}/>`,D+=e.length;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteMirrorSrcForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteMirrorSrcInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteWikiLinksForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteWikiLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteMarkdownLinksForDocumentRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteMarkdownLinksInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteOutboundMarkdownLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let t=readWikiLink$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`!`&&e[D+1]===`[`){let t=readImageRef(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`){let O=readMarkdownLink$2(e,D);if(O){let k=resolveInternalHref(O.href,t);if(k!==null){let t=recomputeRelativeMarkdownHref(O.href,S,k.docName);if(t!==O.href){let e=O.hrefRaw.startsWith(`<`)&&O.hrefRaw.endsWith(`>`)?`<${t}>`:t;w+=`[${O.text}](${e}${O.titleSuffix})`,E++}else w+=e.slice(D,O.nextIndex)}else w+=e.slice(D,O.nextIndex);D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,S){if(posix.dirname(t)===posix.dirname(S))return{markdown:e,rewrites:0};let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteOutboundMarkdownLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,S=[];for(let{from:w,to:E}of e){for(let[e,D]of t)e!==w&&D===E&&S.push({existing:e,incoming:w,to:E});t.set(w,E)}if(S.length>0)throw new ManagedRenameCollisionError(S);return t}function rewriteSupportedLinksForRename(e,t,S,w){let{frontmatter:E,body:D}=stripFrontmatter(e),O=rewriteWikiLinksForDocumentRename(D,S,w),k=rewriteMarkdownLinksForDocumentRename(O.markdown,t,S,w),j=rewriteMirrorSrcForDocumentRename(k.markdown,S,w);return{markdown:prependFrontmatter(E,j.markdown),rewrites:O.rewrites+k.rewrites+j.rewrites}}function applyRenameMap(e,t,S){let w=e,E=0,D,O=[];for(let[e,w]of S)e!==w&&(e===t?D=w:O.push([e,w]));if(D!==void 0){let e=rewriteSupportedLinksForRename(w,t,t,D);w=e.markdown,E+=e.rewrites;let{frontmatter:S,body:O}=stripFrontmatter(w),k=rewriteOutboundMarkdownLinksForSourceMove(O,t,D);w=prependFrontmatter(S,k.markdown),E+=k.rewrites}let k=D??t,j=new Map;for(let[e,t]of O){let S=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,D=rewriteSupportedLinksForRename(w,k,e,S);D.rewrites>0&&(w=D.markdown,E+=D.rewrites,j.set(S,t))}for(let[e,t]of j)w=rewriteSupportedLinksForRename(w,k,e,t).markdown;return{markdown:w,rewrites:E}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,S){if(!normalizeSnippet$1(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
1189
1190
|
`,t-1)),E=[e.indexOf(`.`,S),e.indexOf(`?`,S),e.indexOf(`!`,S),e.indexOf(`
|
|
1190
1191
|
`,S)].filter(e=>e>=0),D=w>=0?w+1:Math.max(0,t-60),O=E.length>0?Math.min(...E)+1:Math.min(e.length,S+60),k=D>0?`…`:``,j=O<e.length?`…`:``,F=normalizeSnippet$1(e.slice(D,O));return F?`${k}${F}${j}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{text:e.slice(w,E),nextIndex:E+S};E+=t}return{text:e.slice(t,w),nextIndex:w}}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let S=WIKI_LINK_RE$1.exec(e);if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function extractWikiLinksFromLine(e){let t=``,S=[],w=leadingMarkdownPrefixLength$1(e);for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){t+=e[w+1],w+=2;continue}if(e[w]==="`"){let S=readInlineCode$1(e,w);if(S){t+=S.text,w=S.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$1(e,w);if(E){let e=getWikiLinkText(E),D=t.length;t+=e;let O=classifyWikiLinkTarget(E.target,E.anchor);O?.kind===`doc`&&S.push({target:O.docName,anchor:O.anchor,start:D,end:D+e.length}),w=E.nextIndex;continue}}t+=e[w],w++}return{text:t,occurrences:S}}function extractExternalWikiLinksFromLine(e){let t=``,S=[],w=leadingMarkdownPrefixLength$1(e);for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){t+=e[w+1],w+=2;continue}if(e[w]==="`"){let S=readInlineCode$1(e,w);if(S){t+=S.text,w=S.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$1(e,w);if(E){let e=getWikiLinkText(E),D=t.length;t+=e;let O=classifyWikiLinkTarget(E.target,E.anchor);O?.kind===`external`&&S.push({url:O.url,label:e,start:D,end:D+e.length}),w=E.nextIndex;continue}}t+=e[w],w++}return{text:t,occurrences:S}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$1(e,t){MD_LINK_RE$1.lastIndex=t;let S=MD_LINK_RE$1.exec(e);return S?{text:S[1]??``,href:normalizeMarkdownHref$1(S[2]??``),nextIndex:t+S[0].length}:null}function extractMarkdownLinksFromLine(e,t){let S=``,w=[],E=leadingMarkdownPrefixLength$1(e);for(;E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e[E+1],E+=2;continue}if(e[E]==="`"){let t=readInlineCode$1(e,E);if(t){S+=t.text,E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$1(e,E);if(t){S+=getWikiLinkText(t),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E-1]!==`!`){let D=readMarkdownLink$1(e,E);if(D){let e=classifyMarkdownHref(D.href,t);if(e?.kind===`doc`){let t=S.length;S+=D.text,w.push({target:e.docName,anchor:e.anchor,start:t,end:t+D.text.length})}else S+=D.text;E=D.nextIndex;continue}}S+=e[E],E++}return{text:S,occurrences:w}}function extractExternalMarkdownLinksFromLine(e,t){let S=``,w=[],E=leadingMarkdownPrefixLength$1(e);for(;E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e[E+1],E+=2;continue}if(e[E]==="`"){let t=readInlineCode$1(e,E);if(t){S+=t.text,E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$1(e,E);if(t){S+=getWikiLinkText(t),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E-1]!==`!`){let D=readMarkdownLink$1(e,E);if(D){let e=classifyMarkdownHref(D.href,t);if(S+=D.text,e?.kind===`external`){let t=S.length-D.text.length;w.push({url:e.url,label:D.text||null,start:t,end:t+D.text.length})}E=D.nextIndex;continue}}S+=e[E],E++}return{text:S,occurrences:w}}function extractMarkdownLinksFromMarkdown(e,t){let S=e.replaceAll(`\r
|
|
1191
1192
|
`,`
|
|
@@ -2103,34 +2104,13 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2103
2104
|
`)){let S=e.indexOf(`
|
|
2104
2105
|
---`,3);S!==-1&&(t=e.slice(S+4))}let S=[],w=new Map,E=createCodeFenceTracker();for(let e of t.split(`
|
|
2105
2106
|
`)){if(E(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),E=getHeadingSlug(e,w);E&&S.push({level:t[1].length,text:e,slug:E})}}return S}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function createApiExtension(e){let{hocuspocus:t,sessionManager:S,contentDir:w,serverInstanceId:E,getFileIndex:D,getFolderIndex:O,getAliasMap:k,rescanFiles:j,enableTestRoutes:F=!1,shadowRef:L,flushGitCommit:B,flushContributors:H,getCurrentBranch:q,getDiskAckSVs:J,contentRoot:Y,backlinkIndex:ee,tagIndex:te,signalChannel:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,onAgentWrite:se,getSyncEngine:ce,localOpCliArgs:ue=[`open-knowledge`],projectDir:de,getPrincipal:fe,contentFilter:me,installedAgentsProbe:ge,forceUnloadDocument:_e,ready:ve,recentlyRemovedDocs:ye}=e,Ce=createConcurrencyGuard(),we=null;function Te(){let e=O?.();return e instanceof Map?e:null}function De(e){let t=Te();if(t)try{upsertFolderIndexEntry(t,w,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function je(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)De(resolve(w,t.slice(0,e).join(`/`)))}function Me(e){let t=Te();t&&removeFolderIndexEntries(t,e)}function Pe(e,t){let S=Te();if(!S)return;let E=[];for(let[w,D]of[...S.entries()]){if(w!==e&&!w.startsWith(`${e}/`))continue;S.delete(w);let O=w.slice(e.length);E.push([`${t}${O}`,D])}if(E.length===0){let e=resolveContentEntryPath(w,`folder`,t);existsSync(e)&&De(e);return}for(let[e,t]of E)S.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(w,e)})}function Ie(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
2106
|
-
`)}let Re=createInstalledAgentsProbe({probe:ge??createOsProbe(process.platform)});function ze(e){if(!isSafeDocName(e))return null;let t=resolve(w),S=resolve(t,`${e}${getDocExtension(e)}`);return!S.startsWith(`${t}/`)&&S!==t?null:S}function Be(e){let t=ze(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Ve(e,t){return t.has(e)?Be(e):e}let Ue={cluster:void 0,category:void 0,tags:void 0};function We(e){try{let S=t.documents.get(e);if(S){let e=readFmMap(S.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,S=typeof e.category==`string`?e.category:void 0,w;return Array.isArray(e.tags)?w=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(w=[e.tags]),{cluster:t,category:S,tags:w}}}}catch{}try{let t=ze(e);if(!t||!existsSync(t))return Ue;let{frontmatter:S}=stripFrontmatter(readFileSync(t,`utf-8`));return S?parseFrontmatterMetadata(S):Ue}catch{return Ue}}function Ge(e,t){return t.has(e)?We(e):Ue}function Ke(e){if(ee)try{if(ee.getBacklinks(e).length>0)return;let t=performance.now(),S=findHubCandidates(e,D()),w=performance.now()-t;return w>5&&log$2.debug({docName:e,elapsedMs:w,candidateCount:S.length},`[orphan-hint] findHubCandidates slow`),S.length===0?void 0:[{type:`orphan`,parentCandidates:S,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${S.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function Xe(e){return k?.().get(e)??e}function $e(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function nt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function rt(e,S){let w=`onStoreDocument-${e}`;(t.debouncer.isDebounced(w)?t.debouncer.executeNow(w):Promise.resolve()).then(()=>B?.()).catch(e=>{log$2.warn({err:e},`[${S}] post-write flush failed`)})}function it(){let e=new Set;for(let[t,S]of D()){e.add(t);for(let t of S.aliases)e.add(t)}return e}function at(){let e=Promise.resolve();return async function(t){let S=e,w=()=>{};e=new Promise(e=>{w=e}),await S;try{return await t()}finally{w()}}}let st=at(),vt=e=>e.endsWith(`.`)?e:`${e}.`;function Tt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:vt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError?{status:400,type:`urn:ok:error:invalid-request`,error:vt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:vt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:vt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Et(e){let w=new Map;for(let S of e){let e=t.documents.get(S);e&&w.set(S,e.getText(`source`).toString())}for(let t of e)await S.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let S of e){let e=t.documents.get(S);deleteReconciledBase(S),e&&(t.closeConnections(S),await(_e??t.unloadDocument.bind(t))(e))}return w}function Dt(e,t){for(let{fromDocName:S,toDocName:E}of e){let e=safeContentPath(E,w),D=t.get(S);typeof D==`string`&&tracedWriteFileSync(e,D,`utf-8`);let O=typeof D==`string`?D:existsSync(e)?readFileSync(e,`utf-8`):null;typeof O==`string`&®isterWrite(e,contentHash(O))}}function jt(e,t){return e.map(e=>{let S=t.get(e);if(typeof S==`string`)return{docName:e,content:S};let E=safeContentPath(e,w);if(!existsSync(E))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(E,`utf-8`)}})}function Mt(e){let S=t.documents.get(e);if(S)return S.getText(`source`).toString();let E=resolveContentEntryPath(w,`file`,e);return existsSync(E)?readFileSync(E,`utf-8`):null}function Ft(e,t){let S=resolveContentEntryPath(w,`file`,e);tracedMkdirSync(dirname(S),{recursive:!0}),tracedWriteFileSync(S,t,`utf-8`),registerWrite(S,contentHash(t)),setReconciledBase(e,t);let E=D();E instanceof Map&&updateFileIndex({kind:`update`,path:S,docName:e,content:t},E)}function It(e,S){let w=t.documents.get(e);if(!w)throw Error(`Document is not loaded: ${e}`);let E={markdown:``,rewrites:0};return w.transact(()=>{E=applyRenameMap(w.getText(`source`).toString(),e,S),E.rewrites!==0&&composeAndWriteRawBody(w,E.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),E}async function Lt(e,S,E,O){return st(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":E}},async k=>{if(!ee)throw new BacklinkIndexRequiredError;let j=resolveContentEntryPath(w,E,e),F=resolveContentEntryPath(w,E,S);if(j===F)return{renamed:[],rewrittenDocs:[]};if(!existsSync(j))throw new ManagedRenameSourceNotFoundError(E);if(existsSync(F))throw new ManagedRenameDestinationExistsError;let B=statSync(j);if(E===`file`&&!B.isFile()||E===`folder`&&!B.isDirectory())throw new ManagedRenameSourceTypeMismatchError(E);let H=(E===`file`?[stripDocExtension(e)]:listAffectedDocNames(D(),E,e)).map(t=>({from:t,to:E===`file`?stripDocExtension(S):remapDocNameForRename(t,E,e,S)}));if(k.setAttribute(`rename.affected_docs`,H.length),H.length===0)return E===`folder`&&(await renameTrackedPathInGit(de,j,F)||(tracedMkdirSync(dirname(F),{recursive:!0}),tracedRenameSync(j,F)),Pe(e,S),ne?.(`files`)),{renamed:[],rewrittenDocs:[]};let J=buildRenameMap(H),Y=H.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),te=new Set;for(let{from:e}of H)for(let t of ee.getBacklinks(e))J.has(t.source)||te.add(t.source);let ae=[...te].sort((e,t)=>e.localeCompare(t)),oe=new Map,se=[],ce=[];for(let e of[...J.keys(),...ae]){if(oe.has(e))continue;if(!J.has(e)&&!existsSync(resolveContentEntryPath(w,`file`,e))){ce.push(e);continue}let t=Mt(e);typeof t==`string`?(oe.set(e,t),J.has(e)||se.push(e)):J.has(e)||ce.push(e)}for(let{from:e}of H)if(typeof oe.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:S,affectedDocs:[...H],snapshots:jt([...oe.keys()],oe)}),fe=[];return await withManagedRenameRecovery(de??w,ue,async()=>{for(let e of ce)ee.deleteDocument(e);for(let e of se){let S=t.documents.get(e)?It(e,J):applyRenameMap(oe.get(e)??``,e,J);S.rewrites>0&&(Ft(e,S.markdown),fe.push({docName:e,rewrites:S.rewrites})),ee.updateDocumentFromMarkdown(e,S.markdown)}if(ye)for(let{from:e,to:t}of H)isSystemDoc(e)||isConfigDoc(e)||(ye.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let k=resolveContentEntryPath(w,E,e),j=resolveContentEntryPath(w,E,S);await renameTrackedPathInGit(de,k,j)||(tracedMkdirSync(dirname(j),{recursive:!0}),tracedRenameSync(k,j)),E===`folder`&&Pe(e,S);let F=await Et([...J.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(L?.current){let e=L.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":E}},t=>{let S=randomUUID(),w=new Date().toISOString(),D=q?.()??`main`,k=getOrLoadRenameLogIndex(e.gitDir),j=O?.actor?{writerId:O.actor.writerId,displayName:O.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},F=0;for(let{from:t,to:L}of H){let B={v:1,from:t,to:L,at:w,commitSha:``,branch:D,groupId:S,kind:E,actor:j};appendRenameLogEntry(e.gitDir,B,k,e),F+=1,O?.actor?recordContributor(L,O.actor.writerId,O.actor.displayName,O.actor.colorSeed,formatRenameSubject(t,L),O.actor.actorMetadata,void 0,[{from:t,to:L}]):recordContributor(L,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,L),void 0,void 0,[{from:t,to:L}])}t.setAttribute(`rename.entries_appended`,F)})}let B=E===`file`&&isSupportedDocFile(S)?extname(S):null;for(let{from:e,to:t}of H){let S=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,B??S)}let Y=[...H].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of Y){let S=resolveContentEntryPath(w,`file`,e),E=resolveContentEntryPath(w,`file`,t),O=applyRenameMap(F.get(e)??oe.get(e)??readFileSync(E,`utf-8`),e,J);Dt([{fromDocName:e,toDocName:t}],new Map([[e,O.markdown]])),setReconciledBase(t,O.markdown);let k=D();k instanceof Map&&updateFileIndex({kind:`rename`,oldPath:S,newPath:E,oldDocName:e,newDocName:t,content:O.markdown},k),ee.renameDocument(e,t,O.markdown),O.rewrites>0&&fe.push({docName:t,rewrites:O.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ee.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ne?.(`files`),ne?.(`backlinks`),ne?.(`graph`),fe.sort((e,t)=>e.docName.localeCompare(t.docName)),k.setAttribute(`rename.rewrite_count`,fe.length),{renamed:Y,rewrittenDocs:fe}}))}function Rt(e){let t=parseAgentBodyFields(e),S=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:S,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??S,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function zt(e){return{principalId:fe?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Bt(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function Vt(e){return{value:e.value}}function Ht(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}let Ut=withValidation(AgentWriteRequestSchema,async(t,w,E)=>{try{let t=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:D,agentName:O,colorSeed:k,clientName:j,clientVersion:F,label:L}=Rt(E);if(isSystemDoc(t)||isConfigDoc(t)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-write`});return}let B=normalizeSummary(E.summary),H=await S.getSession(t,D,{displayName:O,colorSeed:k,clientName:j}),q=new Date().toISOString(),J=typeof E.content==`string`?E.content:`Hello from the agent! ${q}`,{response:Y,stored:ee}=Bt(B);try{let S=iconFromClientName(j),w=AGENT_ICON_COLORS[S]??colorFromSeed(k??D);oe?.setPresence(D,{displayName:O,icon:S,color:w,currentDoc:t,mode:`writing`,ts:Date.now()}),captureEffect(H.dc.document.getText(`source`),D,k,j),H.dc.document.transact(()=>{applyAgentMarkdownWrite(H.dc.document,`${J}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:t}:void 0),H.dc.document.getMap(`agent-flash`).set(D,{agentId:D,timestamp:Date.now(),type:`insert`,description:`Added (${O}): ${J.slice(0,50)}`})},H.origin),recordContributor(t,D,O,k,void 0,zt({clientName:j,clientVersion:F,label:L}),ee),incrementAgentWriteCalls(),Ht(B)}finally{oe?.touchMode(D,`idle`)}rt(t,`agent-write`),se?.(),successResponse(w,200,AgentWriteSuccessSchema,{timestamp:q,...Y?{summary:Y}:{}},{handler:`agent-write`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Wt=withValidation(AgentWriteMdRequestSchema,async(t,w,E)=>{try{let t=E.position??`append`,D=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Rt(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write-md`});return}let H=normalizeSummary(E.summary),{response:q,stored:J}=Bt(H),Y=await S.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=new Date().toISOString();try{let S=iconFromClientName(F),w=AGENT_ICON_COLORS[S]??colorFromSeed(j??O);oe?.setPresence(O,{displayName:k,icon:S,color:w,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),O,j,F),Y.dc.document.transact(()=>{applyAgentMarkdownWrite(Y.dc.document,E.markdown,t,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),Y.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),recordContributor(D,O,k,j,void 0,zt({clientName:F,clientVersion:L,label:B}),J),incrementAgentWriteCalls(),Ht(H)}finally{oe?.touchMode(O,`idle`)}rt(D,`agent-write-md`),ae?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),se?.();let te=Ke(D),ne=$e(D),ce=nt();ce===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)}),successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ee,subscriberCount:ne,systemSubscriberCount:ce,...te?{hints:te}:{},...q?{summary:q}:{}},{handler:`agent-write-md`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Kt=withValidation(EmptyRequestSchema,async(e,S)=>{try{let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(E)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let D=Xe(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`document-read`});return}let O=t.documents.get(D);if(O){successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:O.getText(`source`).toString()},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(w,`file`,D))){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document not found: ${D}.`,{handler:`document-read`});return}let k=await t.openDirectConnection(D);try{let e=k.document;if(!e){errorResponse(S,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:e.getText(`source`).toString()},{handler:`document-read`})}finally{await k.disconnect()}}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),$t=withValidation(EmptyRequestSchema,async(e,t)=>{try{ve&&await ve.catch(e=>{log$2.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=S.searchParams.get(`dir`),k=S.searchParams.get(`showAll`)===`true`;if(E)try{safeSubdir(w,E)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(k&&me){let e=[];try{await walkContentDirForShowAll({contentDir:w,contentFilter:me,dirFilter:E,documents:e,getDocExtension}),e.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:e},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}return}let j=D(),F=O?.()??new Map,L=[];for(let[e,t]of F)E&&!e.startsWith(`${E}/`)&&e!==E||L.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of j){if(E&&!e.startsWith(`${E}/`)&&e!==E)continue;let S=getDocExtension(e);L.push({kind:`document`,docName:e,docExt:S,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let D of t.aliases){if(E&&!D.startsWith(`${E}/`)&&D!==E)continue;let O=relative(w,t.canonicalPath);L.push({kind:`document`,docName:D,docExt:S,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:O})}}let B=[];try{let e=Ie(j);we?.signature!==e&&(we={signature:e,assets:collectReferencedAssets({contentDir:w,fileIndex:j,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:me?e=>me.isPathIgnored(e):void 0})}),B=we?.assets??[]}catch(e){we=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of B)E&&!e.path.startsWith(`${E}/`)&&e.path!==E||L.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});L.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:L},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),en=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:S,backlinks:ee.getBacklinks(S).map(e=>({source:e.source,anchor:e.anchor,title:Be(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),jr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let w={};for(let e of S.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(w[t]=ee.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:w},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Mr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let w=it();successResponse(t,200,ForwardLinksSuccessSchema,{docName:S,forwardLinks:ee.getForwardLinkEntries(S).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ve(e.target,w),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Fr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`docName`);if(w&&!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let E=S.searchParams.get(`degrees`);if(E&&!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let D,O;if(E&&w){let e=Number.parseInt(E,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:D,links:O}=ee.getLinkGraphNeighborhood(w,e))}else ({nodes:D,links:O}=ee.getLinkGraph());let k=it();successResponse(t,200,LinkGraphSuccessSchema,{nodes:D.map(e=>{if(e.kind===`doc`){let t=Ge(e.docName,k);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ve(e.docName,k),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:O},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Ir=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ee.getOrphans([...D().keys()],S).map(e=>({docName:e,title:Be(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),Lr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),w=S?Number.parseInt(S,10):20,E=Number.isFinite(w)&&w>0?w:20,D=it();successResponse(t,200,HubsSuccessSchema,{hubs:ee.getHubs(E).map(e=>({docName:e.docName,title:Ve(e.docName,D),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),zr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(S.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let w=S.length?[...new Set(S.map(e=>Xe(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ee.getDeadLinks(it(),w).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Be(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Br=withValidation(AgentPatchRequestSchema,async(t,w,E)=>{try{let{find:t,replace:D,offset:O}=E,k=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:j,agentName:F,colorSeed:L,clientName:B,clientVersion:H,label:q}=Rt(E);if(findLooksLikeFrontmatter(t)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await S.getSession(k,j,{displayName:F,colorSeed:L,clientName:B}),ee=new Date().toISOString(),te=!1,ne=!1,ce=!1;try{let S=iconFromClientName(B),w=AGENT_ICON_COLORS[S]??colorFromSeed(L??j);if(oe?.setPresence(j,{displayName:F,icon:S,color:w,currentDoc:k,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),j,L,B),Y.dc.document.transact(()=>{let{frontmatter:S,body:w}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),E=prependFrontmatter(S,w),L=O==null?E.indexOf(t):E.slice(O,O+t.length)===t?O:-1;if(L===-1){O==null?te=!0:ne=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":k,findLength:t.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(L<S.length){ce=!0;return}let{body:B}=stripFrontmatter(E.slice(0,L)+D+E.slice(L+t.length));applyAgentMarkdownWrite(Y.dc.document,B,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0),Y.dc.document.getMap(`agent-flash`).set(j,{agentId:j,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${t.slice(0,50)}`})},Y.origin),!te&&!ne&&!ce){let{stored:e}=Bt(J);recordContributor(k,j,F,L,void 0,zt({clientName:B,clientVersion:H,label:q}),e),incrementAgentWriteCalls(),Ht(J)}}finally{oe?.touchMode(j,`idle`)}if(ne){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(te){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ce){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}rt(k,`agent-patch`),ae?.setFocus(j,{agentName:F,currentDoc:k,writeKind:`edit`,ts:Date.now()}),se?.();let ue=$e(k),de=nt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(B)});let{response:fe}=Bt(J);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,...fe?{summary:fe}:{}},{handler:`agent-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Vr=withValidation(AgentUndoRequestSchema,async(t,w,E)=>{try{let{agentId:t,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Rt(E),L=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`);if(isSystemDoc(L)||isConfigDoc(L)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${L}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:B}=E,H=E.scope===`session`||E.scope===`file`?`session`:`last`;if(!S.hasSession(L,B)){errorResponse(w,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let q=await S.getSession(L,B),J=!1;try{let S=iconFromClientName(k),w=AGENT_ICON_COLORS[S]??colorFromSeed(O??t);oe?.setPresence(t,{displayName:D,icon:S,color:w,currentDoc:L,mode:`writing`,ts:Date.now()}),J=applyAgentUndo(q,H,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:L}:void 0),J&&recordContributor(L,B,D,O,void 0,zt({clientName:k,clientVersion:j,label:F}))}finally{oe?.touchMode(t,`idle`)}J&&rt(L,`agent-undo`),ae?.setFocus(B,{agentName:B,currentDoc:L,writeKind:`undo`,ts:Date.now()}),successResponse(w,200,AgentUndoSuccessSchema,{docName:L,scope:H,undone:J},{handler:`agent-undo`})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Hr=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(S,w),{handler:`agent-activity`})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Ur=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=validateAgentId(w.searchParams.get(`agentId`)),D=w.searchParams.get(`docName`),O=w.searchParams.get(`stackIndex`);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!D||D.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let k=Xe(D);if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!O||Number.isNaN(Number(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let j=Number(O);if(!Number.isInteger(j)||j<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let F=S.getLiveSession(k,E);if(!F){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let L=F.um;if(j>=L.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${j} out of range (stack has ${L.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let B=L.undoStack[j];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(B,F.dc.document.getText(`source`),k),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Wr=withValidation(EmptyRequestSchema,async(e,E)=>{try{let D=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),O=Xe(D.searchParams.get(`docName`)??`test-doc`),k;try{k=safeContentPath(O,w)}catch(e){log$2.error({err:e,docName:O},`[test-reset] safeContentPath rejected docName`),errorResponse(E,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await S.closeAll(O),t.closeConnections(O);let j=`onStoreDocument-${O}`;t.debouncer.isDebounced(j)&&await t.debouncer.executeNow(j);let F=t.documents.get(O);if(F&&await(_e??t.unloadDocument.bind(t))(F),writeFileSync(k,``,`utf-8`),ee&&(ee.deleteDocument(O),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${O}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),D.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(w,`.okignore`),S=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(S){let e=S.getText(`source`);e.length>0&&S.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),me&&await me.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}ne?.(`files`),successResponse(E,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Gr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ee.rebuildFromDisk(),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),ne?.(`backlinks`),ne?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),Kr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!j){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}j(),ne?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),qr=withValidation(SaveVersionRequestSchema,async(e,t,S)=>{try{let{rawAgentId:e,agentId:w,agentName:E,clientName:D}=Rt(S),O=L?.current;if(!O){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let k=/^[a-zA-Z0-9_-]+$/,j=[],F,B,H;if(typeof S.message==`string`&&S.message.trim()&&(F=S.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(S.writers))try{j=S.writers.map(e=>{let t=e.id??`unknown`;if(!k.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}S.principal&&(typeof S.principal.name==`string`&&S.principal.name.trim()&&(B=sanitizeGitIdentity(S.principal.name.trim())),typeof S.principal.email==`string`&&S.principal.email.trim()&&(H=sanitizeGitIdentity(S.principal.email.trim()))),j.length===0&&(j=e===void 0?[SERVICE_WRITER]:[{id:w,name:D?`${E} (${D})`:E,email:`${w}@openknowledge.local`}]);let q=Y??`.`,J=await saveVersion(O,q,j);console.log(`[history] checkpoint ${J.checkpointRef}`);try{await gcRenameLog(O,getOrLoadRenameLogIndex(O.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}let ee=swapContributors(),te;if(de){let e=!1;try{await esm_default({baseDir:de,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{te=await withParentLock(async()=>{let e=esm_default({baseDir:de,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,S=`ok/v${t}`,w=`openknowledge`,E=`noreply@openknowledge.local`;if(B&&H)w=B,E=H;else try{let e=await resolveGitIdentity(de);e&&(w=e.name,E=e.email)}catch{}let D=[];for(let e of ee.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;D.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let O=formatCheckpointSubject(F??`Checkpoint v${t}`),k=D.length>0?`${O}\n\n${D.join(`
|
|
2107
|
-
`)}`:O,j=q||`.`;return await e.add(j),await e.env({GIT_AUTHOR_NAME:w,GIT_AUTHOR_EMAIL:E,GIT_COMMITTER_NAME:w,GIT_COMMITTER_EMAIL:E}).commit(k,[`--allow-empty`]),await e.addTag(S),console.log(`[checkpoint] parent-git commit + tag ${S}`),S})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:J.checkpointRef,...te?{versionTag:te}:{}},{handler:`save-version`})}catch(e){log$2.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),
|
|
2108
|
-
`),S=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:S,text:e});e.added&&(ne+=t.length),e.removed&&(ae+=t.length)}successResponse(S,200,DiffSuccessSchema,{lines:Y,additions:ne,deletions:ae},{handler:`diff`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Zr=withValidation(RollbackRequestSchema,async(S,w,E)=>{let D=extractActorIdentity(E,fe);if(D.kind===`invalid-summary`){errorResponse(w,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let O=L?.current;if(!O){errorResponse(w,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:k,commitSha:j,versionTag:F}=E,B=Y??`.`,H=safeDocPath(k,B);if(`error`in H){errorResponse(w,400,`urn:ok:error:invalid-request`,H.error,{handler:`rollback`});return}let J=shadowGit(O),ee=Date.now();try{let S=getOrLoadRenameLogIndex(O.gitDir),E=createAncestorShaSetCache(),L=await resolveDocPathAtCommit(O,k,j,q?.()??`main`,S,e=>{let t=safeDocPath(e,B);return`error`in t?`${e}.md`:t.path},E);if(L===null){errorResponse(w,404,`urn:ok:error:doc-not-found`,`Commit ${j.slice(0,7)} does not contain document ${k} at any known historical path.`,{handler:`rollback`});return}let H=await J.raw(`show`,`${j}:${L}`),te=new Date().toISOString();await safetyCheckpoint(O,B,{action:`rollback`,context:{docName:k,targetSha:j}});let ne=t.documents.get(k);if(!ne){errorResponse(w,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let oe=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0;ne.transact(()=>{replaceRawBody(ne,H,oe)},ROLLBACK_ORIGIN);let se;switch(D.kind){case`agent`:{let e=j.slice(0,8),t=D.summary.kind===`value`,S=t?D.summary:normalizeSummary(`Restored to ${e}`),w=Bt(S);se=t||!w.response?w.response:Vt(w.response),recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,w.stored),incrementAgentWriteCalls(),Ht(S,!t);break}case`principal`:{let e=Bt(D.summary);se=e.response,recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,e.stored),Ht(D.summary,!1);break}case`anonymous`:log$2.debug({docName:k,commitSha:j.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(D.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:D.kind}),rt(k,`rollback`);let ce=Date.now()-ee;if(console.log(`[rollback] docName=${k} from=${j.slice(0,8)} duration=${ce}ms`),de){let e=`Restored to ${F??j.slice(0,8)}: ${k}`,t=Y??`.`;withParentLock(async()=>{let S=esm_default({baseDir:de,timeout:{block:15e3}}),w=t||`.`;await S.add(w),await S.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}D.kind===`agent`&&ae?.setFocus(D.writerId,{agentName:D.displayName,currentDoc:k,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(w,200,RollbackSuccessSchema,{restoredFrom:j,timestamp:te,...se?{summary:se}:{}},{handler:`rollback`})}catch(e){errorResponse(w,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Qr=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$2.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),ji=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$2.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Hi=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=getActiveBranch(),S=J?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:E,currentBranch:e,...S===void 0?{}:{currentDiskAckSVs:S}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function Ui(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let S=fe?.()??null;if(!S){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,S,{handler:`principal`})}async function Gi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=oe?.getPresenceMap()??{},S=Date.now(),w={};for(let[t,E]of Object.entries(e))S-E.ts<2e4&&(w[t]=E);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:w},{handler:`metrics-agent-presence`})}catch(e){log$2.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Ki(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let S=resolve(w),E=S,D=!0;try{E=realpathSync(S)}catch(e){let w=e?.code;if(w===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:S}),D=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:S,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:w??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:E,pathSeparator:sep,symlinkResolved:D},{handler:`workspace`})}let Yi=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let E=assetContentTypeForPath(S),D=extname(S).slice(1).toLowerCase();if(!E||!ASSET_EXTENSIONS.has(D)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let O=realpathSync(w),k=resolve(O,S),j;try{j=realpathSync(k)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(j,O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let F;try{F=statSync(j)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!F.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let L=toContentRelativePath(O,j);if(L!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(me?.isPathIgnored(L)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let B={"Content-Type":E,"Content-Length":String(F.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(D)?`inline`:`attachment`,"Cache-Control":`no-store`};D===`svg`&&(B[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,B);try{await pipeline(createReadStream(j),t)}catch(e){log$2.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:S,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Xi=1440*60*1e3,Zi=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!L?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),S=[],w=resolve(L.current.gitDir,`rescue`);if(existsSync(w))try{let t=readdirSync(w).filter(e=>isSupportedDocFile(e));for(let E of t){let t=resolve(w,E),D=statSync(t);if(e-D.mtimeMs>Xi){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}S.push({docName:stripDocExtension(E),timestamp:D.mtime.toISOString(),size:D.size,source:`flat`})}}catch(e){log$2.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=q?.()??`main`,t=await listRescueCheckpoints(L.current,e);for(let e of t)S.push({...e,source:`timeline`})}catch(e){log$2.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,S,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0});async function ka(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!L?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let w=resolve(L.current.gitDir,`rescue`),E=resolve(w,`${S}${getDocExtension(S)}`);if(!E.startsWith(`${w}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(E)){let e=statSync(E);if(Date.now()-e.mtimeMs>Xi)try{unlinkSync(E)}catch{}else{let e=readFileSync(E,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=q?.()??`main`,w=(await listRescueCheckpoints(L.current,e)).filter(e=>e.docName===S).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(w){let e=shadowGit(L.current),S=((await e.raw(`ls-tree`,`-r`,w.sha)).trim().split(`
|
|
2109
|
-
`)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let _s=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(ye?.delete(H),me&&me.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),ee&&(ee.updateDocumentFromMarkdown(H,L),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),xs=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(me?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),je(e),ne?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Cs=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=ze(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ts=withValidation(RenamePathRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:E,fromPath:D,toPath:O}=S;if(!isValidRelativeContentPath(D)||!isValidRelativeContentPath(O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(E===`file`&&(isSystemDoc(D)||isSystemDoc(O)||isConfigDoc(D)||isConfigDoc(O))){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||O===`.ok`||O.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(D===O){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(D.toLowerCase()===O.toLowerCase()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(E===`file`&&probeAndRegisterSourceFileExtension(w,D),me&&(E===`file`?me.isExcluded(isSupportedDocFile(O)?O:`${O}${getDocExtension(D)}`):me.isDirExcluded(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination ${E===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let k=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,j;try{j=await Lt(D,O,E,{...k?{actor:k}:{}})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(t,409,`urn:ok:error:doc-already-exists`,vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(j.renamed.length===0){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let F;switch(e.kind){case`agent`:{let t=e.summary.kind===`value`,S=t?e.summary:normalizeSummary(`Renamed ${D} → ${O}`),w=Bt(S);F=t||!w.response?w.response:Vt(w.response);for(let t=0;t<j.renamed.length;t++){let{fromDocName:S,toDocName:E}=j.renamed[t];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(S,E),e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Ht(S,!t);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`principal`:{let t=Bt(e.summary);F=t.response;for(let S=0;S<j.renamed.length;S++){let{fromDocName:w,toDocName:E}=j.renamed[S];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(w,E),e.actor,S===0?t.stored:void 0)}Ht(e.summary,!1);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:E,fromPath:D,toPath:O,affectedDocs:j.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(e.kind)}`)}if(renameAttributionCounter().add(1,{kind:`rename-${E}`,attribution_kind:e.kind}),H)try{await H()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(t,200,RenamePathSuccessSchema,{renamed:j.renamed,rewrittenDocs:j.rewrittenDocs,...F?{summary:F}:{}},{handler:`rename-path`})}catch(e){let{status:S,type:w,error:E}=Tt(e);errorResponse(t,S,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Ds=withValidation(DeletePathRequestSchema,async(e,t,S)=>{try{Rt(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let O=resolveContentEntryPath(w,e,E);if(!existsSync(O)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let k=statSync(O);if(e===`file`&&!k.isFile()||e===`folder`&&!k.isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let j=e===`file`?[E]:listAffectedDocNames(D(),e,E);if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`?unlinkSync(O):(rmSync(O,{recursive:!0,force:!1}),Me(E));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);successResponse(t,200,DeletePathSuccessSchema,{deletedDocNames:j},{handler:`delete-path`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Os=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&(E===`__system__`||E===`__config__`||E===`__user__`||E===`__local__`||E.startsWith(`__system__/`)||E.startsWith(`__config__/`)||E.startsWith(`__user__/`)||E.startsWith(`__local__/`));if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}let k=D(),j=e===`file`?k.has(E)?[E]:[]:listAffectedDocNames(k,e,E);if(j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Me(E),ne?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),ks=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(w,`${t}${D}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:D,size:E.size,modified:E.modified})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),As=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Ns(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,de??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=Rt(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$2.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(e.code!==`EEXIST`){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let Ps=`/api/local-op/clone`,Is=`/api/local-op/open`,Rs=600*1e3,$s=45e3,ec=`local-op-clone`,tc=withValidation(LocalOpCloneRequestSchema,nc,{handler:ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ec})});async function nc(e,t,S){let{url:w,dir:E}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ec,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ec,cause:Error(`dir=${E}`)});return}if(!Ce.tryAcquire(Ps)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ec,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let D=createStreamingErrorWriter(t,ec),O=null,k=runCloneSubprocess({cliArgs:ue,url:w,dir:E,timeoutMs:Rs,onEvent:e=>{if(e.type===`complete`){O=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),D(500,`urn:ok:error:clone-failed`,`Clone subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await k.done,O&&!t.writableEnded&&!t.destroyed){let e=await rc(O);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:O})}\n`):D(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?D(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$2.error({err:e,handler:ec},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ce.release(Ps)}})(),t.on(`close`,()=>{k.cancel()})}async function rc(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=ue,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$2.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let ic=`local-op-open`,ac=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:ic,cause:Error(`dir=${w}`)});return}if(!Ce.tryAcquire(Is)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:ic,extraHeaders:{"Retry-After":`5`}});return}try{let e=await rc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:ic}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:ic,cause:Error(e.error)})}finally{Ce.release(Is)}},{handler:ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ic})}),oc=`/api/local-op/auth/login`,sc=`/api/local-op/auth/status`,cc=`/api/local-op/auth/repos`,lc=`/api/local-op/auth/signout`,uc=`/api/local-op/auth/pat`,dc=`local-op-auth-login`,fc=withValidation(LocalOpAuthHostRequestSchema,pc,{handler:dc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dc})});async function pc(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:dc,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,dc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:Rs,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}}),O=()=>{D.cancel()};t.on(`close`,O),D.done.finally(()=>{t.off(`close`,O),t.writableEnded||t.end(),Ce.release(oc)})}let mc=`local-op-auth-status`,hc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(sc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:mc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2110
|
-
`).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:
|
|
2111
|
-
`);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(),Ce.release(
|
|
2112
|
-
`).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:xc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:xc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:xc,cause:e})}finally{Ce.release(uc)}},{handler:xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xc})}),Cc=`local-op-auth-identity`;async function wc(e,t){if(checkLocalOpSecurity(e,t,{handler:Cc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Cc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Cc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Cc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Cc,cause:e})}}}let Tc=`/api/local-op/auth/set-identity`,Ec=`local-op-auth-set-identity`,Dc=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:Ec});return}if(!Ce.tryAcquire(Tc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ec,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Ec})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ec,cause:e})}finally{Ce.release(Tc)}},{handler:Ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ec})});async function Oc(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},{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 kc=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 Ac(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 jc=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})}},{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 Mc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=esm_default({baseDir:de,timeout:{block:15e3}});async function E(e){try{return await w.raw([`show`,`:${e}:${S}`])}catch{return``}}try{let[e,w,D]=await Promise.all([E(1),E(2),E(3)]);successResponse(t,200,SyncConflictContentSuccessSchema,{file:S,base:e,ours:w,theirs:D},{handler:`sync-conflict-content`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Nc(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 Pc=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 Fc(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 Ic=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 Lc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Re.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 Rc(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 zc=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 Bc(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:Be(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 Vc(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 Hc=/^[A-Za-z0-9_-]+$/;function Uc(e,t,S=`template`){return!e||!Hc.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 Wc(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 Gc(e,t){if(e.method===`GET`)return Kc(e,t);if(e.method===`PUT`)return qc(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Vc(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}),qc=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Vc(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:Wc(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`});async function Jc(e,t){if(e.method===`GET`)return Zc(e,t);if(e.method===`PUT`)return Qc(e,t);if(e.method===`DELETE`)return $c(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Yc=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Xc=e=>{let t=e.match(Yc),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}},Zc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Uc(w,t,`template-get`))return;let E=Vc(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}=Xc(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}),Qc=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Uc(e,t,`template-put`))return;let w=Vc(S.folder,t,`folder`,`template-put`);if(!w)return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:Wc(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`}),$c=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Uc(w,t,`template-delete`))return;let E=Vc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E)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 nl(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 il(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 al(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function cl(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 ll(){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,...nl(e)]}function ul(){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 dl(){let e=`${w}${de??``}`,t=ul(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=ll().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 fl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{dl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}fl();async function pl(e,t){if(e.method===`GET`)return ml(e,t);if(e.method===`POST`)return hl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ml=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=al(S.searchParams.get(`intent`)),O=cl(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 dl(),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`?il(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}),hl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=al(S.intent),D=cl(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 dl(),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`?il(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`}),gl=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 _l(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 vl(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 yl=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})});async function xl(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 Cl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce.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 xl([`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{Ce.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})}),Tl=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(!Ce.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 xl([`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{Ce.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})}),El=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(!Ce.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 xl(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{Ce.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Dl={"/api/asset":Yi,"/api/document":Kt,"/api/documents":$t,"/api/backlinks":en,"/api/backlink-counts":jr,"/api/forward-links":Mr,"/api/link-graph":Fr,"/api/dead-links":zr,"/api/orphans":Ir,"/api/hubs":Lr,"/api/tags":zc,"/api/pages":ks,"/api/folder-config":Gc,"/api/template":Jc,"/api/search":pl,"/api/suggest-links":As,"/api/page-headings":Cs,"/api/create-page":_s,"/api/create-folder":xs,"/api/rename-path":Ts,"/api/delete-path":Ds,"/api/trash/cleanup":Os,"/api/upload":Ns,"/api/agent-write":Ut,"/api/agent-write-md":Wt,"/api/agent-patch":Br,"/api/agent-undo":Vr,"/api/agent-activity":Hr,"/api/agent-burst-diff":Ur,"/api/save-version":qr,"/api/history":Jr,"/api/diff":Xr,"/api/rollback":Zr,"/api/metrics/reconciliation":Qr,"/api/metrics/parse-health":ji,"/api/metrics/agent-presence":Gi,"/api/server-info":Hi,"/api/share/construct-url":yl,"/api/share/publish/owners":Cl,"/api/share/publish/name-check":Tl,"/api/share/publish":El,"/api/principal":Ui,"/api/rescue":Zi,"/api/workspace":Ki,"/api/sync/status":Oc,"/api/sync/trigger":kc,"/api/sync/conflicts":Ac,"/api/sync/conflict-content":Mc,"/api/sync/resolve-conflict":jc,"/api/sync/abort-merge":Rc,"/api/local-op/clone":tc,"/api/local-op/open":ac,"/api/local-op/auth/login":fc,"/api/local-op/auth/status":hc,"/api/local-op/auth/repos":_c,"/api/local-op/auth/signout":bc,"/api/local-op/auth/pat":Sc,"/api/local-op/auth/identity":wc,"/api/local-op/auth/set-identity":Dc,"/api/installed-agents":Lc,"/api/spawn-cursor":vl,"/api/handoff":_l,"/api/install-skill":Ic,"/api/skill/install-state":gl,"/api/seed/plan":Nc,"/api/seed/apply":Pc,"/api/seed/packs":Fc};F&&(Dl[`/api/test-reset`]=Wr,Dl[`/api/test-rescan-backlinks`]=Gr,Dl[`/api/test-rescan-files`]=Kr);let Ol=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),kl=[`/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(Ol.has(S)||kl.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`:Dl[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=Dl[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 ka(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Yr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Bc(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 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 (OK) — collaborative markdown via MCP
|
|
2113
|
-
|
|
2114
|
-
**STOP** *(when \`.ok/\` exists)* — do NOT use native \`Read\`, \`Grep\`, \`Glob\`, \`Edit\`, \`Write\` on in-scope \`.md\` / \`.mdx\`. Reads: \`exec\` / \`read_document\` / \`search\` / \`grep\`. Writes: \`write_document\` / \`edit_document\` ONLY.
|
|
2115
|
-
|
|
2116
|
-
**Preview:** open the browser at session start if not already open. On \`attach-preview-once\` in a write response, open \`previewUrl\` one-shot.
|
|
2117
|
-
|
|
2118
|
-
Content dir: ${e.dir}. Path scope: \`.gitignore\` + \`.okignore\` (gitignore syntax) at the project root or any folder depth.
|
|
2119
|
-
|
|
2120
|
-
## Reads
|
|
2121
|
-
|
|
2122
|
-
\`exec("cat <path>.md")\` / \`exec("ls <dir>")\` — primary; returns contents + enrichment. Typed \`read_document\` for one doc, \`search\` for ranked retrieval (cmd-K parity), \`grep\` for every literal-string occurrence — pick by intent.
|
|
2123
|
-
|
|
2124
|
-
## Preview — open at session start
|
|
2125
|
-
|
|
2126
|
-
Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-URL tool or \`open <url>\`. If a write response lacks the \`attach-preview-once\` warning, a browser is attached — do nothing. Server not running: \`open-knowledge ui\`.
|
|
2127
|
-
|
|
2128
|
-
## Full guidance
|
|
2129
|
-
|
|
2130
|
-
Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
|
|
2131
|
-
|
|
2132
|
-
**Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.ok/\`, when no OK MCP is registered, or right after a failed OK MCP call (then prefix with \`Open Knowledge MCP unavailable:\`). Non-markdown: native tools always.
|
|
2133
|
-
`}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(`
|
|
2107
|
+
`)}let Re=createInstalledAgentsProbe({probe:ge??createOsProbe(process.platform)});function ze(e){if(!isSafeDocName(e))return null;let t=resolve(w),S=resolve(t,`${e}${getDocExtension(e)}`);return!S.startsWith(`${t}/`)&&S!==t?null:S}function Be(e){let t=ze(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Ve(e,t){return t.has(e)?Be(e):e}let Ue={cluster:void 0,category:void 0,tags:void 0};function We(e){try{let S=t.documents.get(e);if(S){let e=readFmMap(S.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,S=typeof e.category==`string`?e.category:void 0,w;return Array.isArray(e.tags)?w=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(w=[e.tags]),{cluster:t,category:S,tags:w}}}}catch{}try{let t=ze(e);if(!t||!existsSync(t))return Ue;let{frontmatter:S}=stripFrontmatter(readFileSync(t,`utf-8`));return S?parseFrontmatterMetadata(S):Ue}catch{return Ue}}function Ge(e,t){return t.has(e)?We(e):Ue}function Ke(e){if(ee)try{if(ee.getBacklinks(e).length>0)return;let t=performance.now(),S=findHubCandidates(e,D()),w=performance.now()-t;return w>5&&log$2.debug({docName:e,elapsedMs:w,candidateCount:S.length},`[orphan-hint] findHubCandidates slow`),S.length===0?void 0:[{type:`orphan`,parentCandidates:S,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${S.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function Xe(e){return k?.().get(e)??e}function $e(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function nt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function rt(e,S){let w=`onStoreDocument-${e}`;(t.debouncer.isDebounced(w)?t.debouncer.executeNow(w):Promise.resolve()).then(()=>B?.()).catch(e=>{log$2.warn({err:e},`[${S}] post-write flush failed`)})}function it(){let e=new Set;for(let[t,S]of D()){e.add(t);for(let t of S.aliases)e.add(t)}return e}function at(){let e=Promise.resolve();return async function(t){let S=e,w=()=>{};e=new Promise(e=>{w=e}),await S;try{return await t()}finally{w()}}}let st=at(),vt=e=>e.endsWith(`.`)?e:`${e}.`;function Tt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:vt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError?{status:400,type:`urn:ok:error:invalid-request`,error:vt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:vt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:vt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Et(e){let w=new Map;for(let S of e){let e=t.documents.get(S);e&&w.set(S,e.getText(`source`).toString())}for(let t of e)await S.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let S of e){let e=t.documents.get(S);deleteReconciledBase(S),e&&(t.closeConnections(S),await(_e??t.unloadDocument.bind(t))(e))}return w}function Dt(e,t){for(let{fromDocName:S,toDocName:E}of e){let e=safeContentPath(E,w),D=t.get(S);typeof D==`string`&&tracedWriteFileSync(e,D,`utf-8`);let O=typeof D==`string`?D:existsSync(e)?readFileSync(e,`utf-8`):null;typeof O==`string`&®isterWrite(e,contentHash(O))}}function jt(e,t){return e.map(e=>{let S=t.get(e);if(typeof S==`string`)return{docName:e,content:S};let E=safeContentPath(e,w);if(!existsSync(E))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(E,`utf-8`)}})}function Mt(e){let S=t.documents.get(e);if(S)return S.getText(`source`).toString();let E=resolveContentEntryPath(w,`file`,e);return existsSync(E)?readFileSync(E,`utf-8`):null}function Ft(e,t){let S=resolveContentEntryPath(w,`file`,e);tracedMkdirSync(dirname(S),{recursive:!0}),tracedWriteFileSync(S,t,`utf-8`),registerWrite(S,contentHash(t)),setReconciledBase(e,t);let E=D();E instanceof Map&&updateFileIndex({kind:`update`,path:S,docName:e,content:t},E)}function It(e,S){let w=t.documents.get(e);if(!w)throw Error(`Document is not loaded: ${e}`);let E={markdown:``,rewrites:0};return w.transact(()=>{E=applyRenameMap(w.getText(`source`).toString(),e,S),E.rewrites!==0&&composeAndWriteRawBody(w,E.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),E}async function Lt(e,S,E,O){return st(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":E}},async k=>{if(!ee)throw new BacklinkIndexRequiredError;let j=resolveContentEntryPath(w,E,e),F=resolveContentEntryPath(w,E,S);if(j===F)return{renamed:[],rewrittenDocs:[]};if(!existsSync(j))throw new ManagedRenameSourceNotFoundError(E);if(existsSync(F))throw new ManagedRenameDestinationExistsError;let B=statSync(j);if(E===`file`&&!B.isFile()||E===`folder`&&!B.isDirectory())throw new ManagedRenameSourceTypeMismatchError(E);let H=(E===`file`?[stripDocExtension(e)]:listAffectedDocNames(D(),E,e)).map(t=>({from:t,to:E===`file`?stripDocExtension(S):remapDocNameForRename(t,E,e,S)}));if(k.setAttribute(`rename.affected_docs`,H.length),H.length===0)return E===`folder`&&(await renameTrackedPathInGit(de,j,F)||(tracedMkdirSync(dirname(F),{recursive:!0}),tracedRenameSync(j,F)),Pe(e,S),ne?.(`files`)),{renamed:[],rewrittenDocs:[]};let J=buildRenameMap(H),Y=H.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),te=new Set;for(let{from:e}of H)for(let t of ee.getBacklinks(e))J.has(t.source)||te.add(t.source);let ae=[...te].sort((e,t)=>e.localeCompare(t)),oe=new Map,se=[],ce=[];for(let e of[...J.keys(),...ae]){if(oe.has(e))continue;if(!J.has(e)&&!existsSync(resolveContentEntryPath(w,`file`,e))){ce.push(e);continue}let t=Mt(e);typeof t==`string`?(oe.set(e,t),J.has(e)||se.push(e)):J.has(e)||ce.push(e)}for(let{from:e}of H)if(typeof oe.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:S,affectedDocs:[...H],snapshots:jt([...oe.keys()],oe)}),fe=[];return await withManagedRenameRecovery(de??w,ue,async()=>{for(let e of ce)ee.deleteDocument(e);for(let e of se){let S=t.documents.get(e)?It(e,J):applyRenameMap(oe.get(e)??``,e,J);S.rewrites>0&&(Ft(e,S.markdown),fe.push({docName:e,rewrites:S.rewrites})),ee.updateDocumentFromMarkdown(e,S.markdown)}if(ye)for(let{from:e,to:t}of H)isSystemDoc(e)||isConfigDoc(e)||(ye.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let k=resolveContentEntryPath(w,E,e),j=resolveContentEntryPath(w,E,S);await renameTrackedPathInGit(de,k,j)||(tracedMkdirSync(dirname(j),{recursive:!0}),tracedRenameSync(k,j)),E===`folder`&&Pe(e,S);let F=await Et([...J.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(L?.current){let e=L.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":E}},t=>{let S=randomUUID(),w=new Date().toISOString(),D=q?.()??`main`,k=getOrLoadRenameLogIndex(e.gitDir),j=O?.actor?{writerId:O.actor.writerId,displayName:O.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},F=0;for(let{from:t,to:L}of H){let B={v:1,from:t,to:L,at:w,commitSha:``,branch:D,groupId:S,kind:E,actor:j};appendRenameLogEntry(e.gitDir,B,k,e),F+=1,O?.actor?recordContributor(L,O.actor.writerId,O.actor.displayName,O.actor.colorSeed,formatRenameSubject(t,L),O.actor.actorMetadata,void 0,[{from:t,to:L}]):recordContributor(L,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,L),void 0,void 0,[{from:t,to:L}])}t.setAttribute(`rename.entries_appended`,F)})}let B=E===`file`&&isSupportedDocFile(S)?extname(S):null;for(let{from:e,to:t}of H){let S=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,B??S)}let Y=[...H].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of Y){let S=resolveContentEntryPath(w,`file`,e),E=resolveContentEntryPath(w,`file`,t),O=applyRenameMap(F.get(e)??oe.get(e)??readFileSync(E,`utf-8`),e,J);Dt([{fromDocName:e,toDocName:t}],new Map([[e,O.markdown]])),setReconciledBase(t,O.markdown);let k=D();k instanceof Map&&updateFileIndex({kind:`rename`,oldPath:S,newPath:E,oldDocName:e,newDocName:t,content:O.markdown},k),ee.renameDocument(e,t,O.markdown),O.rewrites>0&&fe.push({docName:t,rewrites:O.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ee.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ne?.(`files`),ne?.(`backlinks`),ne?.(`graph`),fe.sort((e,t)=>e.docName.localeCompare(t.docName)),k.setAttribute(`rename.rewrite_count`,fe.length),{renamed:Y,rewrittenDocs:fe}}))}function Rt(e){let t=parseAgentBodyFields(e),S=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:S,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??S,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function zt(e){return{principalId:fe?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Bt(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function Vt(e){return{value:e.value}}function Ht(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}let Ut=withValidation(AgentWriteRequestSchema,async(t,w,E)=>{try{let t=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:D,agentName:O,colorSeed:k,clientName:j,clientVersion:F,label:L}=Rt(E);if(isSystemDoc(t)||isConfigDoc(t)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-write`});return}let B=normalizeSummary(E.summary),H=await S.getSession(t,D,{displayName:O,colorSeed:k,clientName:j}),q=new Date().toISOString(),J=typeof E.content==`string`?E.content:`Hello from the agent! ${q}`,{response:Y,stored:ee}=Bt(B);try{let S=iconFromClientName(j),w=AGENT_ICON_COLORS[S]??colorFromSeed(k??D);oe?.setPresence(D,{displayName:O,icon:S,color:w,currentDoc:t,mode:`writing`,ts:Date.now()}),captureEffect(H.dc.document.getText(`source`),D,k,j),H.dc.document.transact(()=>{applyAgentMarkdownWrite(H.dc.document,`${J}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:t}:void 0),H.dc.document.getMap(`agent-flash`).set(D,{agentId:D,timestamp:Date.now(),type:`insert`,description:`Added (${O}): ${J.slice(0,50)}`})},H.origin),recordContributor(t,D,O,k,void 0,zt({clientName:j,clientVersion:F,label:L}),ee),incrementAgentWriteCalls(),Ht(B)}finally{oe?.touchMode(D,`idle`)}rt(t,`agent-write`),se?.(),successResponse(w,200,AgentWriteSuccessSchema,{timestamp:q,...Y?{summary:Y}:{}},{handler:`agent-write`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Wt=withValidation(AgentWriteMdRequestSchema,async(t,w,E)=>{try{let t=E.position??`append`,D=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Rt(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write-md`});return}let H=normalizeSummary(E.summary),{response:q,stored:J}=Bt(H),Y=await S.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=new Date().toISOString();try{let S=iconFromClientName(F),w=AGENT_ICON_COLORS[S]??colorFromSeed(j??O);oe?.setPresence(O,{displayName:k,icon:S,color:w,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),O,j,F),Y.dc.document.transact(()=>{applyAgentMarkdownWrite(Y.dc.document,E.markdown,t,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),Y.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),recordContributor(D,O,k,j,void 0,zt({clientName:F,clientVersion:L,label:B}),J),incrementAgentWriteCalls(),Ht(H)}finally{oe?.touchMode(O,`idle`)}rt(D,`agent-write-md`),ae?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),se?.();let te=Ke(D),ne=$e(D),ce=nt();ce===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)}),successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ee,subscriberCount:ne,systemSubscriberCount:ce,...te?{hints:te}:{},...q?{summary:q}:{}},{handler:`agent-write-md`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Kt=withValidation(FrontmatterPatchRequestSchema,async(e,t,w)=>{try{let e=Xe(w.docName!==void 0&&w.docName.length>0?w.docName:`test-doc`),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Rt(w);if(isSystemDoc(e)||isConfigDoc(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${e}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let L=w.patch??{},B=Object.keys(L),H=normalizeSummary(w.summary),{response:q,stored:J}=Bt(H),Y=await S.getSession(e,E,{displayName:D,colorSeed:O,clientName:k}),ee=new Date().toISOString(),te,ne=!1,ce=[];try{let t=iconFromClientName(k),S=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);oe?.setPresence(E,{displayName:D,icon:t,color:S,currentDoc:e,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":e,"frontmatter_patch.keys":B.length}},()=>{Y.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(Y.dc.document.getText(`source`).toString()),S=applyPatchToFm(e,L);if(!S.ok){te=S.error;return}for(let e of Object.keys(L))ce.push(e);if(S.nextFenced!==e){let e=S.nextFenced+t;composeAndWriteRawBody(Y.dc.document,e,`agent`),recordFrontmatterEditSurface(`mcp-write`)}ne=!0},Y.origin)})}finally{oe?.touchMode(E,`idle`)}if(te){let e;switch(te.kind){case`invalid_value`:e={[te.key]:te.reason};break;case`reserved_key`:e={[te.key]:`'${te.key}' is reserved`};break;case`unknown_key`:e={[te.key]:`'${te.key}' is not a recognized key`};break;case`duplicate_target`:e={[te.key]:`'${te.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${te.expected.join(`, `)}; got: ${te.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${te.bytes} > ${te.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${te.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(te)})`}}errorResponse(t,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}ne&&ce.length>0&&(recordContributor(e,E,D,O,void 0,zt({clientName:k,clientVersion:j,label:F}),J),incrementAgentWriteCalls(),Ht(H),rt(e,`frontmatter-patch`)),ae?.setFocus(E,{agentName:D,currentDoc:e,writeKind:`write`,ts:Date.now()}),se?.();let ue=$e(e),de=nt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(k)}),successResponse(t,200,FrontmatterPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,appliedKeys:ce,...q?{summary:q}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(t,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`}),$t=withValidation(EmptyRequestSchema,async(e,S)=>{try{let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(E)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let D=Xe(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`document-read`});return}let O=t.documents.get(D);if(O){successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:O.getText(`source`).toString()},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(w,`file`,D))){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document not found: ${D}.`,{handler:`document-read`});return}let k=await t.openDirectConnection(D);try{let e=k.document;if(!e){errorResponse(S,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:e.getText(`source`).toString()},{handler:`document-read`})}finally{await k.disconnect()}}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),en=withValidation(EmptyRequestSchema,async(e,t)=>{try{ve&&await ve.catch(e=>{log$2.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=S.searchParams.get(`dir`),k=S.searchParams.get(`showAll`)===`true`;if(E)try{safeSubdir(w,E)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(k&&me){let e=[];try{await walkContentDirForShowAll({contentDir:w,contentFilter:me,dirFilter:E,documents:e,getDocExtension}),e.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:e},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}return}let j=D(),F=O?.()??new Map,L=[];for(let[e,t]of F)E&&!e.startsWith(`${E}/`)&&e!==E||L.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of j){if(E&&!e.startsWith(`${E}/`)&&e!==E)continue;let S=getDocExtension(e);L.push({kind:`document`,docName:e,docExt:S,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let D of t.aliases){if(E&&!D.startsWith(`${E}/`)&&D!==E)continue;let O=relative(w,t.canonicalPath);L.push({kind:`document`,docName:D,docExt:S,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:O})}}let B=[];try{let e=Ie(j);we?.signature!==e&&(we={signature:e,assets:collectReferencedAssets({contentDir:w,fileIndex:j,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:me?e=>me.isPathIgnored(e):void 0})}),B=we?.assets??[]}catch(e){we=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of B)E&&!e.path.startsWith(`${E}/`)&&e.path!==E||L.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});L.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:L},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),jr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:S,backlinks:ee.getBacklinks(S).map(e=>({source:e.source,anchor:e.anchor,title:Be(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Mr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let w={};for(let e of S.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(w[t]=ee.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:w},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Fr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let w=it();successResponse(t,200,ForwardLinksSuccessSchema,{docName:S,forwardLinks:ee.getForwardLinkEntries(S).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ve(e.target,w),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Ir=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`docName`);if(w&&!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let E=S.searchParams.get(`degrees`);if(E&&!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let D,O;if(E&&w){let e=Number.parseInt(E,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:D,links:O}=ee.getLinkGraphNeighborhood(w,e))}else ({nodes:D,links:O}=ee.getLinkGraph());let k=it();successResponse(t,200,LinkGraphSuccessSchema,{nodes:D.map(e=>{if(e.kind===`doc`){let t=Ge(e.docName,k);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ve(e.docName,k),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:O},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Lr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ee.getOrphans([...D().keys()],S).map(e=>({docName:e,title:Be(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),zr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),w=S?Number.parseInt(S,10):20,E=Number.isFinite(w)&&w>0?w:20,D=it();successResponse(t,200,HubsSuccessSchema,{hubs:ee.getHubs(E).map(e=>({docName:e.docName,title:Ve(e.docName,D),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Br=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(S.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let w=S.length?[...new Set(S.map(e=>Xe(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ee.getDeadLinks(it(),w).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Be(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Vr=withValidation(AgentPatchRequestSchema,async(t,w,E)=>{try{let{find:t,replace:D,offset:O}=E,k=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:j,agentName:F,colorSeed:L,clientName:B,clientVersion:H,label:q}=Rt(E);if(findLooksLikeFrontmatter(t)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await S.getSession(k,j,{displayName:F,colorSeed:L,clientName:B}),ee=new Date().toISOString(),te=!1,ne=!1,ce=!1;try{let S=iconFromClientName(B),w=AGENT_ICON_COLORS[S]??colorFromSeed(L??j);if(oe?.setPresence(j,{displayName:F,icon:S,color:w,currentDoc:k,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),j,L,B),Y.dc.document.transact(()=>{let{frontmatter:S,body:w}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),E=prependFrontmatter(S,w),L=O==null?E.indexOf(t):E.slice(O,O+t.length)===t?O:-1;if(L===-1){O==null?te=!0:ne=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":k,findLength:t.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(L<S.length){ce=!0;return}let{body:B}=stripFrontmatter(E.slice(0,L)+D+E.slice(L+t.length));applyAgentMarkdownWrite(Y.dc.document,B,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0),Y.dc.document.getMap(`agent-flash`).set(j,{agentId:j,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${t.slice(0,50)}`})},Y.origin),!te&&!ne&&!ce){let{stored:e}=Bt(J);recordContributor(k,j,F,L,void 0,zt({clientName:B,clientVersion:H,label:q}),e),incrementAgentWriteCalls(),Ht(J)}}finally{oe?.touchMode(j,`idle`)}if(ne){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(te){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ce){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}rt(k,`agent-patch`),ae?.setFocus(j,{agentName:F,currentDoc:k,writeKind:`edit`,ts:Date.now()}),se?.();let ue=$e(k),de=nt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(B)});let{response:fe}=Bt(J);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,...fe?{summary:fe}:{}},{handler:`agent-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Hr=withValidation(AgentUndoRequestSchema,async(t,w,E)=>{try{let{agentId:t,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Rt(E),L=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`);if(isSystemDoc(L)||isConfigDoc(L)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${L}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:B}=E,H=E.scope===`session`||E.scope===`file`?`session`:`last`;if(!S.hasSession(L,B)){errorResponse(w,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let q=await S.getSession(L,B),J=!1;try{let S=iconFromClientName(k),w=AGENT_ICON_COLORS[S]??colorFromSeed(O??t);oe?.setPresence(t,{displayName:D,icon:S,color:w,currentDoc:L,mode:`writing`,ts:Date.now()}),J=applyAgentUndo(q,H,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:L}:void 0),J&&recordContributor(L,B,D,O,void 0,zt({clientName:k,clientVersion:j,label:F}))}finally{oe?.touchMode(t,`idle`)}J&&rt(L,`agent-undo`),ae?.setFocus(B,{agentName:B,currentDoc:L,writeKind:`undo`,ts:Date.now()}),successResponse(w,200,AgentUndoSuccessSchema,{docName:L,scope:H,undone:J},{handler:`agent-undo`})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Ur=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(S,w),{handler:`agent-activity`})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Wr=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=validateAgentId(w.searchParams.get(`agentId`)),D=w.searchParams.get(`docName`),O=w.searchParams.get(`stackIndex`);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!D||D.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let k=Xe(D);if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!O||Number.isNaN(Number(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let j=Number(O);if(!Number.isInteger(j)||j<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let F=S.getLiveSession(k,E);if(!F){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let L=F.um;if(j>=L.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${j} out of range (stack has ${L.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let B=L.undoStack[j];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(B,F.dc.document.getText(`source`),k),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Gr=withValidation(EmptyRequestSchema,async(e,E)=>{try{let D=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),O=Xe(D.searchParams.get(`docName`)??`test-doc`),k;try{k=safeContentPath(O,w)}catch(e){log$2.error({err:e,docName:O},`[test-reset] safeContentPath rejected docName`),errorResponse(E,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await S.closeAll(O),t.closeConnections(O);let j=`onStoreDocument-${O}`;t.debouncer.isDebounced(j)&&await t.debouncer.executeNow(j);let F=t.documents.get(O);if(F&&await(_e??t.unloadDocument.bind(t))(F),writeFileSync(k,``,`utf-8`),ee&&(ee.deleteDocument(O),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${O}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),D.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(w,`.okignore`),S=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(S){let e=S.getText(`source`);e.length>0&&S.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),me&&await me.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}ne?.(`files`),successResponse(E,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Kr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ee.rebuildFromDisk(),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),ne?.(`backlinks`),ne?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),qr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!j){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}j(),ne?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Jr=withValidation(SaveVersionRequestSchema,async(e,t,S)=>{try{let{rawAgentId:e,agentId:w,agentName:E,clientName:D}=Rt(S),O=L?.current;if(!O){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let k=/^[a-zA-Z0-9_-]+$/,j=[],F,B,H;if(typeof S.message==`string`&&S.message.trim()&&(F=S.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(S.writers))try{j=S.writers.map(e=>{let t=e.id??`unknown`;if(!k.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}S.principal&&(typeof S.principal.name==`string`&&S.principal.name.trim()&&(B=sanitizeGitIdentity(S.principal.name.trim())),typeof S.principal.email==`string`&&S.principal.email.trim()&&(H=sanitizeGitIdentity(S.principal.email.trim()))),j.length===0&&(j=e===void 0?[SERVICE_WRITER]:[{id:w,name:D?`${E} (${D})`:E,email:`${w}@openknowledge.local`}]);let q=Y??`.`,J=await saveVersion(O,q,j);console.log(`[history] checkpoint ${J.checkpointRef}`);try{await gcRenameLog(O,getOrLoadRenameLogIndex(O.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}let ee=swapContributors(),te;if(de){let e=!1;try{await esm_default({baseDir:de,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{te=await withParentLock(async()=>{let e=esm_default({baseDir:de,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,S=`ok/v${t}`,w=`openknowledge`,E=`noreply@openknowledge.local`;if(B&&H)w=B,E=H;else try{let e=await resolveGitIdentity(de);e&&(w=e.name,E=e.email)}catch{}let D=[];for(let e of ee.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;D.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let O=formatCheckpointSubject(F??`Checkpoint v${t}`),k=D.length>0?`${O}\n\n${D.join(`
|
|
2108
|
+
`)}`:O,j=q||`.`;return await e.add(j),await e.env({GIT_AUTHOR_NAME:w,GIT_AUTHOR_EMAIL:E,GIT_COMMITTER_NAME:w,GIT_COMMITTER_EMAIL:E}).commit(k,[`--allow-empty`]),await e.addTag(S),console.log(`[checkpoint] parent-git commit + tag ${S}`),S})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:J.checkpointRef,...te?{versionTag:te}:{}},{handler:`save-version`})}catch(e){log$2.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),Yr=withValidation(EmptyRequestSchema,async(e,t)=>{let S=L?.current;if(!S){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`docName`)??``,D=w.searchParams.get(`branch`)??q?.()??`main`;if(!E){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName query parameter is required.`,{handler:`history`});return}if(D.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}let O=Y??`.`,k=safeDocPath(E,O);if(`error`in k){errorResponse(t,400,`urn:ok:error:invalid-request`,k.error,{handler:`history`});return}let j=Number(w.searchParams.get(`limit`)??`50`),F=Number(w.searchParams.get(`offset`)??`0`),B=Math.min(200,Number.isFinite(j)?j:50),H=Number.isFinite(F)?F:0,J=w.searchParams.get(`type`)??void 0,ee=w.searchParams.get(`author`)??void 0,te=w.searchParams.get(`excludeAuthor`)??void 0,ne=Date.now();try{let e=await getDocumentHistory(S,{docName:E,branch:D,limit:B,offset:H,type:J,author:ee,excludeAuthor:te},O),w=Date.now()-ne;console.log(`[timeline] query docName=${E} entries=${e.entries.length} duration=${w}ms`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Xr(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let w=L?.current;if(!w){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,D=Y??`.`,O=safeDocPath(E,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history-version`});return}let k=shadowGit(w),j=q?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(w,E,S,j,getOrLoadRenameLogIndex(w.gitDir),e=>{let t=safeDocPath(e,D);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let O=await k.raw(`show`,`${S}:${e}`),[F=``,L=``]=(await k.raw(`log`,`-1`,`--format=%aI%x00%an`,S)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:S,content:O,timestamp:F,author:L},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let Zr=withValidation(EmptyRequestSchema,async(e,S)=>{let w=L?.current;if(!w){errorResponse(S,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),D=E.searchParams.get(`docName`)??``,O=E.searchParams.get(`from`)??``,k=E.searchParams.get(`to`)??``;if(!k||!/^[0-9a-f]{40}$/i.test(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let j=Y??`.`,F=safeDocPath(D,j);if(`error`in F){errorResponse(S,400,`urn:ok:error:invalid-request`,F.error,{handler:`diff`});return}let B=shadowGit(w),H=q?.()??`main`,J=getOrLoadRenameLogIndex(w.gitDir),ee=createAncestorShaSetCache(),te=e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(w,D,k,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let E=await B.raw(`show`,`${k}:${e}`),j;if(O&&/^[0-9a-f]{40}$/i.test(O)){let e=await resolveDocPathAtCommit(w,D,O,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}j=await B.raw(`show`,`${O}:${e}`)}else{let e=t.documents.get(D);if(!e){errorResponse(S,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}j=e.getText(`source`).toString()}let F=stripFrontmatter(j).body,L=stripFrontmatter(E).body,q=diffLines(F,L),Y=[],ne=0,ae=0;for(let e of q){let t=e.value.replace(/\n$/,``).split(`
|
|
2109
|
+
`),S=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:S,text:e});e.added&&(ne+=t.length),e.removed&&(ae+=t.length)}successResponse(S,200,DiffSuccessSchema,{lines:Y,additions:ne,deletions:ae},{handler:`diff`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Qr=withValidation(RollbackRequestSchema,async(S,w,E)=>{let D=extractActorIdentity(E,fe);if(D.kind===`invalid-summary`){errorResponse(w,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let O=L?.current;if(!O){errorResponse(w,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:k,commitSha:j,versionTag:F}=E,B=Y??`.`,H=safeDocPath(k,B);if(`error`in H){errorResponse(w,400,`urn:ok:error:invalid-request`,H.error,{handler:`rollback`});return}let J=shadowGit(O),ee=Date.now();try{let S=getOrLoadRenameLogIndex(O.gitDir),E=createAncestorShaSetCache(),L=await resolveDocPathAtCommit(O,k,j,q?.()??`main`,S,e=>{let t=safeDocPath(e,B);return`error`in t?`${e}.md`:t.path},E);if(L===null){errorResponse(w,404,`urn:ok:error:doc-not-found`,`Commit ${j.slice(0,7)} does not contain document ${k} at any known historical path.`,{handler:`rollback`});return}let H=await J.raw(`show`,`${j}:${L}`),te=new Date().toISOString();await safetyCheckpoint(O,B,{action:`rollback`,context:{docName:k,targetSha:j}});let ne=t.documents.get(k);if(!ne){errorResponse(w,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let oe=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0;ne.transact(()=>{replaceRawBody(ne,H,oe)},ROLLBACK_ORIGIN);let se;switch(D.kind){case`agent`:{let e=j.slice(0,8),t=D.summary.kind===`value`,S=t?D.summary:normalizeSummary(`Restored to ${e}`),w=Bt(S);se=t||!w.response?w.response:Vt(w.response),recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,w.stored),incrementAgentWriteCalls(),Ht(S,!t);break}case`principal`:{let e=Bt(D.summary);se=e.response,recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,e.stored),Ht(D.summary,!1);break}case`anonymous`:log$2.debug({docName:k,commitSha:j.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(D.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:D.kind}),rt(k,`rollback`);let ce=Date.now()-ee;if(console.log(`[rollback] docName=${k} from=${j.slice(0,8)} duration=${ce}ms`),de){let e=`Restored to ${F??j.slice(0,8)}: ${k}`,t=Y??`.`;withParentLock(async()=>{let S=esm_default({baseDir:de,timeout:{block:15e3}}),w=t||`.`;await S.add(w),await S.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}D.kind===`agent`&&ae?.setFocus(D.writerId,{agentName:D.displayName,currentDoc:k,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(w,200,RollbackSuccessSchema,{restoredFrom:j,timestamp:te,...se?{summary:se}:{}},{handler:`rollback`})}catch(e){errorResponse(w,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ji=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$2.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),Hi=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$2.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Ui=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=getActiveBranch(),S=J?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:E,currentBranch:e,...S===void 0?{}:{currentDiskAckSVs:S}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function Gi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let S=fe?.()??null;if(!S){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,S,{handler:`principal`})}async function Ki(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=oe?.getPresenceMap()??{},S=Date.now(),w={};for(let[t,E]of Object.entries(e))S-E.ts<2e4&&(w[t]=E);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:w},{handler:`metrics-agent-presence`})}catch(e){log$2.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Yi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let S=resolve(w),E=S,D=!0;try{E=realpathSync(S)}catch(e){let w=e?.code;if(w===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:S}),D=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:S,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:w??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:E,pathSeparator:sep,symlinkResolved:D},{handler:`workspace`})}let Xi=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let E=assetContentTypeForPath(S),D=extname(S).slice(1).toLowerCase();if(!E||!ASSET_EXTENSIONS.has(D)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let O=realpathSync(w),k=resolve(O,S),j;try{j=realpathSync(k)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(j,O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let F;try{F=statSync(j)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!F.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let L=toContentRelativePath(O,j);if(L!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(me?.isPathIgnored(L)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let B={"Content-Type":E,"Content-Length":String(F.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(D)?`inline`:`attachment`,"Cache-Control":`no-store`};D===`svg`&&(B[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,B);try{await pipeline(createReadStream(j),t)}catch(e){log$2.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:S,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Zi=1440*60*1e3,ka=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!L?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),S=[],w=resolve(L.current.gitDir,`rescue`);if(existsSync(w))try{let t=readdirSync(w).filter(e=>isSupportedDocFile(e));for(let E of t){let t=resolve(w,E),D=statSync(t);if(e-D.mtimeMs>Zi){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}S.push({docName:stripDocExtension(E),timestamp:D.mtime.toISOString(),size:D.size,source:`flat`})}}catch(e){log$2.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=q?.()??`main`,t=await listRescueCheckpoints(L.current,e);for(let e of t)S.push({...e,source:`timeline`})}catch(e){log$2.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,S,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0});async function _s(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!L?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let w=resolve(L.current.gitDir,`rescue`),E=resolve(w,`${S}${getDocExtension(S)}`);if(!E.startsWith(`${w}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(E)){let e=statSync(E);if(Date.now()-e.mtimeMs>Zi)try{unlinkSync(E)}catch{}else{let e=readFileSync(E,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=q?.()??`main`,w=(await listRescueCheckpoints(L.current,e)).filter(e=>e.docName===S).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(w){let e=shadowGit(L.current),S=((await e.raw(`ls-tree`,`-r`,w.sha)).trim().split(`
|
|
2110
|
+
`)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let xs=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(ye?.delete(H),me&&me.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),ee&&(ee.updateDocumentFromMarkdown(H,L),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Cs=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(me?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),je(e),ne?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Ts=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=ze(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ds=withValidation(RenamePathRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:E,fromPath:D,toPath:O}=S;if(!isValidRelativeContentPath(D)||!isValidRelativeContentPath(O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(E===`file`&&(isSystemDoc(D)||isSystemDoc(O)||isConfigDoc(D)||isConfigDoc(O))){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||O===`.ok`||O.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(D===O){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(D.toLowerCase()===O.toLowerCase()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(E===`file`&&probeAndRegisterSourceFileExtension(w,D),me&&(E===`file`?me.isExcluded(isSupportedDocFile(O)?O:`${O}${getDocExtension(D)}`):me.isDirExcluded(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination ${E===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let k=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,j;try{j=await Lt(D,O,E,{...k?{actor:k}:{}})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(t,409,`urn:ok:error:doc-already-exists`,vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(j.renamed.length===0){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let F;switch(e.kind){case`agent`:{let t=e.summary.kind===`value`,S=t?e.summary:normalizeSummary(`Renamed ${D} → ${O}`),w=Bt(S);F=t||!w.response?w.response:Vt(w.response);for(let t=0;t<j.renamed.length;t++){let{fromDocName:S,toDocName:E}=j.renamed[t];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(S,E),e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Ht(S,!t);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`principal`:{let t=Bt(e.summary);F=t.response;for(let S=0;S<j.renamed.length;S++){let{fromDocName:w,toDocName:E}=j.renamed[S];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(w,E),e.actor,S===0?t.stored:void 0)}Ht(e.summary,!1);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:E,fromPath:D,toPath:O,affectedDocs:j.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(e.kind)}`)}if(renameAttributionCounter().add(1,{kind:`rename-${E}`,attribution_kind:e.kind}),H)try{await H()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(t,200,RenamePathSuccessSchema,{renamed:j.renamed,rewrittenDocs:j.rewrittenDocs,...F?{summary:F}:{}},{handler:`rename-path`})}catch(e){let{status:S,type:w,error:E}=Tt(e);errorResponse(t,S,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Os=withValidation(DeletePathRequestSchema,async(e,t,S)=>{try{Rt(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let O=resolveContentEntryPath(w,e,E);if(!existsSync(O)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let k=statSync(O);if(e===`file`&&!k.isFile()||e===`folder`&&!k.isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let j=e===`file`?[E]:listAffectedDocNames(D(),e,E);if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`?unlinkSync(O):(rmSync(O,{recursive:!0,force:!1}),Me(E));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);successResponse(t,200,DeletePathSuccessSchema,{deletedDocNames:j},{handler:`delete-path`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),ks=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&(E===`__system__`||E===`__config__`||E===`__user__`||E===`__local__`||E.startsWith(`__system__/`)||E.startsWith(`__config__/`)||E.startsWith(`__user__/`)||E.startsWith(`__local__/`));if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}let k=D(),j=e===`file`?k.has(E)?[E]:[]:listAffectedDocNames(k,e,E);if(j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Me(E),ne?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),As=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(w,`${t}${D}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:D,size:E.size,modified:E.modified})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Ns=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Ps(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,de??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=Rt(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$2.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(e.code!==`EEXIST`){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let Is=`/api/local-op/clone`,Rs=`/api/local-op/open`,$s=600*1e3,ec=45e3,tc=`local-op-clone`,nc=withValidation(LocalOpCloneRequestSchema,rc,{handler:tc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:tc})});async function rc(e,t,S){let{url:w,dir:E}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:tc,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:tc,cause:Error(`dir=${E}`)});return}if(!Ce.tryAcquire(Is)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:tc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let D=createStreamingErrorWriter(t,tc),O=null,k=runCloneSubprocess({cliArgs:ue,url:w,dir:E,timeoutMs:$s,onEvent:e=>{if(e.type===`complete`){O=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),D(500,`urn:ok:error:clone-failed`,`Clone subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await k.done,O&&!t.writableEnded&&!t.destroyed){let e=await ic(O);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:O})}\n`):D(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?D(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$2.error({err:e,handler:tc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ce.release(Is)}})(),t.on(`close`,()=>{k.cancel()})}async function ic(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=ue,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$2.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let ac=`local-op-open`,oc=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:ac,cause:Error(`dir=${w}`)});return}if(!Ce.tryAcquire(Rs)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:ac,extraHeaders:{"Retry-After":`5`}});return}try{let e=await ic(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:ac}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:ac,cause:Error(e.error)})}finally{Ce.release(Rs)}},{handler:ac,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ac})}),sc=`/api/local-op/auth/login`,cc=`/api/local-op/auth/status`,lc=`/api/local-op/auth/repos`,uc=`/api/local-op/auth/signout`,dc=`/api/local-op/auth/pat`,fc=`local-op-auth-login`,pc=withValidation(LocalOpAuthHostRequestSchema,mc,{handler:fc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:fc})});async function mc(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(sc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:fc,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,fc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:$s,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}}),O=()=>{D.cancel()};t.on(`close`,O),D.done.finally(()=>{t.off(`close`,O),t.writableEnded||t.end(),Ce.release(sc)})}let hc=`local-op-auth-status`,gc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(cc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:hc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2111
|
+
`).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:hc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:hc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:hc,cause:e})}finally{Ce.release(cc)}},{handler:hc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:hc})}),_c=`local-op-auth-repos`,vc=withValidation(LocalOpAuthHostRequestSchema,yc,{handler:_c,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_c})});async function yc(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(lc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:_c,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,_c),[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`)},$s);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
|
|
2112
|
+
`);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(),Ce.release(lc))}),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()),Ce.release(lc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),Ce.release(lc))})}let bc=`local-op-auth-signout`,xc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(uc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:bc,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:bc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:bc,cause:e})}finally{Ce.release(uc)}},{handler:bc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bc})}),Sc=`local-op-auth-pat`,Cc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!Ce.tryAcquire(dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Sc,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(`
|
|
2113
|
+
`).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:Sc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Sc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Sc,cause:e})}finally{Ce.release(dc)}},{handler:Sc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Sc})}),wc=`local-op-auth-identity`;async function Tc(e,t){if(checkLocalOpSecurity(e,t,{handler:wc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:wc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:wc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:wc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:wc,cause:e})}}}let Ec=`/api/local-op/auth/set-identity`,Dc=`local-op-auth-set-identity`,Oc=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:Dc});return}if(!Ce.tryAcquire(Ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Dc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Dc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Dc,cause:e})}finally{Ce.release(Ec)}},{handler:Dc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dc})});async function kc(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},{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 Ac=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 jc(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 Mc=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})}},{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 Nc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=esm_default({baseDir:de,timeout:{block:15e3}});async function E(e){try{return await w.raw([`show`,`:${e}:${S}`])}catch{return``}}try{let[e,w,D]=await Promise.all([E(1),E(2),E(3)]);successResponse(t,200,SyncConflictContentSuccessSchema,{file:S,base:e,ours:w,theirs:D},{handler:`sync-conflict-content`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Pc(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 Fc=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 Ic(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 Lc=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 Rc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Re.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 zc(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 Bc=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 Vc(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:Be(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 Hc(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 Uc=/^[A-Za-z0-9_-]+$/;function Wc(e,t,S=`template`){return!e||!Uc.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 Gc(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 Kc(e,t){if(e.method===`GET`)return qc(e,t);if(e.method===`PUT`)return Jc(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let qc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Hc(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}),Jc=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Hc(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:Gc(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`});async function Yc(e,t){if(e.method===`GET`)return Qc(e,t);if(e.method===`PUT`)return $c(e,t);if(e.method===`DELETE`)return nl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Xc=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Zc=e=>{let t=e.match(Xc),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}},Qc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Wc(w,t,`template-get`))return;let E=Hc(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}=Zc(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}),$c=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Wc(e,t,`template-put`))return;let w=Hc(S.folder,t,`folder`,`template-put`);if(!w)return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:Gc(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`}),nl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Wc(w,t,`template-delete`))return;let E=Hc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E)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 il(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 al(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 cl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function ll(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 ul(){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,...il(e)]}function dl(){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 fl(){let e=`${w}${de??``}`,t=dl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=ul().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 pl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{fl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}pl();async function ml(e,t){if(e.method===`GET`)return hl(e,t);if(e.method===`POST`)return gl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let hl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=cl(S.searchParams.get(`intent`)),O=ll(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 fl(),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`?al(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}),gl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=cl(S.intent),D=ll(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 fl(),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`?al(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`}),_l=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 vl(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 yl(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 xl=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})});async function Cl(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 Tl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce.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 Cl([`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{Ce.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})}),El=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(!Ce.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 Cl([`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{Ce.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})}),Dl=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(!Ce.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 Cl(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{Ce.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Ol={"/api/asset":Xi,"/api/document":$t,"/api/documents":en,"/api/backlinks":jr,"/api/backlink-counts":Mr,"/api/forward-links":Fr,"/api/link-graph":Ir,"/api/dead-links":Br,"/api/orphans":Lr,"/api/hubs":zr,"/api/tags":Bc,"/api/pages":As,"/api/folder-config":Kc,"/api/template":Yc,"/api/search":ml,"/api/suggest-links":Ns,"/api/page-headings":Ts,"/api/create-page":xs,"/api/create-folder":Cs,"/api/rename-path":Ds,"/api/delete-path":Os,"/api/trash/cleanup":ks,"/api/upload":Ps,"/api/agent-write":Ut,"/api/agent-write-md":Wt,"/api/frontmatter-patch":Kt,"/api/agent-patch":Vr,"/api/agent-undo":Hr,"/api/agent-activity":Ur,"/api/agent-burst-diff":Wr,"/api/save-version":Jr,"/api/history":Yr,"/api/diff":Zr,"/api/rollback":Qr,"/api/metrics/reconciliation":ji,"/api/metrics/parse-health":Hi,"/api/metrics/agent-presence":Ki,"/api/server-info":Ui,"/api/share/construct-url":xl,"/api/share/publish/owners":Tl,"/api/share/publish/name-check":El,"/api/share/publish":Dl,"/api/principal":Gi,"/api/rescue":ka,"/api/workspace":Yi,"/api/sync/status":kc,"/api/sync/trigger":Ac,"/api/sync/conflicts":jc,"/api/sync/conflict-content":Nc,"/api/sync/resolve-conflict":Mc,"/api/sync/abort-merge":zc,"/api/local-op/clone":nc,"/api/local-op/open":oc,"/api/local-op/auth/login":pc,"/api/local-op/auth/status":gc,"/api/local-op/auth/repos":vc,"/api/local-op/auth/signout":xc,"/api/local-op/auth/pat":Cc,"/api/local-op/auth/identity":Tc,"/api/local-op/auth/set-identity":Oc,"/api/installed-agents":Rc,"/api/spawn-cursor":yl,"/api/handoff":vl,"/api/install-skill":Lc,"/api/skill/install-state":_l,"/api/seed/plan":Pc,"/api/seed/apply":Fc,"/api/seed/packs":Ic};F&&(Ol[`/api/test-reset`]=Gr,Ol[`/api/test-rescan-backlinks`]=Kr,Ol[`/api/test-rescan-files`]=qr);let kl=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/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/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),jl=[`/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(kl.has(S)||jl.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`:Ol[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=Ol[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 _s(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Xr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Vc(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 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 `list_documents({ 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` / `grep`. 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` / `grep` / `read_document` 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. Prefer `-A` over plain `ls`: OK projects carry dot-prefixed entries (`.ok/`, nested `.ok/`, `.okignore`) that plain `ls` omits. `-A` shows hidden entries without the noisy `.`/`..` rows that `-a` adds, and without the verbose long-format columns that `-la` adds (the per-child enrichment already carries the useful metadata `-l` would surface).\n- Search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files\n- Typed tools (`read_document`, `search`, `grep`, `list_documents`) remain available — prefer them when a structured `structuredContent` shape is useful (e.g., passing results to another tool). For interactive reads, `exec` is lighter. **Pick the right search:** `search` for ranked retrieval (cmd-K parity — title boost + body BM25 + recency); `grep` for every literal-string occurrence grouped by file with frontmatter enrichment.\n\n## Preview — open the browser at session start\n\n**Open the preview browser as your first OK action of the session, if it is not already open.** The user watches edits land live in that pane; if it isn\'t open, your work is invisible and the whole CRDT pipeline is wasted. Treat this as step zero — before your first read, before your first write.\n\n- Claude Code Desktop: `preview_start("open-knowledge-ui")`.\n- Cursor: use the host\'s open-URL tool with a `previewUrl` from any write response.\n- Other hosts: use whatever command opens a URL (macOS: `open <url>`). On hosts with no preview tool (Codex, generic stdio), surface the URL in chat for the user to click.\n\n**How to know if it\'s already open.** You usually can\'t pre-check from the agent side — rely on these signals:\n\n1. You already opened it earlier in this session → don\'t reopen.\n2. A `write_document` / `edit_document` response returns `previewUrl` but NO `warning: { action: "attach-preview-once" }` → a browser is attached somewhere; do nothing.\n3. A response DOES include `warning: { action: "attach-preview-once", previewUrl, message }` → no browser is attached; open immediately, one-shot. The hint fires only when needed (server tracks `__system__` subscribers) and at most once per session in the normal fresh-start case.\n\nIf the server isn\'t running, you\'ll see a `"Hocuspocus server is not running"` error or `previewUrl: null`. Start the UI (`open-knowledge ui` from a terminal, or `preview_start("open-knowledge-ui")` in Claude Code), then retry. NEVER construct preview URLs by hand — always use the `previewUrl` returned in tool responses.\n\n**No screenshots after edits.** Do NOT take `preview_screenshot` after every `edit_document` / `write_document`. Trust the CRDT tool response as confirmation the edit landed. Only screenshot when debugging a visual issue or when explicitly asked.\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(`
|
|
2134
2114
|
`).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)),isPlainObject(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),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.
|
|
2135
2115
|
|
|
2136
2116
|
Topic: ${e}
|
|
@@ -2278,10 +2258,10 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
2278
2258
|
- **Don't delete research articles** — they are the trail; keep them with a \`superseded_by\` marker
|
|
2279
2259
|
- **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
|
|
2280
2260
|
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
|
|
2281
|
-
`}const DESCRIPTION$
|
|
2282
|
-
`);function register$
|
|
2283
|
-
`);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function register$
|
|
2284
|
-
`),InputSchema$7={folder:string$2().describe("Project-root-relative folder. Empty / `.` means project root."),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only.").describe("Template filename without `.md` extension."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$7=outputSchemaWithText({result:union([object$1({ok:literal(!0),path:string$2(),existed:boolean$1(),cleanedEmpty:object$1({templatesDir:boolean$1(),okDir:boolean$1()})}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])});function register$
|
|
2261
|
+
`}const DESCRIPTION$28=[`Returns a multi-step plan for promoting research findings into a canonical article. Does NOT write the article — you execute the plan after the STOP gate confirms the decision.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
|
|
2262
|
+
`);function register$28(e,t){e.registerTool(`consolidate`,{description:DESCRIPTION$28,inputSchema:{topic:string$2().describe(`The topic to consolidate into a canonical article`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}async function resolvePreviewUrlForTool(e,t,S){return resolvePreviewUrl(e,{lockDir:resolveLockDir(S??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function buildListResolver(e,t){let S={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,S),ui:resolveUiInfo(S)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let S=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${S}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$27=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `get_backlinks({ docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.',"- Deletion is irreversible from this tool. Use `save_version` beforehand if you may need to roll back.","- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
|
|
2263
|
+
`);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function register$27(e,t){e.registerTool(`delete_document`,{description:DESCRIPTION$27,inputSchema:{docName:string$2().describe(`Document name to delete`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(E,`/api/delete-path`,{kind:`file`,path:D.docName,...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok){let e=k.error,t={ok:!1,error:e};return textPlusStructured(`Error: ${e}`,t,!0)}let j=parseDeletedDocNames(k.deletedDocNames),F=await resolvePreviewUrlForTool(D.docName,{config:t.config,resolveCwd:t.resolveCwd},w),L={ok:!0,deletedDocNames:j.length>0?j:[D.docName],...F?{previousPreviewUrl:F.url}:{}};return textPlusStructured(L.deletedDocNames.length===1?`Deleted ${L.deletedDocNames[0]}.`:`Deleted ${L.deletedDocNames.length} documents: ${L.deletedDocNames.join(`, `)}.`,L)})}const DESCRIPTION$26=[`[Operates on disk; no running OK server required] Delete a template.`,``,"Deletes `<folder>/.ok/templates/<name>.md` from the current project. Idempotent: deleting a template that does not exist returns success with `existed: false`. Auto-cleans empty `<folder>/.ok/templates/` and `<folder>/.ok/` directories.",``,`**Parameters:**`,"- `folder` — Project-root-relative folder. Empty / `.` means project root.","- `name` — Template filename without `.md` extension."].join(`
|
|
2264
|
+
`),InputSchema$7={folder:string$2().describe("Project-root-relative folder. Empty / `.` means project root."),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only.").describe("Template filename without `.md` extension."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$7=outputSchemaWithText({result:union([object$1({ok:literal(!0),path:string$2(),existed:boolean$1(),cleanedEmpty:object$1({templatesDir:boolean$1(),okDir:boolean$1()})}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])});function register$26(e,t){e.registerTool(`delete_template`,{description:DESCRIPTION$26,inputSchema:object$1(InputSchema$7).strict(),outputSchema:OutputSchema$7,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E=applyTemplateDelete({projectDir:w,folder:e.folder,name:e.name});if(!E.ok)return{isError:!0,structuredContent:{result:E},content:[{type:`text`,text:`${E.error.code}: ${E.error.message}`}]};let D=[E.existed?`Deleted template at ${E.path}`:`Template at ${E.path} did not exist (no-op)`];return E.cleanedEmpty.templatesDir&&D.push(`Removed empty .ok/templates/ directory`),E.cleanedEmpty.okDir&&D.push(`Removed empty .ok/ directory`),textPlusStructured(D.join(`
|
|
2285
2265
|
`),{result:E})})}function buildDiscoverBody(e){return`# Discover — Project Convention Extraction + Link Graph Activation
|
|
2286
2266
|
|
|
2287
2267
|
You're invoked because (a) the user explicitly asked to set up an existing repo, OR (b) \`list_documents\` surfaced a hint because content exists with no folder frontmatter / templates configured. Your job: **extract conventions from existing siblings + activate the link graph, leaving the repo more structured and more navigable than you found it.**
|
|
@@ -2597,20 +2577,23 @@ Link-graph activation:
|
|
|
2597
2577
|
- **Server down** (Phase 1 step 0): surface "discover needs \`open-knowledge start\` running" and exit cleanly. No partial run.
|
|
2598
2578
|
- **User aborts at any STOP gate** → exit cleanly, leaving any already-applied proposals in place (apply is per-phase, not all-or-nothing).
|
|
2599
2579
|
- **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
|
|
2600
|
-
`}const DESCRIPTION$
|
|
2601
|
-
`),InputSchema$6={cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6=outputSchemaWithText({previewUrl:_null()});function register$
|
|
2602
|
-
`)}\n${renderInventoryFooter()}`;function register$
|
|
2580
|
+
`}const DESCRIPTION$25=[`Returns a multi-step plan for setting up an existing repo (extract conventions, set folder frontmatter, write templates, activate link graph). Does NOT execute the plan — you do, with per-phase user confirmation.`,``,`**Use when:**`,`- First arrival at a repo that has existing markdown content AND no folder frontmatter / templates configured`,"- `list_documents` returns empty `frontmatter_defaults` + empty `templates_available` for substantial folders",`- User explicitly asks to onboard / set up / configure an existing repo`,``,`**Do NOT invoke when:**`,"- The repo is empty (< 5 .md files) — use `ok seed` instead",`- The repo is already fully configured (every substantial folder has folder frontmatter + templates)`,``,'One-shot per project. Idempotent on re-run — detects prior configuration and switches to "extend mode" (proposes additions only, never re-proposes existing artifacts). **Requires the OK Hocuspocus server running** — most primitives the body composes (`list_documents`, `read_document`, link-graph) hit the server. Phase 1 step 0 enforces this; if the server is down, the tool exits cleanly with a "run `open-knowledge start`" instruction. Only `exec`, `set_folder_rule`, `write_template`, and the `.okignore` write are fs-direct.',``,"**Composes existing primitives only** — no new MCP tools, no schema changes. Uses `exec`, `list_documents`, `read_document`, `search`, `set_folder_rule`, `write_template`, `get_orphans`, `get_hubs`, `get_dead_links`, `get_backlinks`, `get_forward_links`, `suggest_links`, `edit_document`."].join(`
|
|
2581
|
+
`),InputSchema$6={cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6=outputSchemaWithText({previewUrl:_null()});function register$25(e,t){e.registerTool(`discover`,{description:DESCRIPTION$25,inputSchema:InputSchema$6,outputSchema:OutputSchema$6,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return S.ok?textPlusStructured(buildDiscoverBody(S.config.content.dir),{previewUrl:null}):textResult(`Error: ${S.error}`,!0)})}const DESCRIPTION$24=`${[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,'**Body-only.** Frontmatter-intersecting find/replace calls are rejected with HTTP 400. Frontmatter editing via MCP is currently unavailable — to change frontmatter, use `write_document` with `position: "replace"` and a payload that includes the new YAML block.',``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
2582
|
+
`)}\n${renderInventoryFooter()}`;function register$24(e,t){e.registerTool(`edit_document`,{description:DESCRIPTION$24,inputSchema:{docName:string$2().describe(`Document name to edit`),find:string$2().describe(`Text to find (exact match)`),replace:string$2().describe(`Replacement text`),offset:number$1().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(E,`/api/agent-patch`,{docName:D.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=resolveLockDir(w),F=resolvePreviewUrl(D.docName,{lockDir:j}),L=typeof k.subscriberCount==`number`?k.subscriberCount:void 0,B=(typeof k.systemSubscriberCount==`number`?k.systemSubscriberCount:void 0)===0,H=L===0,q=k.summary&&typeof k.summary==`object`?k.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y=[`Edit applied successfully.`];F&&Y.push(`Preview: ${F.url}`),B&&Y.push(F?`Open ${F.url} in your preview browser.`:`No preview attached. Start the UI.`),J&&Y.push(J);let ee=Y.join(`
|
|
2603
2583
|
`);if(!F&&!B&&!H&&!q)return textResult(ee);let te={};return F&&(te.previewUrl=F.url,te.previewUrlSource=F.source),B&&(te.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:F?.url??null}),q&&(te.summary=q),textPlusStructured(ee,te)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let S=nonFlagArgs(argsOf(t)),w=S.length>0?S[S.length-1]:``,E=w&&w!==`.`?normalize$1(w):``,D=[];E&&D.push(E);for(let t of e.split(`
|
|
2604
2584
|
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let S=E?`${E}/${e}`:e;D.push(S)}return D}function extractFromGrep(e){let t=[];for(let S of e.split(`
|
|
2605
2585
|
`)){if(!S)continue;let e=S.indexOf(`:`);if(e<0)continue;let w=normalize$1(S.slice(0,e));isWikiPath(w)&&t.push(w)}return t}function extractFromFind(e){let t=[];for(let S of e.split(`
|
|
2606
2586
|
`)){let e=normalize$1(S);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],S=e.matchAll(PATH_FALLBACK_RE);for(let e of S)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let S=null;for(let e=t.length-1;e>=0;e--){let w=t[e];if(PRODUCER_COMMANDS.has(w.command)){S=w;break}if((w.command===`head`||w.command===`tail`)&&headTailActsAsProducer(w)){S=w;break}}let w;if(!S)w=fallback(e);else{switch(S.command){case`cat`:w=extractFromCat(S);break;case`ls`:w=extractFromLs(e,S);break;case`grep`:w=extractFromGrep(e);break;case`find`:w=extractFromFind(e);break;case`head`:case`tail`:w=extractFromHeadTail(S);break;default:w=fallback(e)}w.length===0&&(w=fallback(e))}let E=new Set,D=[];for(let e of w){let t=normalize$1(e);!t||E.has(t)||(E.add(t),D.push(t))}return D}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,S){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=S}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new xt({cwd:`/`,fs:new Ss({root:resolve(e),allowSymlinks:!1})})}async function execBash(e,t){let S=await e.exec(t);if(S.stdout.length>MAX_STDOUT_BYTES)throw new StdoutOverflowError(MAX_STDOUT_BYTES,S.stdout.length,{stdout:S.stdout.slice(0,MAX_STDOUT_BYTES),stderr:S.stderr,exitCode:S.exitCode});return{stdout:S.stdout,stderr:S.stderr,exitCode:S.exitCode}}function normalizeGrepGlob(e){return e.startsWith(`**/`)?e.slice(3):e}async function grep(e,t,S={}){let w=createBashInstance(t),E=[`-rn`,`-F`];(S.caseInsensitive??!0)&&E.push(`-i`);for(let e of S.include??[])E.push(`--include=${shellEscape(normalizeGrepGlob(e))}`);for(let e of S.exclude??[])E.push(`--exclude=${shellEscape(normalizeGrepGlob(e))}`),E.push(`--exclude-dir=${shellEscape(normalizeGrepGlob(e))}`);let D=S.paths?.length?S.paths.map(shellEscape):[`.`],O=`grep ${E.join(` `)} ${shellEscape(e)} ${D.join(` `)}`,k;try{k=await execBash(w,O)}catch(e){if(e instanceof StdoutOverflowError)k=e.partial;else throw e}if(k.exitCode===1&&!k.stdout)return[];if(k.exitCode!==0&&k.exitCode!==1&&!k.stdout)throw Error(`grep exited ${k.exitCode}: ${k.stderr}`);let j=[],F=S.maxResults??1/0;for(let e of k.stdout.split(`
|
|
2607
|
-
`)){if(!e)continue;if(j.length>=F)break;let t=e.indexOf(`:`);if(t===-1)continue;let S=e.indexOf(`:`,t+1);if(S===-1)continue;let w=e.slice(0,t),E=e.slice(t+1,S),D=e.slice(S+1),O=Number.parseInt(E,10);Number.isFinite(O)&&j.push({path:w,line:O,text:D})}return j}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),S=new Map,w=0,E=!1;async function D(e){if(E)return;let O;try{O=await readdir(e,{withFileTypes:!0})}catch{return}for(let k of O){if(E)return;if(k.isDirectory()&&SKIP_DIRS.has(k.name))continue;let O=resolve(e,k.name);if(k.isDirectory()){await D(O);continue}if(k.isFile()){if(w>=SCAN_CAP){E=!0;return}try{let e=await stat$1(O);S.set(relative(t,O),e.mtimeMs),w++}catch{}}}}return await D(t),{snapshot:S,truncated:E}}function diffMtimes(e,t){let S=[];for(let[w,E]of t){let t=e.get(w);(t===void 0||t!==E)&&S.push(w)}for(let[w]of e)t.has(w)||S.push(w);return{changed:S}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let S of e)t.push(`-not`,`-path`,`*/${S}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let S=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),w=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,w),...S,...e.args.slice(w)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let S of e){if(typeof S==`string`){if(SUSPICIOUS_STRING_RE.test(S))return{error:{category:`shell_construct_blocked`,message:`Argument '${S}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(S);continue}if(!isOpToken(S))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(S.op===`glob`&&typeof S.pattern==`string`){t.push(S.pattern);continue}return typeof S.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(S)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let S;try{S=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let w=[],E=[];for(let e of S){if(isOpToken(e)&&e.op===`|`){w.push(E),E=[];continue}E.push(e)}w.push(E);let D=[];for(let e of w){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let S={command:t.args[0],args:t.args},w=checkStage(S);if(w)return{error:w};D.push(S)}return{stages:D}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=50*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$
|
|
2587
|
+
`)){if(!e)continue;if(j.length>=F)break;let t=e.indexOf(`:`);if(t===-1)continue;let S=e.indexOf(`:`,t+1);if(S===-1)continue;let w=e.slice(0,t),E=e.slice(t+1,S),D=e.slice(S+1),O=Number.parseInt(E,10);Number.isFinite(O)&&j.push({path:w,line:O,text:D})}return j}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),S=new Map,w=0,E=!1;async function D(e){if(E)return;let O;try{O=await readdir(e,{withFileTypes:!0})}catch{return}for(let k of O){if(E)return;if(k.isDirectory()&&SKIP_DIRS.has(k.name))continue;let O=resolve(e,k.name);if(k.isDirectory()){await D(O);continue}if(k.isFile()){if(w>=SCAN_CAP){E=!0;return}try{let e=await stat$1(O);S.set(relative(t,O),e.mtimeMs),w++}catch{}}}}return await D(t),{snapshot:S,truncated:E}}function diffMtimes(e,t){let S=[];for(let[w,E]of t){let t=e.get(w);(t===void 0||t!==E)&&S.push(w)}for(let[w]of e)t.has(w)||S.push(w);return{changed:S}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let S of e)t.push(`-not`,`-path`,`*/${S}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let S=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),w=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,w),...S,...e.args.slice(w)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let S of e){if(typeof S==`string`){if(SUSPICIOUS_STRING_RE.test(S))return{error:{category:`shell_construct_blocked`,message:`Argument '${S}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(S);continue}if(!isOpToken(S))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(S.op===`glob`&&typeof S.pattern==`string`){t.push(S.pattern);continue}return typeof S.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(S)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let S;try{S=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let w=[],E=[];for(let e of S){if(isOpToken(e)&&e.op===`|`){w.push(E),E=[];continue}E.push(e)}w.push(E);let D=[];for(let e of w){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let S={command:t.args[0],args:t.args},w=checkStage(S);if(w)return{error:w};D.push(S)}return{stages:D}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=50*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$23=["**STOP — native tools on in-scope markdown (when project has `.ok/`).** When the active project contains `.ok/`, do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code, non-markdown paths, and projects without `.ok/`.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
|
|
2608
2588
|
`);function applySoftCap(e){let t=e.split(`
|
|
2609
2589
|
`),S=t[t.length-1]===``?t.length-1:t.length;if(S<=SOFT_CAP_LINES&&e.length<=SOFT_CAP_BYTES)return{text:e,truncated:!1,omittedLines:0};let w=Math.min(S,SOFT_CAP_LINES),E=0,D=0;for(let e=0;e<w;e++){let S=t[e];if(E+=S.length+1,E>SOFT_CAP_BYTES)break;D++}let O=t.slice(0,D).join(`
|
|
2610
2590
|
`),k=S-D;return{text:`${O}\n<truncated: ${k} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:k}}function detectBinaryArgs(e){let t=[];for(let S of e)if(S.command===`cat`)for(let e of S.args.slice(1))e.startsWith(`-`)||BINARY_EXT_RE.test(e)&&t.push(e);return t}function extractHeadTailLimit(e){for(let t=1;t<e.length;t++){let S=e[t],w=S.match(/^--lines=(\d+)$/);if(w)return Number(w[1]);if(S===`--lines`&&t+1<e.length){let S=Number(e[t+1]);if(Number.isFinite(S))return S}if(S===`-n`&&t+1<e.length){let S=Number(e[t+1]);if(Number.isFinite(S))return S}let E=S.match(/^-n(\d+)$/);if(E)return Number(E[1]);let D=S.match(/^-(\d+)$/);if(D)return Number(D[1])}return 10}function detectHeadTailTruncation(e,t){if(e.length<2)return null;let S=e[e.length-1];if(S.command!==`head`&&S.command!==`tail`)return null;let w=extractHeadTailLimit(S.args),E=t.split(`
|
|
2611
2591
|
`),D=E[E.length-1]===``?E.length-1:E.length;if(D<w)return null;let O=E.slice(0,D),k=new Set(O.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,j=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${S.command} -${w}\` cap (${D} lines, ${k} unique file${k===1?``:`s`}). The \`${j}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${S.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let S=[];return S.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&S.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(S.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let S=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${S.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let S=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${S.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,S){let w=null;for(let t=e.length-1;t>=0;t--){let S=e[t],E=S.command;if(E===`ls`||E===`cat`){w=S;break}if((E===`head`||E===`tail`)&&nonFlagArgs(argsOf(S)).length>0){w=S;break}}if(!w)return``;let E=nonFlagArgs(argsOf(w));if(w.command===`ls`){let e=E[E.length-1];if(!e||e===`.`)return``;let S=e.replace(/\/+/g,`/`);return S.startsWith(`./`)&&(S=S.slice(2)),S.endsWith(`/`)&&(S=S.slice(0,-1)),!S||!t.has(S)?``:`${S}/:\n`}let D=E.filter(e=>/\.(md|mdx)$/.test(e)&&S.has(e));return D.length===1?`==> ${D[0]} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let S of e)t.push(isDirectoryMeta(S)?formatDirectoryEntry(S):formatFileEntry(S));return t.join(`
|
|
2612
2592
|
`)}async function classifyPaths(e,t){let S=[],w=[];return await Promise.all(t.map(async t=>{try{let E=await stat$1(resolve(e,t));E.isDirectory()?w.push(t):E.isFile()&&S.push(t)}catch{/\.(md|mdx)$/i.test(t)&&S.push(t)}})),{files:S,dirs:w}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let S=t(docNameFromPath(e.path));return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}})}async function buildExecResult(e,t){let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${S.error}`);let{cwd:w,config:E,url:D}=S,O=parseCommand(e.command);if(`error`in O)return errorCategoryResult(O.error.category,O.error.message);let k=augmentStagesWithExcludes(O.stages),j=serializeStages(k),F=await snapshotMtimes(w),L=createBashInstance(w),B=``,H=``;try{let e=await execBash(L,j);B=e.stdout,H=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let q=await snapshotMtimes(w),J=diffMtimes(F.snapshot,q.snapshot);if(J.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${J.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let Y=applySoftCap(B),ee=extractReferencedPaths(B,k).filter(e=>resolveWithinRoot(w,e).ok),{files:te,dirs:ne}=await classifyPaths(w,ee),ae=k.length===1&&k[0].command===`cat`&&te.length===1,oe=await Promise.all(te.map(e=>enrichPath(e,{projectDir:w,serverUrl:D},{includeRichFields:ae}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),se=await Promise.all(ne.map(e=>enrichDirectory(e,{projectDir:w}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!ae&&D&&oe.length>0){let e=await fetchBacklinkCountsBatch(D,oe.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of oe){let S=e.get(pathToDocName$1(t.path));typeof S==`number`&&(t.backlinkCount=S)}}let ce=new Map(oe.map(e=>[e.path,e])),ue=new Map(se.map(e=>[e.path,e])),de=[];for(let e of ee){let t=ce.get(e);if(t){de.push(t);continue}let S=ue.get(e);S&&de.push(S)}let fe=detectBinaryArgs(k),me=[];fe.length>0&&me.push(`File${fe.length>1?`s`:``} ${fe.join(`, `)} appear${fe.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let ge=detectHeadTailTruncation(k,B);ge&&me.push(ge.banner),H&&me.push(`stderr: ${H.trim()}`);let _e=me.length>0?`${me.join(`
|
|
2613
|
-
`)}\n\n`:``,ve=buildStdoutProvenance(k,ue,ce)+Y.text,ye=`${_e}${ve}${formatEnrichedBlock(de)}`,{resolve:Ce,ui:we}=await buildListResolver({config:E,resolveCwd:async()=>w}),Te=withPreviewUrls(de,Ce),De=we;return textPlusStructured(ye,{enrichedPaths:Te,stdout:ve,stdoutTruncated:Y.truncated,cwd:w,...De?{ui:De}:{},...me.length>0?{warnings:me}:{}})}function register$
|
|
2593
|
+
`)}\n\n`:``,ve=buildStdoutProvenance(k,ue,ce)+Y.text,ye=`${_e}${ve}${formatEnrichedBlock(de)}`,{resolve:Ce,ui:we}=await buildListResolver({config:E,resolveCwd:async()=>w}),Te=withPreviewUrls(de,Ce),De=we;return textPlusStructured(ye,{enrichedPaths:Te,stdout:ve,stdoutTruncated:Y.truncated,cwd:w,...De?{ui:De}:{},...me.length>0?{warnings:me}:{}})}function register$23(e,t){e.registerTool(`exec`,{description:DESCRIPTION$23,inputSchema:{command:string$2().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:string$2().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")}},async e=>{try{return await buildExecResult(e,t)}catch(e){return errorCategoryResult(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const DESCRIPTION$22=[`[Requires: Hocuspocus server] Set, create, or delete frontmatter properties via JSON Merge Patch (RFC 7396).`,``,`Field-level CRDT merge: concurrent patches to different keys (human form + this tool, or two agents) merge cleanly. Same-key concurrent writes resolve last-writer-wins per key.`,``,'**Use this tool — not `edit_document` — for any frontmatter change.** `edit_document` (agent-patch) targets body content; FM-intersecting `edit_document` calls return HTTP 400. For full-document rewrites (≥3-5 frontmatter keys changing), `write_document({ position: "replace" })` remains the canonical pathway.',``,`**Parameters:**`,"- `docName` — Document name. A trailing `.md` or `.mdx` is stripped automatically.","- `patch` — Object whose keys are property names. Each value is the new value (string, number, boolean, or array of strings) to **set or create** the key, or `null` to **delete** the key. Keys not present in `patch` are unchanged.","- `types` (optional) — **Currently ignored.** Shape-validated for forward-compat but not persisted server-side; type is inferred from value shape on read. Reserved for a future per-key widget-type override (`text | number | boolean | date | list`) once persistence ships.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Prefer outcome phrasing ("Marked spec as approved") over structural ("Set status field"). Avoid secrets / PII — summaries persist to git history.',``,`**Atomicity:** any value failing schema validation rejects the WHOLE patch (HTTP 400 with per-key error report). Either every change commits or none do.`].join(`
|
|
2594
|
+
`),PatchValueSchema=union([FrontmatterValueSchema,_null()]).describe("Property value (string|number|boolean|string[]) — `null` deletes the key");function register$22(e,t){e.registerTool(`frontmatter_patch`,{description:DESCRIPTION$22,inputSchema:{docName:string$2().describe(`Document name`),patch:record(string$2(),PatchValueSchema).describe("JSON Merge Patch — `{key: value}` sets, `{key: null}` deletes"),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional().describe(`Currently ignored (shape-validated for forward-compat but not persisted). Type is inferred from value shape on read. Will become a real per-key widget-type override (text|number|boolean|date|list) once persistence lands.`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(E,`/api/frontmatter-patch`,{docName:D.docName,patch:e.patch,...e.types?{types:e.types}:{},...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok){let e=k.error,t=k.fieldErrors&&typeof k.fieldErrors==`object`?k.fieldErrors:void 0;return textResult(t?`Error: ${e}\n${Object.entries(t).map(([e,t])=>` ${e}: ${t}`).join(`
|
|
2595
|
+
`)}`:`Error: ${e}`,!0)}let j=resolveLockDir(w),F=resolvePreviewUrl(D.docName,{lockDir:j}),L=typeof k.subscriberCount==`number`?k.subscriberCount:void 0,B=(typeof k.systemSubscriberCount==`number`?k.systemSubscriberCount:void 0)===0,H=L===0,q=k.summary&&typeof k.summary==`object`?k.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y=[],ee=[];for(let[t,S]of Object.entries(e.patch))S===null?ee.push(t):Y.push(t);let te=[`Frontmatter patched (${[Y.length?`${Y.length} set`:``,ee.length?`${ee.length} deleted`:``].filter(Boolean).join(`, `)||`${Object.keys(e.patch).length} key(s)`}).`];F&&te.push(`Preview: ${F.url}`),B&&te.push(F?`Open ${F.url} in your preview browser.`:`No preview attached. Start the UI.`),J&&te.push(J);let ne=te.join(`
|
|
2596
|
+
`);if(!F&&!B&&!H&&!q)return textResult(ne);let ae={};return F&&(ae.previewUrl=F.url,ae.previewUrlSource=F.source),B&&(ae.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:F?.url??null}),q&&(ae.summary=q),textPlusStructured(ne,ae)})}const DESCRIPTION$21=[`[Requires: Hocuspocus server] Find all pages that link to a given page.`,`Returns source page names, resolved titles, and context snippets as JSON.`,``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
2614
2597
|
`);function register$21(e,t){e.registerTool(`get_backlinks`,{description:DESCRIPTION$21,inputSchema:{docName:string$2().describe(`Target page docName`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=await httpGet(E,`/api/backlinks?docName=${encodeURIComponent(D.docName)}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=j,{resolve:L,ui:B}=await buildListResolver(t,w),H=(F.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,S=t?L(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),q={...F,backlinks:H,ui:B,cwd:w};return textPlusStructured(JSON.stringify(q,null,2),q)})}const ID_CARDINALITY_CAP=32,DESCRIPTION$20=["[Operates on registry data; no running OK server required] Return full per-entry details for the canonical components an agent picked from the inventory rendered in the `write_document` / `edit_document` tool descriptions.",``,"Each entry carries: literal source-form `example` (copy-pasteable) + form-aware `params` (every prop, with `type` / `values?` / `required` / `defaultValue?` / `description`). Unmatched ids surface in `notFound` rather than failing the call.",``,`**Parameters:**`,`- \`ids\` — Array of canonical ids picked from the write-tool inventory (e.g. \`["Callout", "Tabs"]\`). Max ${ID_CARDINALITY_CAP} ids per call. Case-sensitive — must match the inventory exactly (\`Callout\` not \`callout\`; \`img\` not \`Image\`).`,"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2615
2598
|
`),InputSchema$5={ids:array(string$2().min(1)).max(ID_CARDINALITY_CAP).describe(`Array of canonical ids to fetch. Max ${ID_CARDINALITY_CAP} ids per call. Empty array returns an empty components list.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},ParamSchema=object$1({name:string$2(),type:_enum([`string`,`boolean`,`number`,`enum`,`reactnode`]),values:array(string$2()).optional(),required:boolean$1(),defaultValue:union([string$2(),boolean$1(),number$1()]).optional(),description:string$2().optional(),omitOnDefault:literal(!0).optional(),advanced:literal(!0).optional(),language:_enum([`mermaid`,`latex`,`html`,`json`,`yaml`,`javascript`,`markdown`]).optional(),accept:array(string$2()).optional()}),ComponentEntrySchema=object$1({id:string$2(),displayName:string$2(),description:string$2(),kind:_enum([`jsx-block`,`jsx-void`]),example:string$2(),params:array(ParamSchema)}),OutputSchema$5=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(ComponentEntrySchema).describe(`Full per-entry details for ids that matched.`),notFound:array(string$2()).describe(`Ids that did not match any canonical descriptor.`)});function register$20(e,t){e.registerTool(`get_components`,{description:DESCRIPTION$20,inputSchema:InputSchema$5,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t=getAgentCanonicalDescriptors(),S=new Map(t.map(e=>[e.name,e])),w=[],E=[],D=new Set;for(let t of e.ids){if(D.has(t))continue;D.add(t);let e=S.get(t);if(e===void 0){E.push(t);continue}w.push(projectFull(e))}let O={version:1,components:w,notFound:E};return textPlusStructured(JSON.stringify(O,null,2),O)})}const DESCRIPTION$19=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, `github.*`, and `preview.*` config sub-trees were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or hardcoded behavior, in the case of `preview.*`). Reading those paths returns `exists: false`.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["content"]` returns the content sub-tree; `["appearance", "theme"]` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2616
2599
|
`),InputSchema$4={path:array(string$2()).optional().describe(`Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({value:unknown$2().describe(`Resolved config value at the requested path (or full config).`),exists:boolean$1().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:array(string$2()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)});function readConfigPath(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S)return;S=S[e]}return S}function register$19(e,t){e.registerTool(`get_config`,{description:DESCRIPTION$19,inputSchema:InputSchema$4,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let w=e.path??[],E=w.length>0?readConfigPath(S.config,w):S.config;return w.length>0&&E===void 0?textPlusStructured(`(no value at ${w.join(`.`)})`,{value:null,exists:!1,path:w}):textPlusStructured(JSON.stringify(E,null,2),{value:E,exists:!0,path:w})})}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
|
|
@@ -2702,7 +2685,7 @@ If the source is directly relevant to an existing article or research doc, updat
|
|
|
2702
2685
|
- **No promotion to a canonical article** — that's the \`consolidate\` tool's job, later
|
|
2703
2686
|
- **No silent chaining into research** — ingest completes on its own; the user explicitly opts into \`research\`
|
|
2704
2687
|
- **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source
|
|
2705
|
-
`}const DESCRIPTION$12=[`
|
|
2688
|
+
`}const DESCRIPTION$12=[`Returns a multi-step plan for ingesting an external source (URL or local file). Does NOT fetch, write, or execute — you execute the plan. The body details Karpathy's three-layer pattern + the closed-loop ingest contract.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
|
|
2706
2689
|
`);function register$12(e,t){e.registerTool(`ingest`,{description:DESCRIPTION$12,inputSchema:{source:string$2().describe(`URL, file path, or identifier of the source to ingest`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`ingest`,t,`source`,buildBody$1))}const DESCRIPTION$11=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,"Returns document names, optionally filtered by directory. When `dir` is set,","also surfaces folder-level metadata: `frontmatter_defaults` (merged folder","defaults that new docs in this folder will inherit) and `templates_available`","(menu of starter shapes for `write_document({ template })`). Pass `depth: N`","to also enrich subfolders up to N levels deep — mirrors `find -maxdepth N`.",``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory","- `depth` (optional, default `1`) — Subfolder enrichment depth. `1` = this"," folder only; `2` = direct children's folder metadata too; `Infinity` =",` full subtree. Walk-up ancestors' templates always show regardless.`].join(`
|
|
2707
2690
|
`);function register$11(e,t){e.registerTool(`list_documents`,{description:DESCRIPTION$11,inputSchema:{dir:string$2().optional().describe(`Optional directory to filter documents`),depth:number$1().int().min(1).optional().describe("Subfolder enrichment depth (find -maxdepth semantics). Default 1. Only meaningful when `dir` is also set."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=null;if(e.dir!==void 0){let t=resolveWithinRoot(w,e.dir);if(!t.ok)return textResult(`Error: ${t.reason}`,!0);D=t.rel}let O=await httpGet(E,`/api/documents${D===null?``:`?dir=${encodeURIComponent(D)}`}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=j,{resolve:L,ui:B}=await buildListResolver(t,w),H=(F.documents??[]).filter(e=>e.kind!==`folder`).map(e=>{let t=typeof e.docName==`string`?e.docName:null,S=t?L(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),q;if(D!==null){let t=e.depth??1;try{q=await enrichDirectoryRecursive(D,t,{projectDir:w})}catch{q=void 0}}let J={...F,documents:H,ui:B,cwd:w,...q?{folder:q}:{}};return textPlusStructured(JSON.stringify(J,null,2),J)})}const DESCRIPTION$10=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"**When the project has `.ok/`**, strongly prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4. In projects without `.ok/`, use native `Read` as usual.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
|
|
2708
2691
|
`);function formatShadowHistory(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let S of e){let e=S.writerClassification===`agent`?`agent: ${S.writerName}`:S.writerClassification===`principal`?`human: ${S.writerName}`:`${S.writerClassification}: ${S.writerName}`,w=S.hash.slice(0,7);t.push(`- ${w} ${S.date} [${e}] ${S.message}`)}return t.join(`
|
|
@@ -3064,7 +3047,7 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3064
3047
|
- **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
|
|
3065
3048
|
- **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
|
|
3066
3049
|
- **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
|
|
3067
|
-
`}const DESCRIPTION$7=[
|
|
3050
|
+
`}const DESCRIPTION$7=["Returns a multi-step plan for researching a topic. Does NOT fetch sources or write articles — you execute the plan (which calls `ingest` for sources, then writes a provisional article).",`Provisional, not canonical — findings live here until decisions solidify.`,``,`**Use when:**`,`- Researching a topic before committing to an approach`,`- Exploring a decision space or comparing alternatives`,`- Synthesizing multiple sources into structured analysis`,`- Spec conversations and exploratory work that is not yet canonical`,``,`**Triggers on:**`,`- "research", "investigate", "compare options for", "analyze alternatives"`,`- User asks to explore trade-offs, gather evidence, or evaluate approaches`,`- A decision needs structured analysis grounded in external sources`].join(`
|
|
3068
3051
|
`);function register$7(e,t){e.registerTool(`research`,{description:DESCRIPTION$7,inputSchema:{topic:string$2().describe(`The topic, question, or anchor URL to research`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`research`,t,`topic`,buildBody))}const DESCRIPTION$6=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
3069
3052
|
`);function register$6(e,t){e.registerTool(`rollback_to_version`,{description:DESCRIPTION$6,inputSchema:{docName:string$2().describe(`Document name to restore`),commitSha:string$2().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=D.docName,k=await httpGet(E,`/api/history/${e.commitSha}?docName=${encodeURIComponent(O)}`);if(!k.ok)return textResult(`Error: ${k.error??`Version not found`}`,!0);let j=t.identityRef?.current,F=await httpPost(E,`/api/rollback`,{docName:O,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...j?{agentId:j.connectionId,agentName:j.displayName,clientName:j.clientInfo?.name,colorSeed:j.colorSeed}:{}});if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=F.summary&&typeof F.summary==`object`?F.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H=[`Restored "${O}" to version ${e.commitSha.slice(0,8)} (${k.author}, ${k.timestamp}). The change has been applied to all connected editors.`];B&&H.push(B);let q=await resolvePreviewUrlForTool(O,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(H.join(`
|
|
3070
3053
|
`),{previewUrl:q?.url??null,...q?{previewUrlSource:q.source}:{},...L?{summary:L}:{}})})}const DESCRIPTION$5=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
|
|
@@ -3076,7 +3059,7 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3076
3059
|
`)}\n${renderInventoryFooter()}`;function register$1(e,t){e.registerTool(`write_document`,{description:DESCRIPTION$1,inputSchema:{docName:string$2().describe(`Document name to write to`),markdown:string$2().optional().describe("Markdown content to write. Optional when `template` is set — the template body is used."),template:string$2().min(1).optional().describe(`Template name resolved against parent folder's templates_available (leaf → root walk-up; closest-wins on collision). See list_documents({ dir, depth: 1 }) to inspect the menu.`),position:_enum([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current;if(e.template===void 0&&e.markdown===void 0)return textResult("Error: either `markdown` or `template` must be provided. Omitting both would write empty content.",!0);if(e.template!==void 0&&e.markdown!==void 0)return textResult("Error: TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one. The template body becomes the new doc verbatim; fill placeholders via subsequent `edit_document` calls.",!0);let k=e.markdown??``,j=e.position;if(e.template!==void 0){let t=parentFolderOf(D.docName),S=resolveTemplatesAvailable(w,t,{depth:1}),E=S.find(t=>t.name===e.template);if(!E)return textResult(`Error: template "${e.template}" not found for folder "${t||`.`}". Available: ${S.length===0?`(none)`:S.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check list_documents({ dir, depth: 1 }) at the parent folder to see the menu.`,!0);let F;try{F=readFileSync(resolve(w,E.path),`utf-8`)}catch(e){return textResult(`Error: failed to read template at ${E.path}: ${e.message}`,!0)}k=applySubstitution(F,{date:todayIsoUtc(),user:O?.displayName??``}),j=`replace`}let F=await httpPost(E,`/api/agent-write-md`,{docName:D.docName,markdown:k,position:j,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=resolveLockDir(w),B=resolvePreviewUrl(D.docName,{lockDir:L}),H=typeof F.subscriberCount==`number`?F.subscriberCount:void 0,q=(typeof F.systemSubscriberCount==`number`?F.systemSubscriberCount:void 0)===0,J=H===0,Y=Array.isArray(F.hints)?F.hints:void 0,ee=F.summary&&typeof F.summary==`object`?F.summary:void 0,te=typeof ee?.hint==`string`?ee.hint:void 0,ne=[e.template===void 0?`Written successfully (${j}).`:`Written successfully (instantiated from template "${e.template}").`];if(B&&ne.push(`Preview: ${B.url}`),q&&ne.push(B?`Open ${B.url} in your preview browser.`:`No preview attached. Start the UI.`),te&&ne.push(te),Y)for(let e of Y)e.message&&ne.push(e.message);let ae=ne.join(`
|
|
3077
3060
|
`);if(!B&&!q&&!J&&!Y&&!ee)return textResult(ae);let oe={};return B&&(oe.previewUrl=B.url,oe.previewUrlSource=B.source),q&&(oe.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:B?.url??null}),Y&&(oe.hints=Y),ee&&(oe.summary=ee),textPlusStructured(ae,oe)})}const DESCRIPTION=[`[Operates on disk; no running OK server required] Create or update a template.`,``,"Templates are markdown starter shapes that agents pick from when creating a new doc — `write_document({ template: <name> })` resolves the name against the folder cascade and instantiates the body + frontmatter.",``,'Templates live at `<folder>/.ok/templates/<name>.md`. The `folder` argument selects which project folder owns it (project-wide via `folder: ""`, or scoped to a subfolder).',``,"**`title` is required** in the frontmatter — it is the menu surface agents pick from. Missing or empty title returns `TEMPLATE_TITLE_REQUIRED`. `description` is recommended (soft warning when absent) — it disambiguates similarly-named templates.",``,"**Substitution allowlist.** The body MAY contain `{{date}}` (today, ISO-8601) and `{{user}}` (calling principal display name). Any other `{{...}}` token is rejected at write time with `TEMPLATE_UNKNOWN_VARIABLE`. Substitution happens at instantiation time (when `write_document({ template })` materializes the doc), not at template-write time — templates on disk show the raw `{{date}}` token.",``,`**Parameters:**`,'- `folder` — Project-root-relative folder (e.g. `"meetings"`, `"meetings/prep-notes"`). Empty / `.` means project root.',"- `name` — Template filename without `.md`. Letters, digits, `_`, `-` only.","- `body` — Markdown body. May use `{{date}}` / `{{user}}` substitution tokens. Other placeholder text in `{shape}` form (e.g. `{Meeting Title}`) is LITERAL — agents fill it in via subsequent `edit_document` calls.","- `frontmatter` — `{title (required), description?, tags?: string[]}` for the template menu."].join(`
|
|
3078
3061
|
`),InputSchema={folder:string$2().describe("Project-root-relative folder. Empty / `.` means project root."),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).").describe("Template filename without `.md` extension."),body:string$2().describe(`Markdown body for the template.`),frontmatter:object$1({title:string$2().min(1,"Template `title` is required — it is the menu surface agents pick from.").describe(`Required. The menu surface agents pick from. Empty / missing returns TEMPLATE_TITLE_REQUIRED.`),description:string$2().optional().describe(`Recommended. Disambiguates similarly-named templates. Soft warning when absent.`),tags:array(string$2()).optional().describe(`Optional. Concatenated with cascade tags at instantiation time.`)}).describe("Template menu metadata. `title` MUST be present (hard error if missing). `description` SHOULD be present (warning)."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema=outputSchemaWithText({result:union([object$1({ok:literal(!0),path:string$2(),created:boolean$1(),warnings:array(string$2())}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])});function register(e,t){e.registerTool(`write_template`,{description:DESCRIPTION,inputSchema:object$1(InputSchema).strict(),outputSchema:OutputSchema,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E=applyTemplateWrite({projectDir:w,folder:e.folder,name:e.name,body:e.body,frontmatter:e.frontmatter});if(!E.ok)return{isError:!0,structuredContent:{result:E},content:[{type:`text`,text:`${E.error.code}: ${E.error.message}`}]};let D=[`${E.created?`Created`:`Updated`} template at ${E.path}`];if(E.warnings.length>0){D.push(``,`Warnings:`);for(let e of E.warnings)D.push(` - ${e}`)}return textPlusStructured(D.join(`
|
|
3079
|
-
`),{result:E})})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$22(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$12(w,{config:t.config,resolveCwd:E(`ingest`)}),register$7(w,{config:t.config,resolveCwd:E(`research`)}),register$27(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$24(w,{config:t.config,resolveCwd:E(`discover`)}),register$10(w,{resolveCwd:E(`read_document`),config:t.config,serverUrl:t.serverUrl}),register$4(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$13(w,{resolveCwd:E(`grep`),config:t.config,serverUrl:t.serverUrl}),register$2(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`suggest_links`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$23(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$26(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$9(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_document`),identityRef:t.identityRef}),register$8(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_folder`),identityRef:t.identityRef}),register$16(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$5(w,t.config,t.serverUrl,E(`save_version`),t.identityRef),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rollback_to_version`),identityRef:t.identityRef}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_documents`)}),register$21(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_backlinks`)}),register$20(w,{resolveCwd:E(`get_components`),config:t.config}),register$17(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_forward_links`)}),register$14(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_orphans`)}),register$15(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_hubs`)}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_dead_links`)}),register$19(w,{config:t.config,resolveCwd:E(`get_config`)}),register$3(w,{config:t.config,resolveCwd:E(`set_folder_rule`)}),register(w,{config:t.config,resolveCwd:E(`write_template`)}),register$25(w,{config:t.config,resolveCwd:E(`delete_template`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)});installPrettyZodErrors(E);let D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}if(j!==void 0){try{j(e,t,()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})})}catch(e){E.error({err:e},`Unhandled content-asset middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=B.get(S);e!==void 0&&(clearTimeout(e),B.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(B.delete(S),q)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(S,e),E.info({connectionId:S,graceMs:F},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),L.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled([...H])}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let S=resolve(e,t.slice(5));try{return readFileSync(S,`utf-8`).trim()}catch{try{let S=readFileSync(resolve(e,`packed-refs`),`utf-8`),w=t.slice(5),E=S.split(`
|
|
3062
|
+
`),{result:E})})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$23(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$12(w,{config:t.config,resolveCwd:E(`ingest`)}),register$7(w,{config:t.config,resolveCwd:E(`research`)}),register$28(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$25(w,{config:t.config,resolveCwd:E(`discover`)}),register$10(w,{resolveCwd:E(`read_document`),config:t.config,serverUrl:t.serverUrl}),register$4(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$13(w,{resolveCwd:E(`grep`),config:t.config,serverUrl:t.serverUrl}),register$2(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`suggest_links`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$24(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$27(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$22(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`frontmatter_patch`),identityRef:t.identityRef}),register$9(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_document`),identityRef:t.identityRef}),register$8(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_folder`),identityRef:t.identityRef}),register$16(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$5(w,t.config,t.serverUrl,E(`save_version`),t.identityRef),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rollback_to_version`),identityRef:t.identityRef}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_documents`)}),register$21(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_backlinks`)}),register$20(w,{resolveCwd:E(`get_components`),config:t.config}),register$17(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_forward_links`)}),register$14(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_orphans`)}),register$15(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_hubs`)}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_dead_links`)}),register$19(w,{config:t.config,resolveCwd:E(`get_config`)}),register$3(w,{config:t.config,resolveCwd:E(`set_folder_rule`)}),register(w,{config:t.config,resolveCwd:E(`write_template`)}),register$26(w,{config:t.config,resolveCwd:E(`delete_template`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)});installPrettyZodErrors(E);let D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}if(j!==void 0){try{j(e,t,()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})})}catch(e){E.error({err:e},`Unhandled content-asset middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=B.get(S);e!==void 0&&(clearTimeout(e),B.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(B.delete(S),q)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(S,e),E.info({connectionId:S,graceMs:F},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),L.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled([...H])}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let S=resolve(e,t.slice(5));try{return readFileSync(S,`utf-8`).trim()}catch{try{let S=readFileSync(resolve(e,`packed-refs`),`utf-8`),w=t.slice(5),E=S.split(`
|
|
3080
3063
|
`).find(e=>e.endsWith(` ${w}`));if(E)return E.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,S){let w=resolveGitDir(e);if(!w)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let E=w,D=!1,O=null,k=null,j=null,F=null;async function L(e){if(H&&await H,!D)return;O&&=(clearTimeout(O),null),k&&=(clearTimeout(k),null);let t=readHeadSha(E),w=j!==t,L=readBranchFromHead(E),B;B=L?.startsWith(`detached-`)?`detached-head`:F===L?`within-branch`:`cross-branch`;let q=F;try{await S({headMoved:w,oldHead:j,newHead:t,timeout:e,batchKind:B,oldBranch:q,newBranch:L})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{D=!1,j=t,F=L}}function B(){O&&clearTimeout(O),O=setTimeout(()=>{O=null,L(!1)},QUIET_WINDOW_MS)}let H=null;async function q(e){if(!D){D=!0,j=readHeadSha(E);let S=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();H=S,await S,H=null,k=setTimeout(()=>{k=null,L(!0)},BATCH_TIMEOUT_MS)}B()}let J,Y;try{Y=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await Y.subscribe(E,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){q(t);break}}});J=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return j=readHeadSha(E),F=readBranchFromHead(E),console.log(`[head-watcher] Watching ${E} for HEAD changes`),{unsubscribe:async()=>{D&&await L(!1),O&&clearTimeout(O),k&&clearTimeout(k),await J()},getLastKnownBranch:()=>F}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:S,signalChannel:w,debounceMs:E=100}=e,D=new Map;function O(e){let t=D.get(e);t&&(clearTimeout(t),D.delete(e))}function k(e,k){O(e),D.set(e,setTimeout(()=>{D.delete(e);try{let E=serializeLiveDocument(k);t.updateDocumentFromMarkdown(e,E),w?.(`backlinks`),w?.(`graph`),S&&(S.updateDocumentFromMarkdown(e,E),w?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},E))}return{async onChange({documentName:e,document:t,transactionOrigin:S}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(S)&&S.context?.origin===`file-watcher`||k(e,t)},async beforeUnloadDocument({documentName:e}){O(e)},async onDestroy(){for(let e of D.values())clearTimeout(e);D.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),S=resolve(t,PRINCIPAL_FILE),{name:w,email:E}=await readGitConfig(e);if(existsSync(S)){let e;try{e=JSON.parse(readFileSync(S,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,D=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),O=t.slice(10,18),k={id:t,display_name:w?sanitizeGitIdentity(w):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:E?sanitizeGitIdentity(E):typeof e.display_email==`string`?e.display_email:`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:D};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}mkdirSync(t,{recursive:!0});let D=`principal-${randomUUID()}`,O=D.slice(10,18),k={id:D,display_name:w?sanitizeGitIdentity(w):`Local User`,display_email:E?sanitizeGitIdentity(E):`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let S=e.resolveFilePath(t);return S!==null&&e.fileExists(S)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let S=t.recentlyRemovedDocs.get(e);if(S===void 0)return;if(S.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let w=new Set([e]),E=S.newDocName;for(;;){if(w.has(E)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:E}));return}w.add(E);let S=t.recentlyRemovedDocs.get(E);if(S===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E);if(S.kind===`deleted`)throw fileExistsForDocName(t,E)?(t.recentlyRemovedDocs.delete(E),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));E=S.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,S=new Map;return{async afterLoadDocument({documentName:w,document:E}){if(isSystemDoc(w)||isConfigDoc(w)||t.has(w))return;let D=E,O=D.getXmlFragment(`default`),k=D.getText(`source`),j=()=>{try{let S=setupServerObservers({doc:D,xmlFragment:O,ytext:k,mdManager:e.mdManager,schema:e.schema,docName:w,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(w,S),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${w}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!j()){let e=setTimeout(()=>{S.delete(w),!t.has(w)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${w}'`),j())},5e3);S.set(w,e)}},async afterUnloadDocument({documentName:e}){let w=S.get(e);w&&(clearTimeout(w),S.delete(e));let E=t.get(e);E&&(E(),t.delete(e))},async onDestroy(){for(let e of S.values())clearTimeout(e);S.clear();for(let[e,S]of t.entries())try{S()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let S=t.createdBy;return!(typeof S.runtimeVersion!=`string`||S.protocolVersion!==void 0&&typeof S.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let S;try{S=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let w;try{w=JSON.parse(S)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(w))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:w}}function writeStateManifest(e,t){let S=manifestPath(e);mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),S=e.currentStateSchemaVersion??1,w=e.currentRuntimeVersion??RUNTIME_VERSION,E=e.currentProtocolVersion??1,D=(e.now??(()=>new Date))().toISOString(),O=manifestPath(e.lockDir),k=readStateManifest(e.lockDir);if(k.status===`present`){let j=k.manifest;if(!isCompatibleSchema(j.stateSchemaVersion,S))throw new StateManifestError({kind:`incompatible`,path:O,message:`State manifest at ${O} declares stateSchemaVersion=${j.stateSchemaVersion} but this binary supports ${S}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${j.createdBy.runtimeVersion}, protocol ${j.createdBy.protocolVersion}.)`});try{let t={...j,lastWriteBy:{runtimeVersion:w,protocolVersion:E,at:D}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),j}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let k={stateSchemaVersion:S,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E}};return writeStateManifest(e.lockDir,k),t.info({path:O,stateSchemaVersion:S},`[state-manifest] fresh project — wrote manifest`),k}let j={stateSchemaVersion:0,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E,adoptedAt:D}};return writeStateManifest(e.lockDir,j),t.warn({path:O,runtimeVersion:w},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),j}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-DwfYp_z--DreW3fNC.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(`
|
|
3081
3064
|
`).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`)}}};function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=e instanceof Error?e:Error(String(e)),S=extractStderr(t),w=`${t.message}\n${S}`.toLowerCase();return matchesAny(w,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:S}:matchesAny(w,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:S}:matchesAny(w,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:S}:matchesAny(w,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:S}:matchesAny(w,AUTH_PATTERNS)?/\b401\b/.test(w)||/token.*expired/i.test(w)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:S}:/\b403\b/.test(w)?matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:S}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:S}:matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:matchesAny(w,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:S}:matchesAny(w,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:S}:matchesAny(w,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:S}:matchesAny(w,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:S}:matchesAny(w,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:S}:matchesAny(w,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:S}:matchesAny(w,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:S}:matchesAny(w,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:S}:matchesAny(w,NETWORK_PATTERNS)?/timed? out/i.test(w)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:S}:/refused/i.test(w)||/econnrefused/i.test(w)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:S}:/resolve.*host/i.test(w)||/enotfound/i.test(w)||/getaddrinfo/i.test(w)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:S}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:S}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:S}}function computeRemainingMs(e,t,S=Date.now()){if(!e)return 0;let w=new Date(e).getTime();if(Number.isNaN(w))return 0;let E=w+t*1e3;return Math.max(0,E-S)}const log=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function jitteredMs(e){let t=e*1e3,S=t*.15*(2*Math.random()-1);return Math.round(t+S)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let S=readFileSync(t,`utf-8`).trim(),w=/^ref:\s+(refs\/.+)$/.exec(S);if(!w)return!1;let E=w[1];if(existsSync(join(e,`.git`,E)))return!1;let D=join(e,`.git`,`packed-refs`);if(existsSync(D)){let e=readFileSync(D,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${E}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=existsSync(join(this.projectDir,`.git`,`MERGE_HEAD`));if(this.conflictCount>0&&!t)log.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&t)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
3082
3065
|
`).map(e=>e.trim()).filter(Boolean):[]),S=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<S&&log.info({cleared:S-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(t&&this.conflictCount===0){log.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),log.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.error=void 0,this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow()}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`)&&(this.pausedReason=void 0,this.error=void 0),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async resolveConflict(e,t,S){await this.conflictStore.resolveConflict(e,t,S),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()),this.scheduleSaveState()}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let S=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!S||S===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log.warn({},`[sync] detached HEAD — pausing sync`);return}t=S,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))));return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.error=void 0}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{if(await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e))return;await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),S=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),w=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:S});if(isUnbornHead(this.projectDir)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let E;try{E=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),S=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(S)||/ambiguous argument 'HEAD'/i.test(S)||/does not have any commits yet/i.test(S)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))));return}await e.git.raw([`read-tree`,E]);let D=new Set;try{let t=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,E])).trim();for(let e of t?t.split(`
|
|
@@ -3088,4 +3071,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3088
3071
|
`).split(`
|
|
3089
3072
|
`),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=Lt?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex 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:()=>Rt?.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:()=>Lt?Lt.getFileIndex():new Map,getFolderIndex:()=>Lt?Lt.getFolderIndex():new Map,getAliasMap:()=>Lt?Lt.getAliasMap():new Map,rescanFiles:()=>Lt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>zt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}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),vt=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}`)}}},Tt=null,Et=e=>{e&&(Tt===null&&(Tt=new Set,setImmediate(()=>{let e=Tt;if(Tt=null,e)try{for(let t of e)vt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Tt.add(e))};function Dt(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 jt(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`: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(),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)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),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)}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)}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=Rt?.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=S.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Et(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Et(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=Dt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Mt=[];async function Ft(e){if(isBatchInProgress()){Mt.push(e);return}await jt(e)}async function It(){let e=Mt.splice(0,Mt.length);for(let t of e)await jt(t)}let Lt=null,Rt=null,zt=null,Bt=null;async function Vt(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 Ht(){return Bt||(Bt=(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{Rt&&=(await Rt.unsubscribe(),null),Lt&&=(await Lt.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 Vt(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{zt&&=(await zt.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)})}}})(),Bt)}let Ut=[];async function Wt(){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`),Ut.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,Ut.includes(`shadow-repo`)||Ut.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`),Ut.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`),Ut.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`),Ut.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`),Ut.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();zt?.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}`),Ut.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`),Ut.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`)}}Lt=await startWatcher(t,Ft,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`),Ut.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Ut.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Ut.push(`file-watcher`)}try{Rt=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=Mt.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`)setBatchInProgress(!1),await It(),await ge.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Mt.splice(0,Mt.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`),Ut.includes(`basename-index-partial`)||Ut.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++;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(`
|
|
3090
3073
|
`))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`),Ut.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{zt=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 zt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),zt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Wt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ht,ready:Re,degraded:Ut,lockDir:ae,get syncEngine(){return zt}}}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-D7DXNVql-B5nINglj.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=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me}),_e=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ve=null;w!==null&&(ve=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _e()})})),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()})});let ye=fe.address(),Ce=typeof ye==`object`&&ye?ye.port:e.port??0;if(ue=Ce,j(ne,Ce),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let we=!1,Te=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 _e=async()=>{if(we)return;we=!0;let e=[],t=async(t,S)=>{try{await Te(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{ve?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ge.shutdown()),await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ge.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()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:_e,lockDir:ne,contentDir:e.contentDir,port:Ce,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}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,ALL_EDITOR_IDS as $r,incrementServerObserverFire as $t,MissingOkConfigError as A,_coercedNumber as Ai,readServerPackageVersion as An,tracedWriteFile as Ar,createStreamingErrorWriter as At,STARTER_PACK_IDS as B,registerWrite as Bn,writeTargetVersion as Br,formatAuthRejectionWire as Bt,LOG_MD_TEMPLATE as C,boolean$1 as Ci,parseAuthRejectionWire as Cn,tracedMkdir as Cr,createExternalChangeHandler as Ct,MCP_SERVER_NAME as D,object$1 as Di,planSeed as Dn,tracedRmSync as Dr,createPersistenceExtension as Dt,MCP_CONNECTION_ID_HEADER as E,number$1 as Ei,pathToDocName as En,tracedRenameSync as Er,createOsProbe as Et,SERVICE_WRITER as F,readUiLock as Fn,validateCloneInputs as Fr,errorResponse as Ft,StateManifestError as G,resolveContentDir as Gn,isInitializedNotification as Gr,getLocalDir as Gt,STATE_MANIFEST_FILENAME as H,removeLastKnownHash as Hn,McpServer as Hr,formatContributorsFrom as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,reconcile as In,validateSkillZip as Ir,evictStaleTrackerEntries as It,acquireUiLock as J,resolveLockDir as Jn,readConfigSafely as Jr,getMetrics as Jt,TagIndex as K,resolveCursorBinaryDefault as Kn,isJSONRPCRequest as Kr,getLogger as Kt,STARTER_FOLDERS as L,recordContributor as Ln,withSpan as Lr,extractWikiLinksFromMarkdown as Lt,PinoLogger as M,require_dist$2 as Mi,readStateManifest as Mn,updateLastKnownHash as Mr,detectClaudeDesktopPresence as Mt,ProjectGitInitError as N,readTargetRecordedAt as Nn,updateUiLockPort as Nr,detectProjectShape as Nt,MISSING_OK_CONFIG_MESSAGE as O,string$2 as Oi,readAllTargets as On,tracedRmdirSync as Or,createServer$1 as Ot,ROLLBACK_ORIGIN as P,readTargetVersion as Pn,validateAgentId as Pr,ensureProjectGit as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,MalformedGitPointerError as Qr,incrementCollabSocketFilteredError as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,recordSkillInstallEvent as Rn,withSpanSync as Rr,findEnclosingGitRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,array as Si,normalizeFsPath as Sn,tracedLinkSync as Sr,createContentFilterAsync as St,MAX_AGENT_SESSIONS as T,looseObject as Ti,parseKeepaliveConnectionId as Tn,tracedRename as Tr,createMcpHttpHandler as Tt,SeedPrerequisiteError as U,resetMetrics as Un,JSONRPCMessageSchema as Ur,gcCheckpointRefs as Ut,STARTER_TEMPLATES as V,releaseUiLock as Vn,writeTracker as Vr,formatContributors as Vt,SeedRootDirError as W,resolveBundledSkillDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getCurrentMcpLogger as Wt,applyExternalChange as X,resolvePackageVersion as Xn,writeConfigPatch as Xr,handleCollabSocketError as Xt,applyAgentMarkdownWrite as Y,resolvePack as Yn,resolveConfigPath as Yr,getTracer as Yt,applySeed as Z,restoreContributors as Zn,GitDirAccessError as Zr,handleSpawnCursor as Zt,GIT_UPSTREAM_WRITER as _,LOCAL_DIR as _i,listRescueCheckpoints as _n,startWatcher as _r,contentHash as _t,AgentPresenceBroadcaster as a,EXECUTABLE_BLOCKLIST_EXTENSIONS as ai,isAllowedApiOrigin as an,safeContentPath as ar,buildReadResult as at,HocuspocusAuthTokenSchema as b,ZodNumber$1 as bi,loggerFactory as bn,toBroadcasterKey as br,createAssetServeMiddleware as bt,BacklinkIndex as c,ProblemDetailsSchema as ci,isHocuspocusAuthRejectionReason as cn,sanitizeClientName as cr,buildWipTree as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,colorFromSeed as di,isPairedWriteOrigin as dn,seedBasenameIndex as dr,clearContributors as dt,ASSET_EXTENSIONS as ei,initShadowRepo as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,defaultScheduler as fi,isPathWithinDir as fn,setActiveSpanAttributes as fr,coercePackId as ft,FILE_WATCHER_ORIGIN as g,CONFIG_SCHEMA_MAJOR_PATH as gi,lastKnownHash as gn,splitMarkdownBlocks as gr,containsConflictMarkers as gt,FILE_SYSTEM_WRITER as h,isOrphanMode as hi,isSystemDoc as hn,spawnDetached as hr,commitWipFromTree as ht,AgentFocusBroadcaster as i,EDITOR_LABELS as ii,installUserSkill as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,NEVER as ji,readSkillInstallStateSnapshot as jn,tracedWriteFileSync as jr,createTestLogger as jt,McpLogger as k,url as ki,readBranchFromHead as kn,tracedUnlinkSync as kr,createServerObserverExtension as kt,CC1Broadcaster as l,SKILL_STATE_TARGETS as li,isKnownPackId as ln,saveInMemoryCheckpoint as lr,classifyEvents as lt,DEFAULT_PACK_ID as m,iconFromClientName as mi,isSelfWrite as mn,shutdownTelemetry as mr,commitWip as mt,AGENT_ID_RE as n,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ni,installPrettyZodErrors as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,INLINE_RENDERABLE_EXTENSIONS as oi,isAllowedWorkspaceHostHeader as on,safeSubdir as or,buildSkillZip as ot,DEFAULT_CHECKPOINT_RETENTION as p,humanFormat as pi,isProjectRoot as pn,shadowGit as pr,commitUpstreamImport as pt,UiLockCollisionError as q,resolveCursorSpawnInvocation as qn,isJSONRPCResultResponse as qr,getMeter as qt,AGENT_WRITE_ORIGIN as r,DEFAULT_SERVER_HOST as ri,installTestLoggers as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,ORPHAN_MODES as si,isConfigDoc as sn,safetyCheckpoint as sr,buildStarterFolderFrontmatterYaml as st,AGENT_ID_MAX_LEN as t,CC1_CONTRACT_VERSION as ti,initTelemetry as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,SYSTEM_DOC_NAME as ui,isLoopbackAddress as un,saveVersion as ur,classifyFsPath as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,OK_PROJECT_MARKER as vi,listStarterPacks as vn,streamingProblemEvent as vr,contributorCount as vt,MANAGED_RENAME_ORIGIN as w,literal as wi,parseHocuspocusAuthToken as wn,tracedMkdirSync as wr,createLiveDerivedIndexExtension as wt,INSTALLED_AGENTS_SCHEMES as x,any$1 as xi,mountMcpAndApi as xn,tracedAppendFileSync as xr,createContentFilter as xt,HocuspocusAuthRejection as y,locateIssue as yi,loadPrincipal as yn,swapContributors as yr,createApiExtension as yt,STARTER_PACKS as z,registerAllTools as zn,writeStateManifest as zr,findEnclosingProjectRoot as zt};
|
|
3091
|
-
//# sourceMappingURL=dist-
|
|
3074
|
+
//# sourceMappingURL=dist-DCWvlpSX.mjs.map
|