@inkeep/open-knowledge 0.25.0-beta.9 → 0.25.1-beta.0
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/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/assets/skills/write-skill/SKILL.md +1 -1
- package/dist/cli.mjs +65 -65
- package/dist/constants-CgXx1dPb.mjs +2 -0
- package/dist/{dist-Bj79e9B6.mjs → dist-D13xYuEX.mjs} +47 -51
- package/dist/dist-D9WKY736.mjs +1 -0
- package/dist/{gh-detect-Ck0zE5NU.mjs → gh-detect-BcBj3YlE.mjs} +2 -2
- package/dist/{git-handle-DY9lXoT3-CfssnuIB.mjs → git-handle-Bhgrj9qX-DBwQr-02.mjs} +2 -2
- package/dist/git-handle-DjEtQkHv-DQXg1XhZ.mjs +1 -0
- package/dist/index.d.mts +758 -1
- package/dist/index.mjs +1 -1
- package/dist/init-BOHFI-M4.mjs +321 -0
- package/dist/init-CWlEXg63.mjs +1 -0
- package/dist/loader-BZIOGAPP.mjs +1 -0
- package/dist/{loader-1IrHrVRY.mjs → loader-ea54dQyy.mjs} +3 -3
- package/dist/{preview-qP8Vfz3W.mjs → preview-CLxs2bk2.mjs} +2 -2
- package/dist/preview-YrlSomd6.mjs +1 -0
- package/dist/public/assets/ActivityModeContent-mJH5LtOR.js +2 -0
- package/dist/public/assets/ConsentDialogBody-Bza0TMPd.js +2 -0
- package/dist/public/assets/DocumentContext-WluK-pvu.js +32 -0
- package/dist/public/assets/EnableSyncConfirmDialog-BWfcC03w.js +1 -0
- package/dist/public/assets/{GraphPanel-DiyMfzQg.js → GraphPanel-Cf9lwwnw.js} +3 -3
- package/dist/public/assets/ManagedArtifactProperties-BoAxNvK5.js +1 -0
- package/dist/public/assets/McpConsentDialogBody-DXwlUNR4.js +1 -0
- package/dist/public/assets/PropertyPanel-Bbn9RXvr.js +2 -0
- package/dist/public/assets/SettingsDialogBody-BVNxduDH.js +7 -0
- package/dist/public/assets/ShareBranchSwitchDialog-Bo95Aacz.js +1 -0
- package/dist/public/assets/ShareReceiveDialog-jEI9GD0l.js +1 -0
- package/dist/public/assets/ShareReceiveMissDialog-8HKZBtux.js +1 -0
- package/dist/public/assets/{SkillEditorActions-BsGotb40.js → SkillEditorActions-85awfZeZ.js} +1 -1
- package/dist/public/assets/SourceEditor-D0oQT5qb.js +2 -0
- package/dist/public/assets/{TerminalPanel-XlICQw5o.js → TerminalPanel-BNR82pgE.js} +2 -2
- package/dist/public/assets/{_baseFor-D25oCqSU.js → _baseFor-D774tcxR.js} +1 -1
- package/dist/public/assets/{agent-presence-BRmBPq78.js → agent-presence-C79Orlhd.js} +1 -1
- package/dist/public/assets/{arc-DHpQGPKi.js → arc-CbtK-u7K.js} +1 -1
- package/dist/public/assets/architecture-YZFGNWBL-BuVsq_Vy.js +1 -0
- package/dist/public/assets/{architectureDiagram-Q4EWVU46-Dl6zKdMi.js → architectureDiagram-Q4EWVU46-BEI0DR2f.js} +1 -1
- package/dist/public/assets/arrow-up-right-DoN2FmSd.js +1 -0
- package/dist/public/assets/auth-state-cache-CaiWuhtJ.js +11 -0
- package/dist/public/assets/{blockDiagram-DXYQGD6D-TTNbipzm.js → blockDiagram-DXYQGD6D-CvhaR3v1.js} +1 -1
- package/dist/public/assets/button-cneJOVxD.js +1 -0
- package/dist/public/assets/{c4Diagram-AHTNJAMY-DJ6_yNro.js → c4Diagram-AHTNJAMY-CGJ_dXh7.js} +1 -1
- package/dist/public/assets/{calendar-BefXYqrv.js → calendar-D62otKE3.js} +1 -1
- package/dist/public/assets/channel-DQ8biAJJ.js +1 -0
- package/dist/public/assets/check-Dqb-7gfx.js +1 -0
- package/dist/public/assets/checkbox-P04sbGVQ.js +1 -0
- package/dist/public/assets/chevron-down-D3nis7uo.js +1 -0
- package/dist/public/assets/chevron-left-C6Q_NKVx.js +1 -0
- package/dist/public/assets/chevron-right-BfmqRYl8.js +1 -0
- package/dist/public/assets/{chunk-2KRD3SAO-tPsWTtQ8.js → chunk-2KRD3SAO-CTZc4q6X.js} +1 -1
- package/dist/public/assets/{chunk-336JU56O-BDNF8ABQ.js → chunk-336JU56O-Df_WdTwV.js} +2 -2
- package/dist/public/assets/chunk-426QAEUC-Bmtezokd.js +1 -0
- package/dist/public/assets/{chunk-4BX2VUAB-B11p4CCh.js → chunk-4BX2VUAB-DdaeBv7j.js} +1 -1
- package/dist/public/assets/{chunk-4TB4RGXK-k8il4Vah.js → chunk-4TB4RGXK-Z_KF79WQ.js} +1 -1
- package/dist/public/assets/chunk-55IACEB6-BMw0jGoU.js +1 -0
- package/dist/public/assets/{chunk-5FUZZQ4R-BhDATrAC.js → chunk-5FUZZQ4R-BP1tPdP4.js} +1 -1
- package/dist/public/assets/{chunk-5PVQY5BW-7GSXpGpA.js → chunk-5PVQY5BW-DHmdYl18.js} +1 -1
- package/dist/public/assets/{chunk-67CJDMHE-DhsO5dA4.js → chunk-67CJDMHE-Dr8TgESK.js} +1 -1
- package/dist/public/assets/{chunk-7N4EOEYR-_OPnqGDq.js → chunk-7N4EOEYR-wyEzdjqa.js} +1 -1
- package/dist/public/assets/{chunk-AA7GKIK3-CmQNMaMq.js → chunk-AA7GKIK3-DwcoEi3L.js} +1 -1
- package/dist/public/assets/{chunk-BSJP7CBP-DRn1Q8qZ.js → chunk-BSJP7CBP-Bi10nqUB.js} +1 -1
- package/dist/public/assets/{chunk-CIAEETIT-B6L60eSe.js → chunk-CIAEETIT-BRhaZZvf.js} +1 -1
- package/dist/public/assets/{chunk-EDXVE4YY-TfqLQBKW.js → chunk-EDXVE4YY-Cdm2p7eD.js} +1 -1
- package/dist/public/assets/{chunk-ENJZ2VHE-CqUfmxZL.js → chunk-ENJZ2VHE-CtYN5PYG.js} +1 -1
- package/dist/public/assets/{chunk-FMBD7UC4-_M3xiFqk.js → chunk-FMBD7UC4-yxpni0iy.js} +1 -1
- package/dist/public/assets/{chunk-FOC6F5B3-R--gjWDw.js → chunk-FOC6F5B3-zU_D2qL3.js} +1 -1
- package/dist/public/assets/{chunk-ICPOFSXX-MhneOmo1.js → chunk-ICPOFSXX-B1LaL7po.js} +2 -2
- package/dist/public/assets/{chunk-K5T4RW27-kfFBI7dm.js → chunk-K5T4RW27-CMA0573G.js} +1 -1
- package/dist/public/assets/{chunk-KGLVRYIC-MGoiNxXR.js → chunk-KGLVRYIC-4qBf2hVO.js} +1 -1
- package/dist/public/assets/{chunk-LIHQZDEY-3OBi6RFi.js → chunk-LIHQZDEY-DLhCQB7m.js} +1 -1
- package/dist/public/assets/{chunk-ORNJ4GCN-D1jJqGHz.js → chunk-ORNJ4GCN-DYvOtc7p.js} +1 -1
- package/dist/public/assets/{chunk-OYMX7WX6-Dn8GoIJo.js → chunk-OYMX7WX6-Cb6J6ILi.js} +1 -1
- package/dist/public/assets/chunk-QZHKN3VN-D9Augrqb.js +1 -0
- package/dist/public/assets/{chunk-U2HBQHQK-Wd4MIHD7.js → chunk-U2HBQHQK-BQEFtvNE.js} +1 -1
- package/dist/public/assets/{chunk-X2U36JSP-DgR3BYDC.js → chunk-X2U36JSP-B0NFvVYj.js} +1 -1
- package/dist/public/assets/{chunk-XPW4576I-BIhGQhfc.js → chunk-XPW4576I-CWtaxsuf.js} +1 -1
- package/dist/public/assets/{chunk-YZCP3GAM-DfCU0Z-P.js → chunk-YZCP3GAM-wveZpL2J.js} +1 -1
- package/dist/public/assets/{chunk-ZZ45TVLE-Bml1MOax.js → chunk-ZZ45TVLE-DjoyvapL.js} +1 -1
- package/dist/public/assets/classDiagram-6PBFFD2Q-Bh_mU7DM.js +1 -0
- package/dist/public/assets/classDiagram-v2-HSJHXN6E-thFVFTz4.js +1 -0
- package/dist/public/assets/clone-CJvW7gHo.js +1 -0
- package/dist/public/assets/collapsible-iVWLn36m.js +1 -0
- package/dist/public/assets/config-context-CVpOcWSZ.js +1 -0
- package/dist/public/assets/config-provider-D-gGfmXm.js +4 -0
- package/dist/public/assets/{cose-bilkent-S5V4N54A-CIV0yZWV.js → cose-bilkent-S5V4N54A--ojmzpj3.js} +1 -1
- package/dist/public/assets/{cursor-CpjEfgnv.js → cursor-CGeB2PU5.js} +1 -1
- package/dist/public/assets/{dagre-BUnZfAns.js → dagre-D_jVclke.js} +1 -1
- package/dist/public/assets/{dagre-KV5264BT-Bscv1HQo.js → dagre-KV5264BT-LC6-Nebl.js} +1 -1
- package/dist/public/assets/desktop-bridge-types-C22Y6m5Y.js +1 -0
- package/dist/public/assets/{diagram-5BDNPKRD-QBP7yg8z.js → diagram-5BDNPKRD-HYhuDT0y.js} +1 -1
- package/dist/public/assets/{diagram-G4DWMVQ6-CMdeZ41j.js → diagram-G4DWMVQ6-CSvJiR_m.js} +1 -1
- package/dist/public/assets/{diagram-MMDJMWI5-DCz0ew8n.js → diagram-MMDJMWI5-CaR4m-x5.js} +1 -1
- package/dist/public/assets/{diagram-TYMM5635-zN9Dx1fB.js → diagram-TYMM5635-C2IGbfjW.js} +1 -1
- package/dist/public/assets/dialog-BiB39Lhy.js +45 -0
- package/dist/public/assets/dist-0Zj_lz7j.js +11 -0
- package/dist/public/assets/{dist-BdwnfcKi.js → dist-BEW6C_CZ.js} +1 -1
- package/dist/public/assets/dist-BVOt51sU.js +1 -0
- package/dist/public/assets/dist-BkxMNfFN.js +528 -0
- package/dist/public/assets/{dist-znFZQjzE.js → dist-BuoXuHTG.js} +1 -1
- package/dist/public/assets/dist-C0qRhuIN.js +1 -0
- package/dist/public/assets/{dist-CHEQzAl9.js → dist-CPpRuwFX.js} +1 -1
- package/dist/public/assets/{dist-3l3ADjEo.js → dist-CgYE3gek.js} +1 -1
- package/dist/public/assets/{dist-Dtxdqotp.js → dist-CkLidFHS.js} +1 -1
- package/dist/public/assets/{dist-E5KjgWw7.js → dist-D7I9jMga.js} +1 -1
- package/dist/public/assets/{dist-BgLh90uo2.js → dist-D8Itza26.js} +1 -1
- package/dist/public/assets/dist-D9WIglau.js +1 -0
- package/dist/public/assets/{dist-C3ftUzLd.js → dist-DI8cI4NP.js} +1 -1
- package/dist/public/assets/{dist-BZEgBj4N.js → dist-DPfhM7y8.js} +1 -1
- package/dist/public/assets/{dist-AQSp7Qij.js → dist-DQdOYnjt.js} +1 -1
- package/dist/public/assets/{dist-DWaLpHcz.js → dist-DVPtn9Zx.js} +1 -1
- package/dist/public/assets/dist-DfThKWJX.js +1 -0
- package/dist/public/assets/{dist-Bqo1ZTng.js → dist-Dg5nhLZ2.js} +1 -1
- package/dist/public/assets/{dist-KBKQayVB.js → dist-IEs1iCqd.js} +1 -1
- package/dist/public/assets/doc-hash-5OIPOG-G.js +1 -0
- package/dist/public/assets/documents-events-D064jVvV.js +1 -0
- package/dist/public/assets/{erDiagram-SMLLAGMA-CFPPEjz0.js → erDiagram-SMLLAGMA-D1J1j3Yx.js} +1 -1
- package/dist/public/assets/file-tree-adapter-Bg8FQvOB.js +1 -0
- package/dist/public/assets/{flatten-sS3L8FSH.js → flatten-CaB4Oqne.js} +1 -1
- package/dist/public/assets/{flowDiagram-DWJPFMVM-DOjygKY4.js → flowDiagram-DWJPFMVM-CMNxv96M.js} +1 -1
- package/dist/public/assets/{ganttDiagram-T4ZO3ILL-Cox3d5Yp.js → ganttDiagram-T4ZO3ILL-DSJ51gJ8.js} +1 -1
- package/dist/public/assets/git-branch-DtntyZcb.js +1 -0
- package/dist/public/assets/gitGraph-7Q5UKJZL-t28UFBv3.js +1 -0
- package/dist/public/assets/{gitGraphDiagram-UUTBAWPF-BXvw3bmB.js → gitGraphDiagram-UUTBAWPF-eqtXz7Hn.js} +1 -1
- package/dist/public/assets/{graphlib-FYrXvm7X.js → graphlib-CgeMr8SV.js} +1 -1
- package/dist/public/assets/index-BG8OZejR.js +2003 -0
- package/dist/public/assets/index-D53MQUCD.css +1 -0
- package/dist/public/assets/info-B_9IOYHV.js +1 -0
- package/dist/public/assets/info-OMHHGYJF-B1OgcQSI.js +1 -0
- package/dist/public/assets/{infoDiagram-42DDH7IO-Bk54rrHD.js → infoDiagram-42DDH7IO-CB_Gw_tn.js} +1 -1
- package/dist/public/assets/{input-DkQ8Zmzd.js → input-D0MSkqYi.js} +1 -1
- package/dist/public/assets/{isEmpty-DKKUMPPC.js → isEmpty-DA9OVgr8.js} +1 -1
- package/dist/public/assets/isSymbol-BR3mCdgP.js +1 -0
- package/dist/public/assets/{ishikawaDiagram-UXIWVN3A-Bc3G_190.js → ishikawaDiagram-UXIWVN3A-Cnz_ITKx.js} +1 -1
- package/dist/public/assets/{journeyDiagram-VCZTEJTY-CLrtuKm7.js → journeyDiagram-VCZTEJTY-3INdsNOc.js} +1 -1
- package/dist/public/assets/{kanban-definition-6JOO6SKY-DwQiIK5Z.js → kanban-definition-6JOO6SKY-BXFLNQXS.js} +1 -1
- package/dist/public/assets/keyboard-shortcuts-DiiTkD4P.js +1 -0
- package/dist/public/assets/label-hTzLGQhh.js +1 -0
- package/dist/public/assets/{line-Dk1foLQO.js → line-DXPDJkMA.js} +1 -1
- package/dist/public/assets/{linear-D7qoVA2u.js → linear-BmFs-_tv.js} +1 -1
- package/dist/public/assets/loader-circle-CiIO3Fk-.js +1 -0
- package/dist/public/assets/{mermaid-parser.core-WlD4T62P.js → mermaid-parser.core-B0CngrEV.js} +2 -2
- package/dist/public/assets/{mermaid.core-CLOkRfd8.js → mermaid.core-BKAbpHOL.js} +3 -3
- package/dist/public/assets/{mindmap-definition-QFDTVHPH-DYJRBCQs.js → mindmap-definition-QFDTVHPH-Bm9VbqSR.js} +1 -1
- package/dist/public/assets/miss-dialog-store-Ay7SdCdU.js +1 -0
- package/dist/public/assets/{now-C9pOxV0O.js → now-Cnt3xXdO.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-DBkxdYp_.js → open-managed-artifact-tab-TH1tyrz4.js} +2 -2
- package/dist/public/assets/{ordinal-BLFf0NQg.js → ordinal-Ca5DZ3xr.js} +1 -1
- package/dist/public/assets/packet-4T2RLAQJ-BPKm0rz4.js +1 -0
- package/dist/public/assets/panel-BH2RZRZQ.js +1 -0
- package/dist/public/assets/pending-receive-nav-store-BV9CpxST.js +1 -0
- package/dist/public/assets/pie-ZZUOXDRM-C37JdEN8.js +1 -0
- package/dist/public/assets/{pieDiagram-DEJITSTG-BtJ94Yhu.js → pieDiagram-DEJITSTG-0LpqYimt.js} +1 -1
- package/dist/public/assets/project-paths-Dvd83Cnz.js +1 -0
- package/dist/public/assets/prop-types-PwAyvfNz.js +1 -0
- package/dist/public/assets/{propagation-api-CR2CQW4x.js → propagation-api-BHhJitgG.js} +1 -1
- package/dist/public/assets/{quadrantDiagram-34T5L4WZ-B8wf6FVG.js → quadrantDiagram-34T5L4WZ-D4bhJC5O.js} +1 -1
- package/dist/public/assets/radar-PYXPWWZC-BqODBTH1.js +1 -0
- package/dist/public/assets/radio-group-1_2tsQbc.js +1 -0
- package/dist/public/assets/receive-store-z_JiltPn.js +2 -0
- package/dist/public/assets/{reduce-CrpTR7cO.js → reduce-BkAOm6E5.js} +1 -1
- package/dist/public/assets/refresh-cw-EVALIeLp.js +1 -0
- package/dist/public/assets/{requirementDiagram-MS252O5E-PrH6Wk-f.js → requirementDiagram-MS252O5E-CrZIuUV5.js} +1 -1
- package/dist/public/assets/{sankeyDiagram-XADWPNL6-DuDWdyws.js → sankeyDiagram-XADWPNL6-CDJh0Hcw.js} +1 -1
- package/dist/public/assets/{selection-context-vh0MmCBb.js → selection-context-DG6CuE_n.js} +1 -1
- package/dist/public/assets/{sequenceDiagram-FGHM5R23-BvF_oV_w.js → sequenceDiagram-FGHM5R23-Crf8F-0v.js} +1 -1
- package/dist/public/assets/share-metadata-rows-COyU9rhn.js +1 -0
- package/dist/public/assets/skill-actions-DmQL_HGK.js +1 -0
- package/dist/public/assets/skill-scope-Bt2TwqtA.js +1 -0
- package/dist/public/assets/skills-api-T8UMKFuI.js +1 -0
- package/dist/public/assets/{src-DEzC9TbA.js → src-60u1_sM3.js} +1 -1
- package/dist/public/assets/{stateDiagram-FHFEXIEX-BvOoHTsD.js → stateDiagram-FHFEXIEX-CoUQpm-3.js} +1 -1
- package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-BM5GAHWg.js +1 -0
- package/dist/public/assets/target-navigation-intent-idRDy9hG.js +1 -0
- package/dist/public/assets/{telemetry-impl-BM7BnAv2.js → telemetry-impl-6qacFa_I.js} +2 -2
- package/dist/public/assets/telemetry-startup-ZaSL-kj2.js +1 -0
- package/dist/public/assets/{textarea-BQFFQ9_l.js → textarea-CUjvX3CU.js} +1 -1
- package/dist/public/assets/{timeline-definition-GMOUNBTQ-_VzX4HAF.js → timeline-definition-GMOUNBTQ-CiQZrQPS.js} +1 -1
- package/dist/public/assets/toggle-group-IN7Np0Is.js +1 -0
- package/dist/public/assets/tooltip-C9Dd0rIc.js +1 -0
- package/dist/public/assets/treeView-SZITEDCU-ByrE6Vcb.js +1 -0
- package/dist/public/assets/treemap-W4RFUUIX-BcYBme24.js +1 -0
- package/dist/public/assets/triangle-alert-r1Ou0VrE.js +1 -0
- package/dist/public/assets/{typing-burst-detector-BT98lJOb.js → typing-burst-detector-D-XypHNF.js} +3 -3
- package/dist/public/assets/{vennDiagram-DHZGUBPP-BiS2w_m-.js → vennDiagram-DHZGUBPP-CoqI8iiY.js} +1 -1
- package/dist/public/assets/wardley-RL74JXVD-DDdV8nDz.js +1 -0
- package/dist/public/assets/{wardleyDiagram-NUSXRM2D-BgB2gOdF.js → wardleyDiagram-NUSXRM2D-6pXCRu0Y.js} +1 -1
- package/dist/public/assets/{xychartDiagram-5P7HB3ND-DIurDFny.js → xychartDiagram-5P7HB3ND-C3ELwBEZ.js} +1 -1
- package/dist/public/index.html +74 -58
- package/dist/{repair-launch-json-B2igGItE.mjs → repair-launch-json-DsDdzz5S.mjs} +2 -2
- package/dist/{repair-mcp-configs-B0YDgxKo.mjs → repair-mcp-configs-CAw5k6Ut.mjs} +2 -2
- package/dist/repair-skills-BbCNUguw.mjs +3 -0
- package/dist/repair-skills-Bj4d8jaz.mjs +1 -0
- package/dist/server-lock-GuuouVft-BG2sFhIR.mjs +1 -0
- package/dist/{server-lock-CN2YHwpP-BYuwTc93.mjs → server-lock-iLcBw_q0-CPFOrsBn.mjs} +186 -184
- package/dist/src-7DlZEyGh.mjs +3 -0
- package/dist/start-CMWosjhu.mjs +3 -0
- package/dist/start-ame0DmVr.mjs +1 -0
- package/dist/write-project-skill-4cQ_oGJO.mjs +36 -0
- package/package.json +1 -1
- package/scripts/aggregate-tolerance-class-fires.ts +15 -0
- package/scripts/build-config-schema.mjs +69 -0
- package/scripts/postinstall.mjs +19 -0
- package/scripts/probe-exec.ts +8 -0
- package/scripts/probe-read-document.ts +12 -0
- package/dist/constants-BwIQxzxy.mjs +0 -2
- package/dist/dist-DUXDeyBp.mjs +0 -1
- package/dist/git-handle-DdgvPBh6-C80s8fFN.mjs +0 -1
- package/dist/init-BzdKgHZr.mjs +0 -321
- package/dist/init-HqjPAvpy.mjs +0 -1
- package/dist/loader-BEm7pFin.mjs +0 -1
- package/dist/preview-BoSe54Y5.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-QvRIx_do.js +0 -2
- package/dist/public/assets/ConsentDialogBody-CPX75E6Q.js +0 -2
- package/dist/public/assets/DocumentContext-zL3ZbwDo.js +0 -34
- package/dist/public/assets/ManagedArtifactProperties-OxkUY14x.js +0 -1
- package/dist/public/assets/McpConsentDialogBody-Dr_AIi2H.js +0 -1
- package/dist/public/assets/PropertyPanel-D9A27c2E.js +0 -2
- package/dist/public/assets/SettingsDialogBody-cotnwVMw.js +0 -7
- package/dist/public/assets/SourceEditor-BZ3cbLjs.js +0 -2
- package/dist/public/assets/architecture-YZFGNWBL-0pWnpYMK.js +0 -1
- package/dist/public/assets/button-DGf25ccp.js +0 -1
- package/dist/public/assets/channel-ClECMrL_.js +0 -1
- package/dist/public/assets/checkbox-EGJP9xna.js +0 -1
- package/dist/public/assets/chevron-down-CzFz_0zd.js +0 -1
- package/dist/public/assets/chevron-left-Bb3WBx0B.js +0 -1
- package/dist/public/assets/chevron-right-jyIhGBkw.js +0 -1
- package/dist/public/assets/chunk-426QAEUC-UlKin18B.js +0 -1
- package/dist/public/assets/chunk-55IACEB6-maKdi3q_.js +0 -1
- package/dist/public/assets/chunk-QZHKN3VN-DUJDGGgJ.js +0 -1
- package/dist/public/assets/classDiagram-6PBFFD2Q-C9zXtHUq.js +0 -1
- package/dist/public/assets/classDiagram-v2-HSJHXN6E-BLmW_Iw2.js +0 -1
- package/dist/public/assets/clone-1iKEKVKL.js +0 -1
- package/dist/public/assets/collapsible-CjgfK1G5.js +0 -1
- package/dist/public/assets/config-context-DhhN0rlf.js +0 -1
- package/dist/public/assets/config-validation-events-yB2QWKKJ.js +0 -11
- package/dist/public/assets/dialog-CIq9aQLf.js +0 -45
- package/dist/public/assets/dist-BRGUidv4.js +0 -526
- package/dist/public/assets/dist-BXd_K33i.js +0 -1
- package/dist/public/assets/dist-ICp_3rWY.js +0 -1
- package/dist/public/assets/documents-events-DA8Q5ICz.js +0 -11
- package/dist/public/assets/file-tree-adapter-CP3Xa3us.js +0 -1
- package/dist/public/assets/gitGraph-7Q5UKJZL-DNLE-2Tt.js +0 -1
- package/dist/public/assets/index-CG7gf_6X.css +0 -1
- package/dist/public/assets/index-CoukPsjj.js +0 -2004
- package/dist/public/assets/info-OMHHGYJF-BiaOigFV.js +0 -1
- package/dist/public/assets/isSymbol-BgthEULk.js +0 -1
- package/dist/public/assets/keyboard-shortcuts-DOkzBlgc.js +0 -1
- package/dist/public/assets/label-DyT4OD9H.js +0 -1
- package/dist/public/assets/navigation-targets-DNRja8Z0.js +0 -1
- package/dist/public/assets/packet-4T2RLAQJ-v1yqEdTP.js +0 -1
- package/dist/public/assets/panel-BbrtnF__.js +0 -1
- package/dist/public/assets/pie-ZZUOXDRM-pmbX_rAr.js +0 -1
- package/dist/public/assets/project-paths-CcPGtodV.js +0 -1
- package/dist/public/assets/prop-types-C-aZftyS.js +0 -1
- package/dist/public/assets/radar-PYXPWWZC-CQRfh76o.js +0 -1
- package/dist/public/assets/radio-group-CFPLlVag.js +0 -1
- package/dist/public/assets/skill-actions-Sc4IN52j.js +0 -1
- package/dist/public/assets/skills-api-ts3L80AV.js +0 -1
- package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-B02IOISZ.js +0 -1
- package/dist/public/assets/target-navigation-intent-CIKQ1Hj-.js +0 -1
- package/dist/public/assets/telemetry-startup-Pz1ro4a2.js +0 -1
- package/dist/public/assets/toggle-group-Bc5FaFo3.js +0 -1
- package/dist/public/assets/tooltip-DiL7DBhT.js +0 -1
- package/dist/public/assets/treeView-SZITEDCU-iExObZ_v.js +0 -1
- package/dist/public/assets/treemap-W4RFUUIX-B-jRsyTq.js +0 -1
- package/dist/public/assets/wardley-RL74JXVD-DGsNLwY0.js +0 -1
- package/dist/repair-skills-Cv_2HgEN.mjs +0 -3
- package/dist/repair-skills-XaoNNrHC.mjs +0 -1
- package/dist/server-lock-8Lv6A-Xa-xTK-ENFB.mjs +0 -1
- package/dist/src-DD9KqmOQ.mjs +0 -3
- package/dist/start-B4zA8vv3.mjs +0 -1
- package/dist/start-DYPIgVG4.mjs +0 -3
- package/dist/write-project-skill-HXJW0bDK.mjs +0 -36
- /package/dist/public/assets/{ActivityPanelDiffView-TEHR9A38.js → ActivityPanelDiffView-BPrpOwiv.js} +0 -0
- /package/dist/public/assets/{__vite-browser-external-DimdflAw.js → __vite-browser-external-DfbEpKPK.js} +0 -0
- /package/dist/public/assets/{array-CXyn2wAU.js → array-DrKFfLpK.js} +0 -0
- /package/dist/public/assets/{clike-kHME1xsl.js → clike-CY4jFeI9.js} +0 -0
- /package/dist/public/assets/{colors-DOVRXUpv.js → colors-BwB-X4pV.js} +0 -0
- /package/dist/public/assets/{cytoscape.esm-DGKrBfTH.js → cytoscape.esm-B72MXB0V.js} +0 -0
- /package/dist/public/assets/{defaultLocale-CIVmmKdD.js → defaultLocale-DEFJZ-43.js} +0 -0
- /package/dist/public/assets/{diff-B_7QuALZ.js → diff-VsLDmRbo.js} +0 -0
- /package/dist/public/assets/{dist-BAzUe-Rb.js → dist-BdpTVkuI.js} +0 -0
- /package/dist/public/assets/{dist-ug68MPTZ.js → dist-CbgmYSt6.js} +0 -0
- /package/dist/public/assets/{external-link-Bc6KvE1i.js → external-link-ChNdN5KK.js} +0 -0
- /package/dist/public/assets/{file-tree-rename-validation-BqGkSO9-.js → file-tree-rename-validation-BkATWpiZ.js} +0 -0
- /package/dist/public/assets/{format-Fsxus_sZ.js → format-CFXD031r.js} +0 -0
- /package/dist/public/assets/{go-DlHfV6Cv.js → go-CJnIK4Uo.js} +0 -0
- /package/dist/public/assets/{init-DAmDTHXL.js → init-20ACqh4a.js} +0 -0
- /package/dist/public/assets/{isObjectLike-0yTn5bno.js → isObjectLike-DURfeUEd.js} +0 -0
- /package/dist/public/assets/{katex-gTwLOSI2.js → katex-BunQWEOH.js} +0 -0
- /package/dist/public/assets/{lua-Cpo6SgEb.js → lua-BTUOHEPy.js} +0 -0
- /package/dist/public/assets/{mcp-consent-store-Q_heVQ86.js → mcp-consent-store-Bx7YkTj-.js} +0 -0
- /package/dist/public/assets/{min-CGFu6QbN.js → min-cXlECwx8.js} +0 -0
- /package/dist/public/assets/{panzoom.es-1vRDHCmL.js → panzoom.es-BPpDWM66.js} +0 -0
- /package/dist/public/assets/{path-1iyJ-o9O.js → path-Bbctax8p.js} +0 -0
- /package/dist/public/assets/{pdf-BjE4l7oX.js → pdf-Cz6vffXS.js} +0 -0
- /package/dist/public/assets/{pdf.worker-CU7PVDgr.js → pdf.worker-CUSszLRa.js} +0 -0
- /package/dist/public/assets/{perl-uq5LpsPX.js → perl-CSl7RrAK.js} +0 -0
- /package/dist/public/assets/{properties-DuLkwqft.js → properties-KpJMIKzZ.js} +0 -0
- /package/dist/public/assets/{r-DcEDABBa.js → r-DFsc7DIH.js} +0 -0
- /package/dist/public/assets/{rough.esm-Bk-GM2I8.js → rough.esm-CTApjP9q.js} +0 -0
- /package/dist/public/assets/{ruby-C6V5dDsD.js → ruby-dZPnOz8h.js} +0 -0
- /package/dist/public/assets/{shell-CVvCNjui.js → shell-CYSl653a.js} +0 -0
- /package/dist/public/assets/{sql-CQQBnjZX.js → sql-BfVjfYES.js} +0 -0
- /package/dist/public/assets/{src-C3imF5Zq.js → src-BjEzLuzr.js} +0 -0
- /package/dist/public/assets/{startup-marks-CWTDb1CP.js → startup-marks-DdMtjWR-.js} +0 -0
- /package/dist/public/assets/{stex-coA_FIxI.js → stex-DYxKXJZx.js} +0 -0
- /package/dist/public/assets/{swift-BBOV2SBg.js → swift-DjBuuwmF.js} +0 -0
- /package/dist/public/assets/{toml-lQGk0tnp.js → toml-C3_Svn60.js} +0 -0
- /package/dist/public/assets/{trace-api-MhJXZpsM.js → trace-api-D6fqC5Nw.js} +0 -0
- /package/dist/public/assets/{w3c-keyname-beU76Hfb.js → w3c-keyname-CHcJEDvG.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$a as ZodOptional$1,$i as reattachLeadingDocBoundary,$n as SkillInstallStateSuccessSchema,$r as assertNeverProblemType,$t as MANAGED_ARTIFACT_PREFIX_TEMPLATE,A as ApiConfigSuccessSchema,Aa as EXECUTABLE_BLOCKLIST_EXTENSIONS,Ai as isBranchNotFoundGitError,An as SaveVersionRequestSchema,Ao as prettifyError,Ar as TEMPLATE_NAME_REGEX,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Ba as detectRemovedKeys,Bi as parseFrontmatterYaml,Bn as ShareConstructUrlRequestSchema,Br as TestFlushGitSuccessSchema,Bt as InstalledSkillsSchema,C as AgentPatchSuccessSchema,Ca as ConfigSchema$1,Ci as formatFileSize,Cn as SKILL_STATE_REL,Co as meta$1,Cr as SyncConflictsSuccessSchema,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Da as DEFAULT_LOGS_MAX_BYTES,Di as getWikiLinkText,Do as parseAsync,Dr as SyncTriggerRequestSchema,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ea as DEFAULT_EMBEDDINGS_MODEL,Ei as getParseHealth,En as SKILL_TARGETS_REL,Eo as parse$1,Er as SyncStatusSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as isOrphanMode,Fn as SeedApplySuccessSchema,Fr as TemplateMoveRequestSchema,Ft as HubsSuccessSchema,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ga as mediaKindForSidebarAssetExtension,Gi as parseSkillTargets,Gn as SharePublishResponseSchema,Gr as TrashCleanupSuccessSchema,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1ServerInfoPayloadSchema,Ha as isKnownConfigError,Hi as parseInstalledSkills,Hn as SharePublishNameCheckResponseSchema,Hr as TestRescanFilesSuccessSchema,Ht as LinkGraphSuccessSchema,I as BrokenLinkSchema,Ia as SANDBOXED_HTML_CSP,Ii as isValidBranchName,In as SeedListPacksSuccessSchema,Ir as TemplateMoveSuccessSchema,It as INSTALLED_SKILLS_REL,J as CC1_CONTRACT_VERSION,Ja as validatePatchScopes,Ji as previewEmbedFence,Jn as SkillFileGetSuccessSchema,Jr as UploadRequestSchema,Jt as LocalOpEmbeddingsMutationSuccessSchema,K as CC1_CHANNEL_DISK_ACK,Ka as normalizeAttachmentFolderPath,Ki as parseTemplateFile,Kn as SkillDeleteSuccessSchema,Kr as UA_PATTERNS,Kt as LocalOpAuthStatusSuccessSchema,L as CC1BranchSwitchedPayloadSchema,La as SANDBOXED_HTML_EXTENSIONS,Li as managedArtifactDocNameFromContentTarget,Ln as SeedPlanSuccessSchema,Lr as TemplatePutRequestSchema,Lt as InstallSkillRequestSchema,M as BacklinksSuccessSchema,Ma as LINKABLE_ASSET_EXTENSIONS,Mi as isHiddenDocName,Mn as SearchRequestSchema,Mo as defineLazy,Mr as TagsListSuccessSchema,N as BranchInfoResponseSchema,Na as LOCAL_DIR,Nn as SearchSuccessSchema,No as normalizeParams,Nr as TemplateDeleteSuccessSchema,Nt as HistorySuccessSchema,O as AgentWriteRequestSchema,Oa as DEFAULT_SPANS_MAX_BYTES,Oi as iconFromClientName,On as SUPPORTED_DOC_EXTENSIONS,Oo as safeParse$1,Or as SyncTriggerSuccessSchema,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pa as OK_PROJECT_MARKER,Pi as isManagedArtifactDocName,Pn as SeedApplyRequestSchema,Po as $constructor,Pr as TemplateGetSuccessSchema,Pt as HistoryVersionSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qi as readFmMap,Qn as SkillInstallRequestSchema,Qr as applyPatchToFm,Qt as MANAGED_ARTIFACT_PREFIX_SKILL,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ra as addConfigSpanEvent,Ri as mergeThreeWay,Rn as SemanticIndexStatusSchema,Rr as TemplatePutSuccessSchema,Rt as InstallSkillSuccessSchema,S as AgentPatchRequestSchema,Sa as CONFIG_SCHEMA_MAJOR_PATH,Si as fnv1aDigest,Sn as SKILL_NAME_REGEX,So as describe$1,Sr as SyncConflictContentSuccessSchema,St as EDITOR_PROJECT_SKILL_ROOT,T as AgentUndoSuccessSchema,Ta as DEFAULT_EMBEDDINGS_BASE_URL,Ti as getHeadingSlug,Tn as SKILL_STATE_VERSION_RE,To as $ZodType,Tr as SyncResolveConflictSuccessSchema,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ua as isValidAttachmentFolderPath,Ui as parseManagedArtifactName,Un as SharePublishOwnersResponseSchema,Ur as TestResetSuccessSchema,Ut as LocalOpAuthEmptySuccessSchema,V as CC1DiskAckPayloadSchema,Va as humanFormat,Vi as parseGlobalSkillBundleDoc,Vn as ShareConstructUrlResponseSchema,Vr as TestRescanBacklinksSuccessSchema,Vt as LINEAGE_EPOCH_KEY,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wa as locateIssue,Wi as parseProjectSkillBundleDoc,Wn as SharePublishRequestSchema,Wr as TrashCleanupRequestSchema,Wt as LocalOpAuthHostRequestSchema,X as CONFIG_DOC_NAMES,Xa as withConfigSpanSync,Xi as projectMergeBoundarySpace,Xn as SkillFilePutSuccessSchema,Xr as applyFastDiff,Xt as LocalOpOkInitRequestSchema,Y as CLIENT_VERSION_HEADER,Ya as withConfigSpan,Yi as projectFull,Yn as SkillFilePutRequestSchema,Yr as WorkspaceSuccessSchema,Yt as LocalOpEmbeddingsSetKeyRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Za as require_dist$1,Zi as projectSkillContentDocName,Zn as SkillGetSuccessSchema,Zr as applyIncrementalDiff,Zt as LocalOpOkInitResponseSchema,_ as AGENT_ICON_COLORS,_a as withFences,_i as emptyInstalledSkills,_n as RenamePathSuccessSchema,_o as unknown,_r as SkillUpdateSuccessSchema,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as serializeFrontmatterMap,ai as composeTemplateFile,an as MetricsReconciliationSuccessSchema,ao as custom,ar as SkillRestoreRequestSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,ba as Fragment,bi as expandTagToHierarchy,bn as RollbackSuccessSchema,bo as toJSONSchema,br as StreamingProblemEventSchema,c as isValidLockPid,ci as createCodeFenceTracker,cn as PREVIEW_EMBED_STARTERS,co as literal,cr as SkillStateSchema,ct as CreatePageSuccessSchema,da as stripFrontmatter,di as createWorkspaceSearchDocument,dn as PROTOCOL_VERSION,do as object$1,dr as SkillTargetsPutRequestSchema,ea as renderInventoryFooter,ei as classifyGitAuthError,en as MANAGED_ARTIFACT_SCOPES,eo as _enum,er as SkillInstallSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fa as tagsMatchingPrefix,fi as defaultScheduler,fn as PageHeadingsSuccessSchema,fo as optional,fr as SkillTargetsPutSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as validateDocName,gi as emitToleranceFire,gn as RenamePathRequestSchema,go as union,gr as SkillUpdateRequestSchema,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as unwrapFrontmatterFences,hi as displayNameFromClientName,hn as ProblemDetailsSchema,ho as string,hr as SkillUninstallSuccessSchema,ht as DeletePathSuccessSchema,ia as searchWorkspaceCorpus,ii as colorFromSeed,in as MetricsParseHealthSuccessSchema,io as boolean,ir as SkillPutSuccessSchema,it as ClientLogsSuccessSchema,j as BacklinkCountsSuccessSchema,ja as INLINE_RENDERABLE_EXTENSIONS,ji as isFrontmatterValueEmpty,jn as SaveVersionSuccessSchema,jo as clone,jr as TagsForNameSuccessSchema,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ka as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,ki as instantiateDoc,kn as SYSTEM_DOC_NAME,ko as safeParseAsync$1,kr as TEMPLATE_IDENTITY_KEY,kt as FrontmatterPatchRequestSchema,la as skillLiveDocName,li as createTagInTextRegex,ln as PREVIEW_THEME_TOKENS,lo as looseObject,lr as SkillTargetEditorSchema,m as releaseServerLock,ma as toWikiLinkSlug,mi as detectFmRegion,mn as PrincipalSuccessSchema,mo as record,mr as SkillUninstallRequestSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as resolveInternalHref,ni as classifyWikiLinkTarget,nn as MarkdownManager,nr as SkillMoveSuccessSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as setToleranceTelemetryHook,oi as containsXmlTag,on as ORPHAN_MODES,oo as discriminatedUnion,or as SkillRestoreSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as toBridgeInvariantLog,pi as detectAppliedToleranceClasses,pn as PagesSuccessSchema,po as preprocess,pr as SkillTargetsSchema,pt as DeadLinksSuccessSchema,q as CC1_CHANNEL_SERVER_INFO,qa as toConfigIssue,qi as prependFrontmatter,qn as SkillFileDeleteSuccessSchema,qr as UploadAssetSuccessSchema,qt as LocalOpCloneRequestSchema,ra as resolveSkillBundleWikiTarget,rn as MetricsAgentPresenceSuccessSchema,ro as array,rr as SkillPutRequestSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as sharedExtensions,si as createBasenameIndex,sn as OrphansSuccessSchema,so as intersection,sr as SkillScopeSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as resolveAssetProjectPath,ti as classifyMarkdownHref,tn as MCP_SERVER_NAME,to as _null,tr as SkillMoveRequestSchema,tt as CheckoutRequestSchema,u as readProcessLock,ua as splitLeadingDocBoundary,ui as createWorkspaceSearchCorpus,un as PROJECT_SKILL_EDITOR_IDS,uo as number,ur as SkillTargetsGetSuccessSchema,va as getSchema,vi as emptySkillState,vn as RescueListSuccessSchema,vr as SkillsListSuccessSchema,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wa as DEFAULT_DEDUP_MODE,wi as getAgentCanonicalDescriptors,wn as SKILL_STATE_TARGETS,wo as $ZodObject,wr as SyncResolveConflictRequestSchema,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as ASSET_EXTENSIONS,xi as extractFrontmatterTags,xn as SKILL_CONTENT_ROOT,xr as SuggestLinksSuccessSchema,xt as EDITOR_PROJECT_CONFIG_PATH,y as AdvisoryWarningSchema,ya as PluginKey,yi as encodeShareUrl,yn as RollbackRequestSchema,yo as datetime,yr as SpawnCursorSuccessSchema,yt as DuplicatePathSuccessSchema,z as CC1ConfigValidationRejectedPayloadSchema,za as applyPatchToDocument,zi as normalizeBridge,zn as ServerInfoSuccessSchema,zr as TemplatesListSuccessSchema,zt as InstalledAgentsSuccessSchema}from"./server-lock-CN2YHwpP-BYuwTc93.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BQ4-CT8p.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-DY9lXoT3-CfssnuIB.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DHter9G3.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DigWkxW2.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-D6YUa1Xl.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-2lBQUjKO.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import Crypto from"crypto";import crypto$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{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),g=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 g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${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 g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.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 g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}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 g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. 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(`
|
|
1
|
+
import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CLIENT_VERSION_HEADER,$a as locateIssue,$i as parseSkillTargets,$n as SkillDeleteSuccessSchema,$r as UA_PATTERNS,$t as LocalOpEmbeddingsSetKeyRequestSchema,A as AgentWriteMdRequestSchema,Aa as ASSET_EXTENSIONS,Ai as formatFileSize,An as SKILL_STATE_VERSION_RE,Ao as describe$1,Ar as SyncConflictsSuccessSchema,At as FolderConfigPutRequestSchema,B as BrokenLinkSchema,Ba as INLINE_RENDERABLE_EXTENSIONS,Bn as SeedApplySuccessSchema,Bo as defineLazy,Br as TemplateDeleteSuccessSchema,Bt as INSTALLED_SKILLS_REL,C as AdvisoryWarningSchema,Ca as toWikiLinkSlug,Ci as emitToleranceFire,Cn as RescueListSuccessSchema,Co as string,Cr as SkillUpdateRequestSchema,Ct as DuplicatePathSuccessSchema,D as AgentPatchSuccessSchema,Da as getSchema,Di as expandTagToHierarchy,Dn as SKILL_NAME_REGEX,Do as datetime,Dr as StreamingProblemEventSchema,Dt as EmbedDetectSuccessSchema,E as AgentPatchRequestSchema,Ea as withFences,Ei as encodeShareUrl,En as SKILL_CONTENT_ROOT,Er as SpawnCursorSuccessSchema,Et as EDITOR_PROJECT_SKILL_ROOT,F as BacklinkCountsSuccessSchema,Fa as DEFAULT_EMBEDDINGS_MODEL,Fi as iconFromClientName,Fn as SaveVersionRequestSchema,Fo as parseAsync,Fr as SyncTriggerSuccessSchema,Ft as FrontmatterValueSchema,G as CC1DiskAckPayloadSchema,Ga as SANDBOXED_HTML_CSP,Gi as managedArtifactDocNameFromContentTarget,Gn as ShareConstructUrlRequestSchema,Gr as TemplatePutSuccessSchema,Gt as LINEAGE_EPOCH_KEY,H as CC1ConfigIgnoreNestedErrorPayloadSchema,Ha as LOCAL_DIR,Hi as isOrphanMode,Hn as SeedPlanSuccessSchema,Ho as $constructor,Hr as TemplateMoveRequestSchema,Ht as InstallSkillSuccessSchema,I as BacklinksSuccessSchema,Ia as DEFAULT_LOGS_MAX_BYTES,Ii as instantiateDoc,In as SaveVersionSuccessSchema,Io as safeParse$1,Ir as TEMPLATE_IDENTITY_KEY,J as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ja as applyPatchToDocument,Ji as parseFrontmatterYaml,Jn as SharePublishOwnersResponseSchema,Jr as TestRescanBacklinksSuccessSchema,Jt as LocalOpAuthHostRequestSchema,K as CC1ServerInfoPayloadSchema,Ka as SANDBOXED_HTML_EXTENSIONS,Ki as mergeThreeWay,Kn as ShareConstructUrlResponseSchema,Kr as TemplatesListSuccessSchema,Kt as LinkGraphSuccessSchema,L as BranchInfoResponseSchema,La as DEFAULT_SPANS_MAX_BYTES,Li as isBranchNotFoundGitError,Ln as SearchRequestSchema,Lo as safeParseAsync$1,Lr as TEMPLATE_NAME_REGEX,Lt as HistorySuccessSchema,M as AgentWriteRequestSchema,Ma as ConfigSchema$1,Mi as getHeadingSlug,Mo as $ZodObject,Mr as SyncResolveConflictSuccessSchema,Mt as ForwardLinksSuccessSchema,N as AgentWriteSuccessSchema,Na as DEFAULT_DEDUP_MODE,Ni as getParseHealth,Nn as SUPPORTED_DOC_EXTENSIONS,No as $ZodType,Nr as SyncStatusSchema,Nt as FrontmatterPatchRequestSchema,O as AgentUndoRequestSchema,Oa as PluginKey,Oi as extractFrontmatterTags,On as SKILL_STATE_REL,Oo as toJSONSchema,Or as SuggestLinksSuccessSchema,Ot as EmptyRequestSchema,P as ApiConfigSuccessSchema,Pa as DEFAULT_EMBEDDINGS_BASE_URL,Pi as getWikiLinkText,Pn as SYSTEM_DOC_NAME,Po as parse$1,Pr as SyncTriggerRequestSchema,Pt as FrontmatterPatchSuccessSchema,Q as CC1_CONTRACT_VERSION,Qa as isValidAttachmentFolderPath,Qi as parseProjectSkillBundleDoc,Qn as ShareTargetStatusResponseSchema,Qr as TrashCleanupSuccessSchema,Qt as LocalOpEmbeddingsMutationSuccessSchema,R as BridgeInvariantViolationError,Ra as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,Ri as isFrontmatterValueEmpty,Rn as SearchSuccessSchema,Ro as prettifyError,Rr as TagsForNameSuccessSchema,Rt as HistoryVersionSuccessSchema,Sa as toBridgeInvariantLog,Si as displayNameFromClientName,Sn as RenamePathSuccessSchema,So as record,Sr as SkillUninstallSuccessSchema,St as DuplicatePathRequestSchema,T as AgentBurstDiffSuccessSchema,Ta as validateDocName,Ti as emptySkillState,Tn as RollbackSuccessSchema,To as unknown,Tr as SkillsListSuccessSchema,Tt as EDITOR_PROJECT_CONFIG_PATH,U as CC1ConfigValidationRejectedPayloadSchema,Ua as OK_PROJECT_MARKER,Ui as isParseEquivalentBridge,Un as SemanticIndexStatusSchema,Ur as TemplateMoveSuccessSchema,Ut as InstalledAgentsSuccessSchema,V as CC1BranchSwitchedPayloadSchema,Va as LINKABLE_ASSET_EXTENSIONS,Vi as isManagedArtifactDocName,Vn as SeedListPacksSuccessSchema,Vo as normalizeParams,Vr as TemplateGetSuccessSchema,Vt as InstallSkillRequestSchema,W as CC1DerivedViewPayloadSchema,Wi as isValidBranchName,Wn as ServerInfoSuccessSchema,Wo as require_dist$1,Wr as TemplatePutRequestSchema,Wt as InstalledSkillsSchema,X as CC1_CHANNEL_DISK_ACK,Xa as humanFormat,Xi as parseInstalledSkills,Xn as SharePublishResponseSchema,Xr as TestResetSuccessSchema,Xt as LocalOpAuthStatusSuccessSchema,Y as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ya as detectRemovedKeys,Yi as parseGlobalSkillBundleDoc,Yn as SharePublishRequestSchema,Yr as TestRescanFilesSuccessSchema,Yt as LocalOpAuthSetIdentityRequestSchema,Z as CC1_CHANNEL_SERVER_INFO,Za as isKnownConfigError,Zi as parseManagedArtifactName,Zn as ShareTargetStatusRequestSchema,Zr as TrashCleanupRequestSchema,Zt as LocalOpCloneRequestSchema,_ as releaseServerLock,_i as createWorkspaceSearchCorpus,_n as PageHeadingsSuccessSchema,_o as looseObject,_r as SkillTargetsGetSuccessSchema,_t as DeadLinksSuccessSchema,a as acquireProcessLock,aa as projectSkillContentDocName,ai as applyPatchToFm,an as MCP_SERVER_NAME,ao as withConfigSpanSync,ar as SkillInstallRequestSchema,at as CheckoutRequestSchema,ba as stripFrontmatter,bi as detectAppliedToleranceClasses,bn as ProblemDetailsSchema,bo as optional,br as SkillTargetsSchema,bt as DocumentListSuccessSchema,c as isProcessAlive,ca as renderInventoryFooter,ci as classifyMarkdownHref,cn as MetricsParseHealthSuccessSchema,co as _enum,cr as SkillMoveRequestSchema,ct as ClientLogsSuccessSchema,d as markProcessLockDraining,da as resolveInternalHref,di as colorFromSeed,dn as OrphansSuccessSchema,do as array,dr as SkillPutSuccessSchema,dt as CreatePageRequestSchema,ea as parseTemplateFile,ei as UploadAssetSuccessSchema,en as LocalOpOkInitRequestSchema,eo as mediaKindForSidebarAssetExtension,er as SkillFileDeleteSuccessSchema,et as CONFIG_DOC_NAMES,f as markServerLockDraining,fa as resolveSkillBundleWikiTarget,fi as composeTemplateFile,fn as PARSE_EQUIVALENCE_TOLERANCE,fo as boolean,fr as SkillRestoreRequestSchema,ft as CreatePageSuccessSchema,g as releaseProcessLock,ga as sharedExtensions,gi as createTagInTextRegex,gn as PROTOCOL_VERSION,go as literal,gr as SkillTargetEditorSchema,gt as DOCUMENT_OPEN_BYTE_LIMIT,h as readServerLock,ha as setToleranceTelemetryHook,hi as createCodeFenceTracker,hn as PROJECT_SKILL_EDITOR_IDS,ho as intersection,hr as SkillStateSchema,ia as projectMergeBoundarySpace,ii as applyIncrementalDiff,in as MANAGED_ARTIFACT_SCOPES,io as withConfigSpan,ir as SkillGetSuccessSchema,it as CONFIG_DOC_NAME_USER,j as AgentWriteMdSuccessSchema,ja as CONFIG_SCHEMA_MAJOR_PATH,ji as getAgentCanonicalDescriptors,jn as SKILL_TARGETS_REL,jo as meta$1,jr as SyncResolveConflictRequestSchema,jt as FolderConfigPutSuccessSchema,k as AgentUndoSuccessSchema,ka as Fragment,ki as fnv1aDigest,kn as SKILL_STATE_TARGETS,kr as SyncConflictContentSuccessSchema,kt as FolderConfigGetSuccessSchema,l as isValidLockPid,la as resolveAssetProjectPath,li as classifyWikiLinkTarget,ln as MetricsReconciliationSuccessSchema,lo as _null,lr as SkillMoveSuccessSchema,lt as CreateFolderRequestSchema,ma as serializeFrontmatterMap,mi as createBasenameIndex,mn as PREVIEW_THEME_TOKENS,mo as discriminatedUnion,mr as SkillScopeSchema,n as RUNTIME_VERSION,na as previewEmbedFence,ni as WorkspaceSuccessSchema,nn as MANAGED_ARTIFACT_PREFIX_SKILL,no as toConfigIssue,nr as SkillFilePutRequestSchema,nt as CONFIG_DOC_NAME_PROJECT,o as acquireServerLock,oa as readFmMap,oi as assertNeverProblemType,on as MarkdownManager,or as SkillInstallStateSuccessSchema,ot as CheckoutResponseSchema,p as readProcessLock,pa as searchWorkspaceCorpus,pi as containsXmlTag,pn as PREVIEW_EMBED_STARTERS,po as custom,pr as SkillRestoreSuccessSchema,q as CC1_CHANNEL_BRANCH_SWITCHED,qa as addConfigSpanEvent,qi as normalizeBridge,qn as SharePublishNameCheckResponseSchema,qr as TestFlushGitSuccessSchema,qt as LocalOpAuthEmptySuccessSchema,ra as projectFull,ri as applyFastDiff,rn as MANAGED_ARTIFACT_PREFIX_TEMPLATE,ro as validatePatchScopes,rr as SkillFilePutSuccessSchema,rt as CONFIG_DOC_NAME_PROJECT_LOCAL,sa as reattachLeadingDocBoundary,si as classifyGitAuthError,sn as MetricsAgentPresenceSuccessSchema,so as ZodOptional$1,sr as SkillInstallSuccessSchema,st as ClientLogsRequestSchema,t as ProcessLockCollisionError,ta as prependFrontmatter,ti as UploadRequestSchema,tn as LocalOpOkInitResponseSchema,to as normalizeAttachmentFolderPath,tr as SkillFileGetSuccessSchema,tt as CONFIG_DOC_NAME_OKIGNORE,un as ORPHAN_MODES,ur as SkillPutRequestSchema,ut as CreateFolderSuccessSchema,v as updateProcessLockPort,va as skillLiveDocName,vi as createWorkspaceSearchDocument,vn as PagesSuccessSchema,vo as number,vr as SkillTargetsPutRequestSchema,vt as DeletePathRequestSchema,w as AgentActivitySuccessSchema,wa as unwrapFrontmatterFences,wi as emptyInstalledSkills,wn as RollbackRequestSchema,wo as union,wr as SkillUpdateSuccessSchema,x as AGENT_ICON_COLORS,xa as tagsMatchingPrefix,xi as detectFmRegion,xn as RenamePathRequestSchema,xo as preprocess,xr as SkillUninstallRequestSchema,xt as DocumentReadSuccessSchema,ya as splitLeadingDocBoundary,yi as defaultScheduler,yn as PrincipalSuccessSchema,yo as object$1,yr as SkillTargetsPutSuccessSchema,yt as DeletePathSuccessSchema,z as BridgeMergeContentLossError,za as EXECUTABLE_BLOCKLIST_EXTENSIONS,zi as isHiddenDocName,zn as SeedApplyRequestSchema,zo as clone,zr as TagsListSuccessSchema,zt as HubsSuccessSchema}from"./server-lock-iLcBw_q0-CPFOrsBn.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BQ4-CT8p.mjs";import{a as esm_default,i as withParentLock,n as createGitInstance,o as simpleGit,r as splitNulSeparatedPaths,s as require_src$15,t as applyGitEnv}from"./git-handle-Bhgrj9qX-DBwQr-02.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DHter9G3.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DigWkxW2.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-D6YUa1Xl.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-2lBQUjKO.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$2 from"crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{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),g=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 g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${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 g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.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 g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}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 g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. 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(`
|
|
2
2
|
`)){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(`
|
|
3
3
|
`)){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 g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}if(S===`auto-consolidation`){let e=w;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:E,size:D,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}: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,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}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,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,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`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}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 parseOkActor(e){if(!e)return null;for(let t of e.split(`
|
|
4
4
|
`)){let e=t.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let s;try{s=JSON.parse(e.slice(10))}catch{return null}return typeof s!=`object`||!s?null:parseOkActorObject(s)}return null}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
@@ -11,7 +11,7 @@ import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __
|
|
|
11
11
|
To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
|
|
12
12
|
`,`Details:
|
|
13
13
|
`,(0,g.getIncompatibilityDetails)(S,e),`To resolve the conflict:
|
|
14
|
-
`,(0,g.getConflictResolutionRecipe)(S,e))}return w}}})),require_MultiWritableMetricStorage$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,s,g){this._backingStorages.forEach(S=>{S.record(e,t,s,g)})}}})),require_ObservableResult$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_HashMap$2(),g=require_Instruments$2();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new s.AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,s={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(s,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,S,w={}){if(!(0,g.isObservableInstrument)(e))return;let E=this._buffer.get(e);if(E??(E=new s.AttributeHashMap,this._buffer.set(e,E)),typeof S!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${S}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(S)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),S=Math.trunc(S),!Number.isInteger(S))||E.set(w,S)}}})),require_ObservableRegistry$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Instruments$2(),g=require_ObservableResult$2(),S=require_utils$13();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let s=this._findCallback(e,t);s<0||this._callbacks.splice(s,1)}addBatchCallback(e,g){let S=new Set(g.filter(s.isObservableInstrument));if(S.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,g);return}this._findBatchCallback(e,S)>=0||this._batchCallbacks.push({callback:e,instruments:S})}removeBatchCallback(e,t){let g=new Set(t.filter(s.isObservableInstrument)),S=this._findBatchCallback(e,g);S<0||this._batchCallbacks.splice(S,1)}async observe(e,t){let s=this._observeCallbacks(e,t),g=this._observeBatchCallbacks(e,t);return(await(0,S.PromiseAllSettled)([...s,...g])).filter(S.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:s,instrument:w})=>{let E=new g.ObservableResultImpl(w._descriptor.name,w._descriptor.valueType),D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w._metricStorages.forEach(t=>{t.record(E._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:s,instruments:w})=>{let E=new g.BatchObservableResultImpl,D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w.forEach(t=>{let s=E._buffer.get(t);s!=null&&t._metricStorages.forEach(t=>{t.record(s,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(s=>s.callback===e&&s.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(s=>s.callback===e&&(0,S.setEquals)(s.instruments,t))}}})),require_SyncMetricStorage$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage$2(),s=require_DeltaMetricProcessor$2(),g=require_TemporalMetricProcessor$2();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,S,w,E){super(e),this._attributesProcessor=S,this._aggregationCardinalityLimit=E,this._deltaMetricStorage=new s.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new g.TemporalMetricProcessor(t,w)}record(e,t,s,g){t=this._attributesProcessor.process(t,s),this._deltaMetricStorage.record(e,t,s,g)}collect(e,t){let s=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,s,t)}}})),require_AttributesProcessor$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},s=class{_processors;constructor(e){this._processors=e}process(e,t){let s=e;for(let e of this._processors)s=e.process(s,t);return s}},g=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let s={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>s[t]=e[t]),s}},S=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let s={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>s[t]=e[t]),s}};function w(){return k}e.createNoopAttributesProcessor=w;function E(e){return new s(e)}e.createMultiAttributesProcessor=E;function D(e){return new g(e)}e.createAllowListAttributesProcessor=D;function O(e){return new S(e)}e.createDenyListAttributesProcessor=O;let k=new t})),require_MeterSharedState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor$2(),s=require_Meter$2(),g=require_utils$13(),S=require_AsyncMetricStorage$2(),w=require_MetricStorageRegistry$2(),E=require_MultiWritableMetricStorage$2(),D=require_ObservableRegistry$2(),O=require_SyncMetricStorage$2(),k=require_AttributesProcessor$2();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new w.MetricStorageRegistry;observableRegistry=new D.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new s.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,O.SyncMetricStorage);return t.length===1?t[0]:new E.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,S.AsyncMetricStorage)}async collect(e,t,s){let S=await this.observableRegistry.observe(t,s?.timeoutMillis),w=this.metricStorageRegistry.getStorages(e);if(w.length===0)return null;let E=w.map(s=>s.collect(e,t)).filter(g.isNotNullish);return E.length===0?{errors:S}:{scopeMetrics:{scope:this._instrumentationScope,metrics:E},errors:S}}_registerMetricStorage(e,s){let g=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(g=>{let S=(0,t.createInstrumentDescriptorWithView)(g,e),w=this.metricStorageRegistry.findOrUpdateCompatibleStorage(S);if(w!=null)return w;let E=new s(S,g.aggregation.createAggregator(S),g.attributesProcessor,this._meterProviderSharedState.metricCollectors,g.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(g.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,g])=>{let S=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(S!=null)return S;let w=g.createAggregator(e),E=t.selectCardinalityLimit(e.type),D=new s(e,w,(0,k.createNoopAttributesProcessor)(),[t],E);return this.metricStorageRegistry.registerForCollector(t,D),D});g=g.concat(t)}return g}}})),require_MeterProviderSharedState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$13(),s=require_ViewRegistry$2(),g=require_MeterSharedState$2(),S=require_AggregationOption$2();e.MeterProviderSharedState=class{resource;viewRegistry=new s.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let s=(0,t.instrumentationScopeId)(e),S=this.meterSharedStates.get(s);return S??(S=new g.MeterSharedState(this,e),this.meterSharedStates.set(s,S)),S}selectAggregations(e){let t=[];for(let s of this.metricCollectors)t.push([s,(0,S.toAggregation)(s.selectAggregation(e))]);return t}}})),require_MetricCollector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$13();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let s=(0,t.millisToHrTime)(Date.now()),g=[],S=[],w=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let w=await t.collect(this,s,e);w?.scopeMetrics!=null&&g.push(w.scopeMetrics),w?.errors!=null&&S.push(...w.errors)});return await Promise.all(w),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:g},errors:S}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate$2();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate$2();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate$2(),s=require_AttributesProcessor$2(),g=require_InstrumentSelector$2(),S=require_MeterSelector$2(),w=require_AggregationOption$2();function E(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function D(e){if(E(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){D(e),e.attributesProcessors==null?this.attributesProcessor=(0,s.createNoopAttributesProcessor)():this.attributesProcessor=(0,s.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,w.toAggregation)(e.aggregation??{type:w.AggregationType.DEFAULT}),this.instrumentSelector=new g.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new S.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$12(),g=require_MeterProviderSharedState$2(),S=require_MetricCollector$2(),w=require_View$2();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new g.MeterProviderSharedState(e?.resource??(0,s.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new w.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new S.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,s=``,g={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:s,schemaUrl:g.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality$2();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var s=require_MetricData$2();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return s.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return s.InstrumentType}});var g=require_MetricReader$2();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return g.MetricReader}});var S=require_PeriodicExportingMetricReader$2();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return S.PeriodicExportingMetricReader}});var w=require_InMemoryMetricExporter$2();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return w.InMemoryMetricExporter}});var E=require_ConsoleMetricExporter$2();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return E.ConsoleMetricExporter}});var D=require_MeterProvider$2();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return D.MeterProvider}});var O=require_AggregationOption$2();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return O.AggregationType}});var k=require_AttributesProcessor$2();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return k.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return k.createDenyListAttributesProcessor}});var j=require_utils$13();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return j.TimeoutError}})})),require_internal_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.EAggregationTemporality=void 0,(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(e.EAggregationTemporality||={})})),require_internal$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportMetricsServiceRequest=e.toMetric=e.toScopeMetrics=e.toResourceMetrics=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$11(),g=require_internal_types(),S=require_utils$14(),w=require_internal$3();function E(e,t){let s=(0,S.getOtlpEncoder)(t),g=(0,w.createResource)(e.resource);return{resource:g,schemaUrl:g.schemaUrl,scopeMetrics:D(e.scopeMetrics,s)}}e.toResourceMetrics=E;function D(e,t){return Array.from(e.map(e=>({scope:(0,w.createInstrumentationScope)(e.scope),metrics:e.metrics.map(e=>O(e,t)),schemaUrl:e.scope.schemaUrl})))}e.toScopeMetrics=D;function O(e,t){let g={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},S=B(e.aggregationTemporality);switch(e.dataPointType){case s.DataPointType.SUM:g.sum={aggregationTemporality:S,isMonotonic:e.isMonotonic,dataPoints:j(e,t)};break;case s.DataPointType.GAUGE:g.gauge={dataPoints:j(e,t)};break;case s.DataPointType.HISTOGRAM:g.histogram={aggregationTemporality:S,dataPoints:F(e,t)};break;case s.DataPointType.EXPONENTIAL_HISTOGRAM:g.exponentialHistogram={aggregationTemporality:S,dataPoints:L(e,t)};break}return g}e.toMetric=O;function k(e,s,g){let S={attributes:(0,w.toAttributes)(e.attributes),startTimeUnixNano:g.encodeHrTime(e.startTime),timeUnixNano:g.encodeHrTime(e.endTime)};switch(s){case t.ValueType.INT:S.asInt=e.value;break;case t.ValueType.DOUBLE:S.asDouble=e.value;break}return S}function j(e,t){return e.dataPoints.map(s=>k(s,e.descriptor.valueType,t))}function F(e,t){return e.dataPoints.map(e=>{let s=e.value;return{attributes:(0,w.toAttributes)(e.attributes),bucketCounts:s.buckets.counts,explicitBounds:s.buckets.boundaries,count:s.count,sum:s.sum,min:s.min,max:s.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function L(e,t){return e.dataPoints.map(e=>{let s=e.value;return{attributes:(0,w.toAttributes)(e.attributes),count:s.count,min:s.min,max:s.max,sum:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},scale:s.scale,zeroCount:s.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function B(e){switch(e){case s.AggregationTemporality.DELTA:return g.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;case s.AggregationTemporality.CUMULATIVE:return g.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE}}function H(e,t){return{resourceMetrics:e.map(e=>E(e,t))}}e.createExportMetricsServiceRequest=H})),require_metrics$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;let t=require_root(),s=require_internal$1(),g=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,S=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.ProtobufMetricsSerializer={serializeRequest:e=>{let t=(0,s.createExportMetricsServiceRequest)([e]);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;var t=require_metrics$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return t.ProtobufMetricsSerializer}})})),require_internal=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportTraceServiceRequest=e.toOtlpSpanEvent=e.toOtlpLink=e.sdkSpanToOtlpSpan=void 0;let t=require_internal$3(),s=require_utils$14();function g(e,s){let g=e.spanContext(),E=e.status,D=e.parentSpanContext?.spanId?s.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:s.encodeSpanContext(g.traceId),spanId:s.encodeSpanContext(g.spanId),parentSpanId:D,traceState:g.traceState?.serialize(),name:e.name,kind:e.kind==null?0:e.kind+1,startTimeUnixNano:s.encodeHrTime(e.startTime),endTimeUnixNano:s.encodeHrTime(e.endTime),attributes:(0,t.toAttributes)(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>w(e,s)),droppedEventsCount:e.droppedEventsCount,status:{code:E.code,message:E.message},links:e.links.map(e=>S(e,s)),droppedLinksCount:e.droppedLinksCount}}e.sdkSpanToOtlpSpan=g;function S(e,s){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],spanId:s.encodeSpanContext(e.context.spanId),traceId:s.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpLink=S;function w(e,s){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],name:e.name,timeUnixNano:s.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpSpanEvent=w;function E(e,t){return{resourceSpans:O(e,(0,s.getOtlpEncoder)(t))}}e.createExportTraceServiceRequest=E;function D(e){let t=new Map;for(let s of e){let e=t.get(s.resource);e||(e=new Map,t.set(s.resource,e));let g=`${s.instrumentationScope.name}@${s.instrumentationScope.version||``}:${s.instrumentationScope.schemaUrl||``}`,S=e.get(g);S||(S=[],e.set(g,S)),S.push(s)}return t}function O(e,s){let S=D(e),w=[],E=S.entries(),O=E.next();for(;!O.done;){let[e,S]=O.value,D=[],k=S.values(),j=k.next();for(;!j.done;){let e=j.value;if(e.length>0){let S=e.map(e=>g(e,s));D.push({scope:(0,t.createInstrumentationScope)(e[0].instrumentationScope),spans:S,schemaUrl:e[0].instrumentationScope.schemaUrl})}j=k.next()}let F=(0,t.createResource)(e),L={resource:F,scopeSpans:D,schemaUrl:F.schemaUrl};w.push(L),O=E.next()}return w}})),require_trace$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;let t=require_root(),s=require_internal(),g=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,S=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.ProtobufTraceSerializer={serializeRequest:e=>{let t=(0,s.createExportTraceServiceRequest)(e);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;var t=require_trace$1();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return t.ProtobufTraceSerializer}})})),require_logs=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;let t=require_internal$2();e.JsonLogsSerializer={serializeRequest:e=>{let s=(0,t.createExportLogsServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;var t=require_logs();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return t.JsonLogsSerializer}})})),require_metrics=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;let t=require_internal$1();e.JsonMetricsSerializer={serializeRequest:e=>{let s=(0,t.createExportMetricsServiceRequest)([e],{useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;var t=require_metrics();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return t.JsonMetricsSerializer}})})),require_trace=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;let t=require_internal();e.JsonTraceSerializer={serializeRequest:e=>{let s=(0,t.createExportTraceServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;var t=require_trace();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return t.JsonTraceSerializer}})})),require_src$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=e.JsonMetricsSerializer=e.JsonLogsSerializer=e.ProtobufTraceSerializer=e.ProtobufMetricsSerializer=e.ProtobufLogsSerializer=void 0;var t=require_protobuf$2();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}});var s=require_protobuf$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return s.ProtobufMetricsSerializer}});var g=require_protobuf();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return g.ProtobufTraceSerializer}});var S=require_json$2();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return S.JsonLogsSerializer}});var w=require_json$1();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return w.JsonMetricsSerializer}});var E=require_json();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return E.JsonTraceSerializer}})}));const create$8=()=>new Map,copy=e=>{let t=create$8();return e.forEach((e,s)=>{t.set(s,e)}),t},setIfUndefined$1=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g},any=(e,t)=>{for(let[s,g]of e)if(t(g,s))return!0;return!1},create$7=()=>new Set,last=e=>e[e.length-1],appendTo=(e,t)=>{for(let s=0;s<t.length;s++)e.push(t[s])},from$1=Array.from,some=(e,t)=>{for(let s=0;s<e.length;s++)if(t(e[s],s,e))return!0;return!1},isArray$1=Array.isArray;var ObservableV2=class{constructor(){this._observers=create$8()}on(e,t){return setIfUndefined$1(this._observers,e,create$7).add(t),t}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from$1((this._observers.get(e)||create$8()).values()).forEach(e=>e(...t))}destroy(){this._observers=create$8()}};const floor$2=Math.floor,abs=Math.abs,min$2=(e,t)=>e<t?e:t,max$2=(e,t)=>e>t?e:t,isNaN$2=Number.isNaN,isNegativeZero=e=>e===0?1/e<0:e<0,BIT1=1,BIT2=2,BIT3=4,BIT4=8,BIT6=32,BIT7=64,BIT8$2=128,BIT18$2=1<<17,BIT19$2=1<<18,BIT20$2=1<<19,BIT21$2=1<<20,BIT22$2=1<<21,BIT23$2=1<<22,BIT24$2=1<<23,BIT25$2=1<<24,BIT26$2=1<<25,BIT27$2=1<<26,BIT28$2=1<<27,BIT29$2=1<<28,BIT30$2=1<<29,BIT31$2=1<<30,BITS5=31,BITS6=63,BITS7$2=127,BITS17=BIT18$2-1,BITS18=BIT19$2-1,BITS19=BIT20$2-1,BITS20=BIT21$2-1,BITS21=BIT22$2-1,BITS22=BIT23$2-1,BITS23=BIT24$2-1,BITS24=BIT25$2-1,BITS25=BIT26$2-1,BITS26=BIT27$2-1,BITS27=BIT28$2-1,BITS28=BIT29$2-1,BITS29=BIT30$2-1,BITS30=BIT31$2-1,BITS31=2147483647,BITS32=4294967295,MAX_SAFE_INTEGER$2=2**53-1,MIN_SAFE_INTEGER=-(2**53-1),HIGHEST_INT32=BITS31,HIGHEST_UINT32=BITS32,isInteger=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&floor$2(e)===e),isNaN$1=Number.isNaN,parseInt$1=Number.parseInt,fromCharCode$2=String.fromCharCode,fromCodePoint=String.fromCodePoint,MAX_UTF16_CHARACTER=fromCharCode$2(65535),toLowerCase=e=>e.toLowerCase(),trimLeftRegex=/^\s*/g,trimLeft=e=>e.replace(trimLeftRegex,``),fromCamelCaseRegex=/([A-Z])/g,fromCamelCase=(e,t)=>trimLeft(e.replace(fromCamelCaseRegex,e=>`${t}${toLowerCase(e)}`)),_encodeUtf8Polyfill$2=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$2=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$2=e=>utf8TextEncoder$2.encode(e),encodeUtf8$2=utf8TextEncoder$2?_encodeUtf8Native$2:_encodeUtf8Polyfill$2;let utf8TextDecoder$2=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$2&&utf8TextDecoder$2.decode(new Uint8Array).length===1&&(utf8TextDecoder$2=null);var Encoder$1=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder$1=()=>new Encoder$1,encode=e=>{let t=createEncoder$1();return e(t),toUint8Array$1(t)},length$1=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array$1=e=>{let t=new Uint8Array(length$1(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},verifyLen=(e,t)=>{let s=e.cbuf.length;s-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(max$2(s,t)*2),e.cpos=0)},write$2=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeUint8=write$2,writeVarUint$2=(e,t)=>{for(;t>127;)write$2(e,128|127&t),t=floor$2(t/128);write$2(e,127&t)},writeVarInt=(e,t)=>{let s=isNegativeZero(t);for(s&&(t=-t),write$2(e,(t>63?128:0)|(s?64:0)|63&t),t=floor$2(t/64);t>0;)write$2(e,(t>127?128:0)|127&t),t=floor$2(t/128)},_strBuffer$2=new Uint8Array(3e4),_maxStrBSize$2=_strBuffer$2.length/3,_writeVarStringNative$2=(e,t)=>{if(t.length<_maxStrBSize$2){let s=utf8TextEncoder$2.encodeInto(t,_strBuffer$2).written||0;writeVarUint$2(e,s);for(let t=0;t<s;t++)write$2(e,_strBuffer$2[t])}else writeVarUint8Array$2(e,encodeUtf8$2(t))},_writeVarStringPolyfill$2=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$2(e,g);for(let t=0;t<g;t++)write$2(e,s.codePointAt(t))},writeVarString$2=utf8TextEncoder$2&&utf8TextEncoder$2.encodeInto?_writeVarStringNative$2:_writeVarStringPolyfill$2,writeUint8Array$2=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$2(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$2(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$2=(e,t)=>{writeVarUint$2(e,t.byteLength),writeUint8Array$2(e,t)},writeOnDataView=(e,t)=>{verifyLen(e,t);let s=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,s},writeFloat32=(e,t)=>writeOnDataView(e,4).setFloat32(0,t,!1),writeFloat64=(e,t)=>writeOnDataView(e,8).setFloat64(0,t,!1),writeBigInt64=(e,t)=>writeOnDataView(e,8).setBigInt64(0,t,!1),floatTestBed=new DataView(new ArrayBuffer(4)),isFloat32=e=>(floatTestBed.setFloat32(0,e),floatTestBed.getFloat32(0)===e),writeAny=(e,t)=>{switch(typeof t){case`string`:write$2(e,119),writeVarString$2(e,t);break;case`number`:isInteger(t)&&abs(t)<=2147483647?(write$2(e,125),writeVarInt(e,t)):isFloat32(t)?(write$2(e,124),writeFloat32(e,t)):(write$2(e,123),writeFloat64(e,t));break;case`bigint`:write$2(e,122),writeBigInt64(e,t);break;case`object`:if(t===null)write$2(e,126);else if(isArray$1(t)){write$2(e,117),writeVarUint$2(e,t.length);for(let s=0;s<t.length;s++)writeAny(e,t[s])}else if(t instanceof Uint8Array)write$2(e,116),writeVarUint8Array$2(e,t);else{write$2(e,118);let s=Object.keys(t);writeVarUint$2(e,s.length);for(let g=0;g<s.length;g++){let S=s[g];writeVarString$2(e,S),writeAny(e,t[S])}}break;case`boolean`:write$2(e,t?120:121);break;default:write$2(e,127)}};var RleEncoder=class extends Encoder$1{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&writeVarUint$2(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const flushUintOptRleEncoder=e=>{e.count>0&&(writeVarInt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&writeVarUint$2(e.encoder,e.count-2))};var UintOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0}write(e){this.s===e?this.count++:(flushUintOptRleEncoder(this),this.count=1,this.s=e)}toUint8Array(){return flushUintOptRleEncoder(this),toUint8Array$1(this.encoder)}};const flushIntDiffOptRleEncoder=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);writeVarInt(e.encoder,t),e.count>1&&writeVarUint$2(e.encoder,e.count-2)}};var IntDiffOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(flushIntDiffOptRleEncoder(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return flushIntDiffOptRleEncoder(this),toUint8Array$1(this.encoder)}},StringEncoder=class{constructor(){this.sarr=[],this.s=``,this.lensE=new UintOptRleEncoder}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Encoder$1;return this.sarr.push(this.s),this.s=``,writeVarString$2(e,this.sarr.join(``)),writeUint8Array$2(e,this.lensE.toUint8Array()),toUint8Array$1(e)}};const create$6=e=>Error(e),methodUnimplemented=()=>{throw create$6(`Method unimplemented`)},unexpectedCase=()=>{throw create$6(`Unexpected case`)},errorUnexpectedEndOfArray$2=create$6(`Unexpected end of array`),errorIntegerOutOfRange$2=create$6(`Integer out of Range`);var Decoder$1=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder$1=e=>new Decoder$1(e),hasContent$1=e=>e.pos!==e.arr.length,readUint8Array$1=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array$1=e=>readUint8Array$1(e,readVarUint$1(e)),readUint8$1=e=>e.arr[e.pos++],readVarUint$1=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&127)*s,s*=128,g<128)return t;if(t>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},readVarInt=e=>{let t=e.arr[e.pos++],s=t&63,g=64,S=(t&64)>0?-1:1;if(!(t&128))return S*s;let w=e.arr.length;for(;e.pos<w;){if(t=e.arr[e.pos++],s+=(t&127)*g,g*=128,t<128)return S*s;if(s>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},_readVarStringPolyfill$1=e=>{let t=readVarUint$1(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8$1(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8$1(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative$1=e=>utf8TextDecoder$2.decode(readVarUint8Array$1(e)),readVarString$1=utf8TextDecoder$2?_readVarStringNative$1:_readVarStringPolyfill$1,readFromDataView=(e,t)=>{let s=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,s},readFloat32=e=>readFromDataView(e,4).getFloat32(0,!1),readFloat64=e=>readFromDataView(e,8).getFloat64(0,!1),readBigInt64=e=>readFromDataView(e,8).getBigInt64(0,!1),readAnyLookupTable=[e=>void 0,e=>null,readVarInt,readFloat32,readFloat64,readBigInt64,e=>!1,e=>!0,readVarString$1,e=>{let t=readVarUint$1(e),s={};for(let g=0;g<t;g++){let t=readVarString$1(e);s[t]=readAny(e)}return s},e=>{let t=readVarUint$1(e),s=[];for(let g=0;g<t;g++)s.push(readAny(e));return s},readVarUint8Array$1],readAny=e=>readAnyLookupTable[127-readUint8$1(e)](e);var RleDecoder=class extends Decoder$1{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hasContent$1(this)?this.count=readVarUint$1(this)+1:this.count=-1),this.count--,this.s}},UintOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=readVarInt(this);let e=isNegativeZero(this.s);this.count=1,e&&(this.s=-this.s,this.count=readVarUint$1(this)+2)}return this.count--,this.s}},IntDiffOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=readVarInt(this),t=e&1;this.diff=floor$2(e/2),this.count=1,t&&(this.count=readVarUint$1(this)+2)}return this.s+=this.diff,this.count--,this.s}},StringDecoder=class{constructor(e){this.decoder=new UintOptRleDecoder(e),this.str=readVarString$1(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};const subtle=webcrypto$1.subtle,getRandomValues=webcrypto$1.getRandomValues.bind(webcrypto$1),uint32=()=>getRandomValues(new Uint32Array(1))[0],uuidv4Template=`10000000-1000-4000-8000-100000000000`,uuidv4=()=>uuidv4Template.replace(/[018]/g,e=>(e^uint32()&15>>e/4).toString(16)),getUnixTime$1=Date.now,create$5=e=>new Promise(e),all=Promise.all.bind(Promise),undefinedToNull=e=>e===void 0?null:e;var VarStoragePolyfill=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};let _localStorage=new VarStoragePolyfill,usePolyfill=!0;try{typeof localStorage<`u`&&localStorage&&(_localStorage=localStorage)}catch{}const varStorage=_localStorage,EqualityTraitSymbol$1=Symbol(`Equality`),equals=(e,t)=>e===t||!!e?.[EqualityTraitSymbol$1]?.(t)||!1,assign=Object.assign,keys$1=Object.keys,forEach=(e,t)=>{for(let s in e)t(e[s],s)},size$1=e=>keys$1(e).length,isEmpty$3=e=>{for(let t in e)return!1;return!0},every=(e,t)=>{for(let s in e)if(!t(e[s],s))return!1;return!0},hasProperty$1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalFlat=(e,t)=>e===t||size$1(e)===size$1(t)&&every(e,(e,s)=>(e!==void 0||hasProperty$1(t,s))&&equals(t[s],e)),freeze=Object.freeze,deepFreeze=e=>{for(let t in e){let s=e[t];(typeof s==`object`||typeof s==`function`)&&deepFreeze(e[t])}return freeze(e)},callAll=(e,t,s=0)=>{try{for(;s<e.length;s++)e[s](...t)}finally{s<e.length&&callAll(e,t,s+1)}},id=e=>e,isOneOf=(e,t)=>t.includes(e),isArray=isArray$1,isNode=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,isBrowser=typeof window<`u`&&typeof document<`u`&&!isNode,isMac=typeof navigator<`u`?/Mac/.test(navigator.platform):!1;let params;const args=[],computeParams=()=>{if(params===void 0)if(isNode){params=create$8();let e=process.argv,t=null;for(let s=0;s<e.length;s++){let g=e[s];g[0]===`-`?(t!==null&¶ms.set(t,``),t=g):t===null?args.push(g):(params.set(t,g),t=null)}t!==null&¶ms.set(t,``)}else typeof location==`object`?(params=create$8(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,s]=e.split(`=`);params.set(`--${fromCamelCase(t,`-`)}`,s),params.set(`-${fromCamelCase(t,`-`)}`,s)}})):params=create$8();return params},hasParam=e=>computeParams().has(e),getVariable=e=>undefinedToNull(isNode?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:varStorage.getItem(e)),hasConf=e=>hasParam(`--`+e)||getVariable(e)!==null,production=hasConf(`production`),forceColor=isNode&&isOneOf(process.env.FORCE_COLOR,[`true`,`1`,`2`]),supportsColor=forceColor||!hasParam(`--no-colors`)&&!hasConf(`no-color`)&&(!isNode||process.stdout.isTTY)&&(!isNode||hasParam(`--color`)||getVariable(`COLORTERM`)!==null||(getVariable(`TERM`)||``).includes(`color`)),createUint8ArrayFromLen=e=>new Uint8Array(e),createUint8ArrayViewFromArrayBuffer=(e,t,s)=>new Uint8Array(e,t,s),toBase64Browser=e=>{let t=``;for(let s=0;s<e.byteLength;s++)t+=fromCharCode$2(e[s]);return btoa(t)},toBase64Node=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),fromBase64Browser=e=>{let t=atob(e),s=createUint8ArrayFromLen(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s},fromBase64Node=e=>{let t=Buffer.from(e,`base64`);return createUint8ArrayViewFromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)},toBase64=isBrowser?toBase64Browser:toBase64Node,fromBase64=isBrowser?fromBase64Browser:fromBase64Node,copyUint8Array=e=>{let t=createUint8ArrayFromLen(e.byteLength);return t.set(e),t},encodeAny=e=>encode(t=>writeAny(t,e)),create$4=Symbol,BOLD=create$4(),UNBOLD=create$4(),BLUE=create$4(),GREY=create$4(),GREEN=create$4(),RED=create$4(),PURPLE=create$4(),ORANGE=create$4(),UNCOLOR=create$4(),computeNoColorLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],s=[],g=0;for(;g<e.length;g++){let s=e[g];if(s===void 0)break;if(s.constructor===String||s.constructor===Number)t.push(s);else if(s.constructor===Object)break}for(g>0&&s.push(t.join(``));g<e.length;g++){let t=e[g];t instanceof Symbol||s.push(t)}return s};let lastLoggingTime=getUnixTime$1();const _nodeStyleMap={[BOLD]:`\x1B[1m`,[UNBOLD]:`\x1B[2m`,[BLUE]:`\x1B[34m`,[GREEN]:`\x1B[32m`,[GREY]:`\x1B[37m`,[RED]:`\x1B[31m`,[PURPLE]:`\x1B[35m`,[ORANGE]:`\x1B[38;5;208m`,[UNCOLOR]:`\x1B[0m`},computeNodeLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],s=[],g=0;for(;g<e.length;g++){let s=e[g],S=_nodeStyleMap[s];if(S!==void 0)t.push(S);else if(s===void 0)break;else if(s.constructor===String||s.constructor===Number)t.push(s);else break}for(g>0&&(t.push(`\x1B[0m`),s.push(t.join(``)));g<e.length;g++){let t=e[g];t instanceof Symbol||s.push(t)}return s},computeLoggingArgs=supportsColor?computeNodeLoggingArgs:computeNoColorLoggingArgs,print=(...e)=>{console.log(...computeLoggingArgs(e))},warn=(...e)=>{console.warn(...computeLoggingArgs(e))},createIterator=e=>({[Symbol.iterator](){return this},next:e}),iteratorFilter=(e,t)=>createIterator(()=>{let s;do s=e.next();while(!s.done&&!t(s.value));return s}),iteratorMap=(e,t)=>createIterator(()=>{let{done:s,value:g}=e.next();return{done:s,value:s?void 0:t(g)}});var DeleteItem=class{constructor(e,t){this.clock=e,this.len=t}},DeleteSet=class{constructor(){this.clients=new Map}};const iterateDeletedStructs=(e,t,s)=>t.clients.forEach((t,g)=>{let S=e.doc.store.clients.get(g);if(S!=null){let g=S[S.length-1],w=g.id.clock+g.length;for(let g=0,E=t[g];g<t.length&&E.clock<w;E=t[++g])iterateStructs(e,S,E.clock,E.len,s)}}),findIndexDS=(e,t)=>{let s=0,g=e.length-1;for(;s<=g;){let S=floor$2((s+g)/2),w=e[S],E=w.clock;if(E<=t){if(t<E+w.len)return S;s=S+1}else g=S-1}return null},isDeleted=(e,t)=>{let s=e.clients.get(t.client);return s!==void 0&&findIndexDS(s,t.clock)!==null},sortAndMergeDeleteSet=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,s;for(t=1,s=1;t<e.length;t++){let g=e[s-1],S=e[t];g.clock+g.len>=S.clock?e[s-1]=new DeleteItem(g.clock,max$2(g.len,S.clock+S.len-g.clock)):(s<t&&(e[s]=S),s++)}e.length=s})},mergeDeleteSets=e=>{let t=new DeleteSet;for(let s=0;s<e.length;s++)e[s].clients.forEach((g,S)=>{if(!t.clients.has(S)){let w=g.slice();for(let t=s+1;t<e.length;t++)appendTo(w,e[t].clients.get(S)||[]);t.clients.set(S,w)}});return sortAndMergeDeleteSet(t),t},addToDeleteSet=(e,t,s,g)=>{setIfUndefined$1(e.clients,t,()=>[]).push(new DeleteItem(s,g))},createDeleteSet=()=>new DeleteSet,createDeleteSetFromStructStore=e=>{let t=createDeleteSet();return e.clients.forEach((e,s)=>{let g=[];for(let t=0;t<e.length;t++){let s=e[t];if(s.deleted){let S=s.id.clock,w=s.length;if(t+1<e.length)for(let s=e[t+1];t+1<e.length&&s.deleted;s=e[++t+1])w+=s.length;g.push(new DeleteItem(S,w))}}g.length>0&&t.clients.set(s,g)}),t},writeDeleteSet=(e,t)=>{writeVarUint$2(e.restEncoder,t.clients.size),from$1(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,s])=>{e.resetDsCurVal(),writeVarUint$2(e.restEncoder,t);let g=s.length;writeVarUint$2(e.restEncoder,g);for(let t=0;t<g;t++){let g=s[t];e.writeDsClock(g.clock),e.writeDsLen(g.len)}})},readDeleteSet=e=>{let t=new DeleteSet,s=readVarUint$1(e.restDecoder);for(let g=0;g<s;g++){e.resetDsCurVal();let s=readVarUint$1(e.restDecoder),g=readVarUint$1(e.restDecoder);if(g>0){let S=setIfUndefined$1(t.clients,s,()=>[]);for(let t=0;t<g;t++)S.push(new DeleteItem(e.readDsClock(),e.readDsLen()))}}return t},readAndApplyDeleteSet=(e,t,s)=>{let g=new DeleteSet,S=readVarUint$1(e.restDecoder);for(let w=0;w<S;w++){e.resetDsCurVal();let S=readVarUint$1(e.restDecoder),w=readVarUint$1(e.restDecoder),E=s.clients.get(S)||[],D=getState(s,S);for(let s=0;s<w;s++){let s=e.readDsClock(),w=s+e.readDsLen();if(s<D){D<w&&addToDeleteSet(g,S,D,w-D);let e=findIndexSS(E,s),O=E[e];for(!O.deleted&&O.id.clock<s&&(E.splice(e+1,0,splitItem(t,O,s-O.id.clock)),e++);e<E.length&&(O=E[e++],O.id.clock<w);)O.deleted||(w<O.id.clock+O.length&&E.splice(e,0,splitItem(t,O,w-O.id.clock)),O.delete(t))}else addToDeleteSet(g,S,s,w-s)}}if(g.clients.size>0){let e=new UpdateEncoderV2;return writeVarUint$2(e.restEncoder,0),writeDeleteSet(e,g),e.toUint8Array()}return null},equalDeleteSets=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[s,g]of e.clients.entries()){let e=t.clients.get(s);if(e===void 0||g.length!==e.length)return!1;for(let t=0;t<g.length;t++){let s=g[t],S=e[t];if(s.clock!==S.clock||s.len!==S.len)return!1}}return!0},generateNewClientId=uint32;var Doc=class e extends ObservableV2{constructor({guid:e=uuidv4(),collectionid:t=null,gc:s=!0,gcFilter:g=()=>!0,meta:S=null,autoLoad:w=!1,shouldLoad:E=!0}={}){super(),this.gc=s,this.gcFilter=g,this.clientID=generateNewClientId(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new StructStore,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=E,this.autoLoad=w,this.meta=S,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=create$5(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let D=()=>create$5(e=>{let t=s=>{(s===void 0||s===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=D()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=D()}load(){let e=this._item;e!==null&&!this.shouldLoad&&transact(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(from$1(this.subdocs).map(e=>e.guid))}transact(e,t=null){return transact(this,e,t)}get(e,t=AbstractType){let s=setIfUndefined$1(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),g=s.constructor;if(t!==AbstractType&&g!==t)if(g===AbstractType){let g=new t;g._map=s._map,s._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=g}),g._start=s._start;for(let e=g._start;e!==null;e=e.right)e.parent=g;return g._length=s._length,this.share.set(e,g),g._integrate(this,null),g}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=``){return this.get(e,YArray)}getText(e=``){return this.get(e,YText)}getMap(e=``){return this.get(e,YMap)}getXmlElement(e=``){return this.get(e,YXmlElement)}getXmlFragment(e=``){return this.get(e,YXmlFragment)}toJSON(){let e={};return this.share.forEach((t,s)=>{e[s]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,from$1(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let s=t.content;s.doc=new e({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=t,transact(t.parent.doc,e=>{let g=s.doc;t.deleted||e.subdocsAdded.add(g),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},DSDecoderV1=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return readVarUint$1(this.restDecoder)}readDsLen(){return readVarUint$1(this.restDecoder)}},UpdateDecoderV1=class extends DSDecoderV1{readLeftID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readRightID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readClient(){return readVarUint$1(this.restDecoder)}readInfo(){return readUint8$1(this.restDecoder)}readString(){return readVarString$1(this.restDecoder)}readParentInfo(){return readVarUint$1(this.restDecoder)===1}readTypeRef(){return readVarUint$1(this.restDecoder)}readLen(){return readVarUint$1(this.restDecoder)}readAny(){return readAny(this.restDecoder)}readBuf(){return copyUint8Array(readVarUint8Array$1(this.restDecoder))}readJSON(){return JSON.parse(readVarString$1(this.restDecoder))}readKey(){return readVarString$1(this.restDecoder)}},DSDecoderV2=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=readVarUint$1(this.restDecoder),this.dsCurrVal}readDsLen(){let e=readVarUint$1(this.restDecoder)+1;return this.dsCurrVal+=e,e}},UpdateDecoderV2=class extends DSDecoderV2{constructor(e){super(e),this.keys=[],readVarUint$1(e),this.keyClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.clientDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.leftClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.rightClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.infoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.stringDecoder=new StringDecoder(readVarUint8Array$1(e)),this.parentInfoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.typeRefDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.lenDecoder=new UintOptRleDecoder(readVarUint8Array$1(e))}readLeftID(){return new ID(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ID(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return readAny(this.restDecoder)}readBuf(){return readVarUint8Array$1(this.restDecoder)}readJSON(){return readAny(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},DSEncoderV1=class{constructor(){this.restEncoder=createEncoder$1()}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){writeVarUint$2(this.restEncoder,e)}writeDsLen(e){writeVarUint$2(this.restEncoder,e)}},UpdateEncoderV1=class extends DSEncoderV1{writeLeftID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeRightID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeClient(e){writeVarUint$2(this.restEncoder,e)}writeInfo(e){writeUint8(this.restEncoder,e)}writeString(e){writeVarString$2(this.restEncoder,e)}writeParentInfo(e){writeVarUint$2(this.restEncoder,e?1:0)}writeTypeRef(e){writeVarUint$2(this.restEncoder,e)}writeLen(e){writeVarUint$2(this.restEncoder,e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeVarString$2(this.restEncoder,JSON.stringify(e))}writeKey(e){writeVarString$2(this.restEncoder,e)}},DSEncoderV2=class{constructor(){this.restEncoder=createEncoder$1(),this.dsCurrVal=0}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,writeVarUint$2(this.restEncoder,t)}writeDsLen(e){e===0&&unexpectedCase(),writeVarUint$2(this.restEncoder,e-1),this.dsCurrVal+=e}},UpdateEncoderV2=class extends DSEncoderV2{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new IntDiffOptRleEncoder,this.clientEncoder=new UintOptRleEncoder,this.leftClockEncoder=new IntDiffOptRleEncoder,this.rightClockEncoder=new IntDiffOptRleEncoder,this.infoEncoder=new RleEncoder(writeUint8),this.stringEncoder=new StringEncoder,this.parentInfoEncoder=new RleEncoder(writeUint8),this.typeRefEncoder=new UintOptRleEncoder,this.lenEncoder=new UintOptRleEncoder}toUint8Array(){let e=createEncoder$1();return writeVarUint$2(e,0),writeVarUint8Array$2(e,this.keyClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.clientEncoder.toUint8Array()),writeVarUint8Array$2(e,this.leftClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.rightClockEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.infoEncoder)),writeVarUint8Array$2(e,this.stringEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.parentInfoEncoder)),writeVarUint8Array$2(e,this.typeRefEncoder.toUint8Array()),writeVarUint8Array$2(e,this.lenEncoder.toUint8Array()),writeUint8Array$2(e,toUint8Array$1(this.restEncoder)),toUint8Array$1(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeAny(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const writeStructs=(e,t,s,g)=>{g=max$2(g,t[0].id.clock);let S=findIndexSS(t,g);writeVarUint$2(e.restEncoder,t.length-S),e.writeClient(s),writeVarUint$2(e.restEncoder,g);let w=t[S];w.write(e,g-w.id.clock);for(let s=S+1;s<t.length;s++)t[s].write(e,0)},writeClientsStructs=(e,t,s)=>{let g=new Map;s.forEach((e,s)=>{getState(t,s)>e&&g.set(s,e)}),getStateVector(t).forEach((e,t)=>{s.has(t)||g.set(t,0)}),writeVarUint$2(e.restEncoder,g.size),from$1(g.entries()).sort((e,t)=>t[0]-e[0]).forEach(([s,g])=>{writeStructs(e,t.clients.get(s),s,g)})},readClientsStructRefs=(e,t)=>{let s=create$8(),g=readVarUint$1(e.restDecoder);for(let S=0;S<g;S++){let g=readVarUint$1(e.restDecoder),S=Array(g),w=e.readClient(),E=readVarUint$1(e.restDecoder);s.set(w,{i:0,refs:S});for(let s=0;s<g;s++){let g=e.readInfo();switch(31&g){case 0:{let t=e.readLen();S[s]=new GC(createID(w,E),t),E+=t;break}case 10:{let t=readVarUint$1(e.restDecoder);S[s]=new Skip(createID(w,E),t),E+=t;break}default:{let D=(g&192)==0,O=new Item(createID(w,E),null,(g&128)==128?e.readLeftID():null,null,(g&64)==64?e.readRightID():null,D?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,D&&(g&32)==32?e.readString():null,readItemContent(e,g));S[s]=O,E+=O.length}}}}return s},integrateStructs=(e,t,s)=>{let g=[],S=from$1(s.keys()).sort((e,t)=>e-t);if(S.length===0)return null;let w=()=>{if(S.length===0)return null;let e=s.get(S[S.length-1]);for(;e.refs.length===e.i;)if(S.pop(),S.length>0)e=s.get(S[S.length-1]);else return null;return e},E=w();if(E===null)return null;let D=new StructStore,O=new Map,k=(e,t)=>{let s=O.get(e);(s==null||s>t)&&O.set(e,t)},j=E.refs[E.i++],F=new Map,L=()=>{for(let e of g){let t=e.id.client,g=s.get(t);g?(g.i--,D.clients.set(t,g.refs.slice(g.i)),s.delete(t),g.i=0,g.refs=[]):D.clients.set(t,[e]),S=S.filter(e=>e!==t)}g.length=0};for(;;){if(j.constructor!==Skip){let S=setIfUndefined$1(F,j.id.client,()=>getState(t,j.id.client))-j.id.clock;if(S<0)g.push(j),k(j.id.client,j.id.clock-1),L();else{let w=j.getMissing(e,t);if(w!==null){g.push(j);let e=s.get(w)||{refs:[],i:0};if(e.refs.length===e.i)k(w,getState(t,w)),L();else{j=e.refs[e.i++];continue}}else (S===0||S<j.length)&&(j.integrate(e,S),F.set(j.id.client,j.id.clock+j.length))}}if(g.length>0)j=g.pop();else if(E!==null&&E.i<E.refs.length)j=E.refs[E.i++];else{if(E=w(),E===null)break;j=E.refs[E.i++]}}if(D.clients.size>0){let e=new UpdateEncoderV2;return writeClientsStructs(e,D,new Map),writeVarUint$2(e.restEncoder,0),{missing:O,update:e.toUint8Array()}}return null},writeStructsFromTransaction=(e,t)=>writeClientsStructs(e,t.doc.store,t.beforeState),readUpdateV2=(e,t,s,g=new UpdateDecoderV2(e))=>transact(t,e=>{e.local=!1;let t=!1,s=e.doc,S=s.store,w=integrateStructs(e,S,readClientsStructRefs(g,s)),E=S.pendingStructs;if(E){for(let[e,s]of E.missing)if(s<getState(S,e)){t=!0;break}if(w){for(let[e,t]of w.missing){let s=E.missing.get(e);(s==null||s>t)&&E.missing.set(e,t)}E.update=mergeUpdatesV2([E.update,w.update])}}else S.pendingStructs=w;let D=readAndApplyDeleteSet(g,e,S);if(S.pendingDs){let t=new UpdateDecoderV2(createDecoder$1(S.pendingDs));readVarUint$1(t.restDecoder);let s=readAndApplyDeleteSet(t,e,S);D&&s?S.pendingDs=mergeUpdatesV2([D,s]):S.pendingDs=D||s}else S.pendingDs=D;if(t){let t=S.pendingStructs.update;S.pendingStructs=null,applyUpdateV2(e.doc,t)}},s,!1),applyUpdateV2=(e,t,s,g=UpdateDecoderV2)=>{let S=createDecoder$1(t);readUpdateV2(S,e,s,new g(S))},applyUpdate=(e,t,s)=>applyUpdateV2(e,t,s,UpdateDecoderV1),writeStateAsUpdate=(e,t,s=new Map)=>{writeClientsStructs(e,t.store,s),writeDeleteSet(e,createDeleteSetFromStructStore(t.store))},encodeStateAsUpdateV2=(e,t=new Uint8Array([0]),s=new UpdateEncoderV2)=>{writeStateAsUpdate(s,e,decodeStateVector(t));let g=[s.toUint8Array()];if(e.store.pendingDs&&g.push(e.store.pendingDs),e.store.pendingStructs&&g.push(diffUpdateV2(e.store.pendingStructs.update,t)),g.length>1){if(s.constructor===UpdateEncoderV1)return mergeUpdates(g.map((e,t)=>t===0?e:convertUpdateFormatV2ToV1(e)));if(s.constructor===UpdateEncoderV2)return mergeUpdatesV2(g)}return g[0]},encodeStateAsUpdate=(e,t)=>encodeStateAsUpdateV2(e,t,new UpdateEncoderV1),readStateVector=e=>{let t=new Map,s=readVarUint$1(e.restDecoder);for(let g=0;g<s;g++){let s=readVarUint$1(e.restDecoder),g=readVarUint$1(e.restDecoder);t.set(s,g)}return t},decodeStateVector=e=>readStateVector(new DSDecoderV1(createDecoder$1(e))),writeStateVector=(e,t)=>(writeVarUint$2(e.restEncoder,t.size),from$1(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,s])=>{writeVarUint$2(e.restEncoder,t),writeVarUint$2(e.restEncoder,s)}),e),writeDocumentStateVector=(e,t)=>writeStateVector(e,getStateVector(t.store)),encodeStateVectorV2=(e,t=new DSEncoderV2)=>(e instanceof Map?writeStateVector(t,e):writeDocumentStateVector(t,e),t.toUint8Array()),encodeStateVector=e=>encodeStateVectorV2(e,new DSEncoderV1);var EventHandler=class{constructor(){this.l=[]}};const createEventHandler=()=>new EventHandler,addEventHandlerListener=(e,t)=>e.l.push(t),removeEventHandlerListener=(e,t)=>{let s=e.l,g=s.length;e.l=s.filter(e=>t!==e),g===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},callEventHandlerListeners=(e,t,s)=>callAll(e.l,[t,s]);var ID=class{constructor(e,t){this.client=e,this.clock=t}};const compareIDs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,createID=(e,t)=>new ID(e,t),findRootTypeKey=e=>{for(let[t,s]of e.doc.share.entries())if(s===e)return t;throw unexpectedCase()},isParentOf=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Snapshot=class{constructor(e,t){this.ds=e,this.sv=t}};const createSnapshot=(e,t)=>new Snapshot(e,t),emptySnapshot=createSnapshot(createDeleteSet(),new Map),snapshot=e=>createSnapshot(createDeleteSetFromStructStore(e.store),getStateVector(e.store)),isVisible$1=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!isDeleted(t.ds,e.id),splitSnapshotAffectedStructs=(e,t)=>{let s=setIfUndefined$1(e.meta,splitSnapshotAffectedStructs,create$7),g=e.doc.store;s.has(t)||(t.sv.forEach((t,s)=>{t<getState(g,s)&&getItemCleanStart(e,createID(s,t))}),iterateDeletedStructs(e,t.ds,e=>{}),s.add(t))},snapshotContainsUpdateV2=(e,t,s=UpdateDecoderV2)=>{let g=new s(createDecoder$1(t)),S=new LazyStructReader(g,!1);for(let t=S.curr;t!==null;t=S.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let w=mergeDeleteSets([e.ds,readDeleteSet(g)]);return equalDeleteSets(e.ds,w)},snapshotContainsUpdate=(e,t)=>snapshotContainsUpdateV2(e,t,UpdateDecoderV1);var StructStore=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const getStateVector=e=>{let t=new Map;return e.clients.forEach((e,s)=>{let g=e[e.length-1];t.set(s,g.id.clock+g.length)}),t},getState=(e,t)=>{let s=e.clients.get(t);if(s===void 0)return 0;let g=s[s.length-1];return g.id.clock+g.length},addStruct=(e,t)=>{let s=e.clients.get(t.id.client);if(s===void 0)s=[],e.clients.set(t.id.client,s);else{let e=s[s.length-1];if(e.id.clock+e.length!==t.id.clock)throw unexpectedCase()}s.push(t)},findIndexSS=(e,t)=>{let s=0,g=e.length-1,S=e[g],w=S.id.clock;if(w===t)return g;let E=floor$2(t/(w+S.length-1)*g);for(;s<=g;){if(S=e[E],w=S.id.clock,w<=t){if(t<w+S.length)return E;s=E+1}else g=E-1;E=floor$2((s+g)/2)}throw unexpectedCase()},find=(e,t)=>{let s=e.clients.get(t.client);return s[findIndexSS(s,t.clock)]},getItem=find,findIndexCleanStart=(e,t,s)=>{let g=findIndexSS(t,s),S=t[g];return S.id.clock<s&&S instanceof Item?(t.splice(g+1,0,splitItem(e,S,s-S.id.clock)),g+1):g},getItemCleanStart=(e,t)=>{let s=e.doc.store.clients.get(t.client);return s[findIndexCleanStart(e,s,t.clock)]},getItemCleanEnd=(e,t,s)=>{let g=t.clients.get(s.client),S=findIndexSS(g,s.clock),w=g[S];return s.clock!==w.id.clock+w.length-1&&w.constructor!==GC&&g.splice(S+1,0,splitItem(e,w,s.clock-w.id.clock+1)),w},replaceStruct=(e,t,s)=>{let g=e.clients.get(t.id.client);g[findIndexSS(g,t.id.clock)]=s},iterateStructs=(e,t,s,g,S)=>{if(g===0)return;let w=s+g,E=findIndexCleanStart(e,t,s),D;do D=t[E++],w<D.id.clock+D.length&&findIndexCleanStart(e,t,w),S(D);while(E<t.length&&t[E].id.clock<w)};var Transaction=class{constructor(e,t,s){this.doc=e,this.deleteSet=new DeleteSet,this.beforeState=getStateVector(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const writeUpdateMessageFromTransaction=(e,t)=>t.deleteSet.clients.size===0&&!any(t.afterState,(e,s)=>t.beforeState.get(s)!==e)?!1:(sortAndMergeDeleteSet(t.deleteSet),writeStructsFromTransaction(e,t),writeDeleteSet(e,t.deleteSet),!0),addChangedTypeToTransaction=(e,t,s)=>{let g=t._item;(g===null||g.id.clock<(e.beforeState.get(g.id.client)||0)&&!g.deleted)&&setIfUndefined$1(e.changed,t,create$7).add(s)},tryToMergeWithLefts=(e,t)=>{let s=e[t],g=e[t-1],S=t;for(;S>0;s=g,g=e[--S-1]){if(g.deleted===s.deleted&&g.constructor===s.constructor&&g.mergeWith(s)){s instanceof Item&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,g);continue}break}let w=t-S;return w&&e.splice(t+1-w,w),w},tryGcDeleteSet=(e,t,s)=>{for(let[g,S]of e.clients.entries()){let e=t.clients.get(g);for(let g=S.length-1;g>=0;g--){let w=S[g],E=w.clock+w.len;for(let g=findIndexSS(e,w.clock),S=e[g];g<e.length&&S.id.clock<E;S=e[++g]){let S=e[g];if(w.clock+w.len<=S.id.clock)break;S instanceof Item&&S.deleted&&!S.keep&&s(S)&&S.gc(t,!1)}}}},tryMergeDeleteSet=(e,t)=>{e.clients.forEach((e,s)=>{let g=t.clients.get(s);for(let t=e.length-1;t>=0;t--){let s=e[t],S=min$2(g.length-1,1+findIndexSS(g,s.clock+s.len-1));for(let e=S,t=g[e];e>0&&t.id.clock>=s.clock;t=g[e])e-=1+tryToMergeWithLefts(g,e)}})},cleanupTransactions=(e,t)=>{if(t<e.length){let s=e[t],g=s.doc,S=g.store,w=s.deleteSet,E=s._mergeStructs;try{sortAndMergeDeleteSet(w),s.afterState=getStateVector(s.doc.store),g.emit(`beforeObserverCalls`,[s,g]);let e=[];s.changed.forEach((t,g)=>e.push(()=>{(g._item===null||!g._item.deleted)&&g._callObserver(s,t)})),e.push(()=>{s.changedParentTypes.forEach((t,g)=>{g._dEH.l.length>0&&(g._item===null||!g._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=g,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{callEventHandlerListeners(g._dEH,t,s)}))}),e.push(()=>g.emit(`afterTransaction`,[s,g])),e.push(()=>{s._needFormattingCleanup&&cleanupYTextAfterTransaction(s)})}),callAll(e,[])}finally{g.gc&&tryGcDeleteSet(w,S,g.gcFilter),tryMergeDeleteSet(w,S),s.afterState.forEach((e,t)=>{let g=s.beforeState.get(t)||0;if(g!==e){let e=S.clients.get(t),s=max$2(findIndexSS(e,g),1);for(let t=e.length-1;t>=s;)t-=1+tryToMergeWithLefts(e,t)}});for(let e=E.length-1;e>=0;e--){let{client:t,clock:s}=E[e].id,g=S.clients.get(t),w=findIndexSS(g,s);w+1<g.length&&tryToMergeWithLefts(g,w+1)>1||w>0&&tryToMergeWithLefts(g,w)}if(!s.local&&s.afterState.get(g.clientID)!==s.beforeState.get(g.clientID)&&(print(ORANGE,BOLD,`[yjs] `,UNBOLD,RED,`Changed the client-id because another client seems to be using it.`),g.clientID=generateNewClientId()),g.emit(`afterTransactionCleanup`,[s,g]),g._observers.has(`update`)){let e=new UpdateEncoderV1;writeUpdateMessageFromTransaction(e,s)&&g.emit(`update`,[e.toUint8Array(),s.origin,g,s])}if(g._observers.has(`updateV2`)){let e=new UpdateEncoderV2;writeUpdateMessageFromTransaction(e,s)&&g.emit(`updateV2`,[e.toUint8Array(),s.origin,g,s])}let{subdocsAdded:D,subdocsLoaded:O,subdocsRemoved:k}=s;(D.size>0||k.size>0||O.size>0)&&(D.forEach(e=>{e.clientID=g.clientID,e.collectionid??=g.collectionid,g.subdocs.add(e)}),k.forEach(e=>g.subdocs.delete(e)),g.emit(`subdocs`,[{loaded:O,added:D,removed:k},g,s]),k.forEach(e=>e.destroy())),e.length<=t+1?(g._transactionCleanups=[],g.emit(`afterAllTransactions`,[g,e])):cleanupTransactions(e,t+1)}}},transact=(e,t,s=null,g=!0)=>{let S=e._transactionCleanups,w=!1,E=null;e._transaction===null&&(w=!0,e._transaction=new Transaction(e,s,g),S.push(e._transaction),S.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{E=t(e._transaction)}finally{if(w){let t=e._transaction===S[0];e._transaction=null,t&&cleanupTransactions(S,0)}}return E};var StackItem=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const clearUndoManagerStackItem=(e,t,s)=>{iterateDeletedStructs(e,s.deletions,s=>{s instanceof Item&&t.scope.some(t=>t===e.doc||isParentOf(t,s))&&keepItem(s,!1)})},popStackItem=(e,t,s)=>{let g=null,S=e.doc,w=e.scope;transact(S,s=>{for(;t.length>0&&e.currStackItem===null;){let g=S.store,E=t.pop(),D=new Set,O=[],k=!1;iterateDeletedStructs(s,E.insertions,e=>{if(e instanceof Item){if(e.redone!==null){let{item:t,diff:S}=followRedone(g,e.id);S>0&&(t=getItemCleanStart(s,createID(t.id.client,t.id.clock+S))),e=t}!e.deleted&&w.some(t=>t===s.doc||isParentOf(t,e))&&O.push(e)}}),iterateDeletedStructs(s,E.deletions,e=>{e instanceof Item&&w.some(t=>t===s.doc||isParentOf(t,e))&&!isDeleted(E.insertions,e.id)&&D.add(e)}),D.forEach(t=>{k=redoItem(s,t,D,E.insertions,e.ignoreRemoteMapChanges,e)!==null||k});for(let t=O.length-1;t>=0;t--){let g=O[t];e.deleteFilter(g)&&(g.delete(s),k=!0)}e.currStackItem=k?E:null}s.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),g=s},e);let E=e.currStackItem;if(E!=null){let t=g.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:E,type:s,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return E};var UndoManager=class extends ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:s=e=>!0,deleteFilter:g=()=>!0,trackedOrigins:S=new Set([null]),ignoreRemoteMapChanges:w=!1,doc:E=isArray$1(e)?e[0].doc:e instanceof Doc?e:e.doc}={}){super(),this.scope=[],this.doc=E,this.addToScope(e),this.deleteFilter=g,S.add(this),this.trackedOrigins=S,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=w,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,s=this.redoing,g=t?this.redoStack:this.undoStack;t?this.stopCapturing():s||this.clear(!1,!0);let S=new DeleteSet;e.afterState.forEach((t,s)=>{let g=e.beforeState.get(s)||0,w=t-g;w>0&&addToDeleteSet(S,s,g,w)});let w=getUnixTime$1(),E=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&g.length>0&&!t&&!s){let t=g[g.length-1];t.deletions=mergeDeleteSets([t.deletions,e.deleteSet]),t.insertions=mergeDeleteSets([t.insertions,S])}else g.push(new StackItem(e.deleteSet,S)),E=!0;!t&&!s&&(this.lastChange=w),iterateDeletedStructs(e,e.deleteSet,t=>{t instanceof Item&&this.scope.some(s=>s===e.doc||isParentOf(s,t))&&keepItem(t,!0)});let D=[{stackItem:g[g.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];E?this.emit(`stack-item-added`,D):this.emit(`stack-item-updated`,D)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=isArray$1(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof AbstractType?e.doc!==this.doc:e!==this.doc)&&warn(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(e=>clearUndoManagerStackItem(s,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>clearUndoManagerStackItem(s,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=popStackItem(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=popStackItem(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*lazyStructReaderGenerator(e){let t=readVarUint$1(e.restDecoder);for(let s=0;s<t;s++){let t=readVarUint$1(e.restDecoder),s=e.readClient(),g=readVarUint$1(e.restDecoder);for(let S=0;S<t;S++){let t=e.readInfo();if(t===10){let t=readVarUint$1(e.restDecoder);yield new Skip(createID(s,g),t),g+=t}else if(31&t){let S=(t&192)==0,w=new Item(createID(s,g),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,S?e.readParentInfo()?e.readString():e.readLeftID():null,S&&(t&32)==32?e.readString():null,readItemContent(e,t));yield w,g+=w.length}else{let t=e.readLen();yield new GC(createID(s,g),t),g+=t}}}}var LazyStructReader=class{constructor(e,t){this.gen=lazyStructReaderGenerator(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Skip);return this.curr}},LazyStructWriter=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const mergeUpdates=e=>mergeUpdatesV2(e,UpdateDecoderV1,UpdateEncoderV1),sliceStruct=(e,t)=>{if(e.constructor===GC){let{client:s,clock:g}=e.id;return new GC(createID(s,g+t),e.length-t)}else if(e.constructor===Skip){let{client:s,clock:g}=e.id;return new Skip(createID(s,g+t),e.length-t)}else{let s=e,{client:g,clock:S}=s.id;return new Item(createID(g,S+t),null,createID(g,S+t-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(t))}},mergeUpdatesV2=(e,t=UpdateDecoderV2,s=UpdateEncoderV2)=>{if(e.length===1)return e[0];let g=e.map(e=>new t(createDecoder$1(e))),S=g.map(e=>new LazyStructReader(e,!0)),w=null,E=new s,D=new LazyStructWriter(E);for(;S=S.filter(e=>e.curr!==null),S.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let s=e.curr.id.clock-t.curr.id.clock;return s===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Skip?1:-1:s}else return t.curr.id.client-e.curr.id.client}),S.length!==0;){let e=S[0],t=e.curr.id.client;if(w!==null){let s=e.curr,g=!1;for(;s!==null&&s.id.clock+s.length<=w.struct.id.clock+w.struct.length&&s.id.client>=w.struct.id.client;)s=e.next(),g=!0;if(s===null||s.id.client!==t||g&&s.id.clock>w.struct.id.clock+w.struct.length)continue;if(t!==w.struct.id.client)writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0},e.next();else if(w.struct.id.clock+w.struct.length<s.id.clock)if(w.struct.constructor===Skip)w.struct.length=s.id.clock+s.length-w.struct.id.clock;else{writeStructToLazyStructWriter(D,w.struct,w.offset);let e=s.id.clock-w.struct.id.clock-w.struct.length;w={struct:new Skip(createID(t,w.struct.id.clock+w.struct.length),e),offset:0}}else{let t=w.struct.id.clock+w.struct.length-s.id.clock;t>0&&(w.struct.constructor===Skip?w.struct.length-=t:s=sliceStruct(s,t)),w.struct.mergeWith(s)||(writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0},e.next())}}else w={struct:e.curr,offset:0},e.next();for(let s=e.curr;s!==null&&s.id.client===t&&s.id.clock===w.struct.id.clock+w.struct.length&&s.constructor!==Skip;s=e.next())writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0}}return w!==null&&(writeStructToLazyStructWriter(D,w.struct,w.offset),w=null),finishLazyStructWriting(D),writeDeleteSet(E,mergeDeleteSets(g.map(e=>readDeleteSet(e)))),E.toUint8Array()},diffUpdateV2=(e,t,s=UpdateDecoderV2,g=UpdateEncoderV2)=>{let S=decodeStateVector(t),w=new g,E=new LazyStructWriter(w),D=new s(createDecoder$1(e)),O=new LazyStructReader(D,!1);for(;O.curr;){let e=O.curr,t=e.id.client,s=S.get(t)||0;if(O.curr.constructor===Skip){O.next();continue}if(e.id.clock+e.length>s)for(writeStructToLazyStructWriter(E,e,max$2(s-e.id.clock,0)),O.next();O.curr&&O.curr.id.client===t;)writeStructToLazyStructWriter(E,O.curr,0),O.next();else for(;O.curr&&O.curr.id.client===t&&O.curr.id.clock+O.curr.length<=s;)O.next()}return finishLazyStructWriting(E),writeDeleteSet(w,readDeleteSet(D)),w.toUint8Array()},flushLazyStructWriter=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:toUint8Array$1(e.encoder.restEncoder)}),e.encoder.restEncoder=createEncoder$1(),e.written=0)},writeStructToLazyStructWriter=(e,t,s)=>{e.written>0&&e.currClient!==t.id.client&&flushLazyStructWriter(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),writeVarUint$2(e.encoder.restEncoder,t.id.clock+s)),t.write(e.encoder,s),e.written++},finishLazyStructWriting=e=>{flushLazyStructWriter(e);let t=e.encoder.restEncoder;writeVarUint$2(t,e.clientStructs.length);for(let s=0;s<e.clientStructs.length;s++){let g=e.clientStructs[s];writeVarUint$2(t,g.written),writeUint8Array$2(t,g.restEncoder)}},convertUpdateFormat=(e,t,s,g)=>{let S=new s(createDecoder$1(e)),w=new LazyStructReader(S,!1),E=new g,D=new LazyStructWriter(E);for(let e=w.curr;e!==null;e=w.next())writeStructToLazyStructWriter(D,t(e),0);return finishLazyStructWriting(D),writeDeleteSet(E,readDeleteSet(S)),E.toUint8Array()},convertUpdateFormatV2ToV1=e=>convertUpdateFormat(e,id,UpdateDecoderV2,UpdateEncoderV1),errorComputeChanges=`You must not compute changes after the event-handler fired.`;var YEvent=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=getPathTo(this.currentTarget,this.target)}deletes(e){return isDeleted(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){let g=t._map.get(s),S,w;if(this.adds(g)){let e=g.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(g))if(e!==null&&this.deletes(e))S=`delete`,w=last(e.content.getContent());else return;else e!==null&&this.deletes(e)?(S=`update`,w=last(e.content.getContent())):(S=`add`,w=void 0)}else if(this.deletes(g))S=`delete`,w=last(g.content.getContent());else return;e.set(s,{action:S,oldValue:w})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let t=this.target,s=create$7(),g=create$7(),S=[];if(e={added:s,deleted:g,delta:S,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,w=()=>{e&&S.push(e)};for(let S=t._start;S!==null;S=S.right)S.deleted?this.deletes(S)&&!this.adds(S)&&((e===null||e.delete===void 0)&&(w(),e={delete:0}),e.delete+=S.length,g.add(S)):this.adds(S)?((e===null||e.insert===void 0)&&(w(),e={insert:[]}),e.insert=e.insert.concat(S.content.getContent()),s.add(S)):((e===null||e.retain===void 0)&&(w(),e={retain:0}),e.retain+=S.length);e!==null&&e.retain===void 0&&w()}this._changes=e}return e}};const getPathTo=(e,t)=>{let s=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)s.unshift(t._item.parentSub);else{let e=0,g=t._item.parent._start;for(;g!==t._item&&g!==null;)!g.deleted&&g.countable&&(e+=g.length),g=g.right;s.unshift(e)}t=t._item.parent}return s},warnPrematureAccess=()=>{warn(`Invalid access: Add Yjs type to a document before reading data.`)},maxSearchMarker=80;let globalSearchMarkerTimestamp=0;var ArraySearchMarker=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=globalSearchMarkerTimestamp++}};const refreshMarkerTimestamp=e=>{e.timestamp=globalSearchMarkerTimestamp++},overwriteMarker=(e,t,s)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=s,e.timestamp=globalSearchMarkerTimestamp++},markPosition=(e,t,s)=>{if(e.length>=maxSearchMarker){let g=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return overwriteMarker(g,t,s),g}else{let g=new ArraySearchMarker(t,s);return e.push(g),g}},findMarker=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let s=e._searchMarker.length===0?null:e._searchMarker.reduce((e,s)=>abs(t-e.index)<abs(t-s.index)?e:s),g=e._start,S=0;for(s!==null&&(g=s.p,S=s.index,refreshMarkerTimestamp(s));g.right!==null&&S<t;){if(!g.deleted&&g.countable){if(t<S+g.length)break;S+=g.length}g=g.right}for(;g.left!==null&&S>t;)g=g.left,!g.deleted&&g.countable&&(S-=g.length);for(;g.left!==null&&g.left.id.client===g.id.client&&g.left.id.clock+g.left.length===g.id.clock;)g=g.left,!g.deleted&&g.countable&&(S-=g.length);return s!==null&&abs(s.index-S)<g.parent.length/maxSearchMarker?(overwriteMarker(s,g,S),s):markPosition(e._searchMarker,g,S)},updateMarkerChanges=(e,t,s)=>{for(let g=e.length-1;g>=0;g--){let S=e[g];if(s>0){let t=S.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(S.index-=t.length);if(t===null||t.marker===!0){e.splice(g,1);continue}S.p=t,t.marker=!0}(t<S.index||s>0&&t===S.index)&&(S.index=max$2(t,S.index+s))}},callTypeObservers=(e,t,s)=>{let g=e,S=t.changedParentTypes;for(;setIfUndefined$1(S,e,()=>[]).push(s),e._item!==null;)e=e._item.parent;callEventHandlerListeners(g._eH,s,t)};var AbstractType=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=createEventHandler(),this._dEH=createEventHandler(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw methodUnimplemented()}clone(){throw methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){addEventHandlerListener(this._eH,e)}observeDeep(e){addEventHandlerListener(this._dEH,e)}unobserve(e){removeEventHandlerListener(this._eH,e)}unobserveDeep(e){removeEventHandlerListener(this._dEH,e)}toJSON(){}};const typeListSlice=(e,t,s)=>{e.doc??warnPrematureAccess(),t<0&&(t=e._length+t),s<0&&(s=e._length+s);let g=s-t,S=[],w=e._start;for(;w!==null&&g>0;){if(w.countable&&!w.deleted){let e=w.content.getContent();if(e.length<=t)t-=e.length;else{for(let s=t;s<e.length&&g>0;s++)S.push(e[s]),g--;t=0}}w=w.right}return S},typeListToArray=e=>{e.doc??warnPrematureAccess();let t=[],s=e._start;for(;s!==null;){if(s.countable&&!s.deleted){let e=s.content.getContent();for(let s=0;s<e.length;s++)t.push(e[s])}s=s.right}return t},typeListToArraySnapshot=(e,t)=>{let s=[],g=e._start;for(;g!==null;){if(g.countable&&isVisible$1(g,t)){let e=g.content.getContent();for(let t=0;t<e.length;t++)s.push(e[t])}g=g.right}return s},typeListForEach=(e,t)=>{let s=0,g=e._start;for(e.doc??warnPrematureAccess();g!==null;){if(g.countable&&!g.deleted){let S=g.content.getContent();for(let g=0;g<S.length;g++)t(S[g],s++,e)}g=g.right}},typeListMap=(e,t)=>{let s=[];return typeListForEach(e,(g,S)=>{s.push(t(g,S,e))}),s},typeListCreateIterator=e=>{let t=e._start,s=null,g=0;return{[Symbol.iterator](){return this},next:()=>{if(s===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};s=t.content.getContent(),g=0,t=t.right}let e=s[g++];return s.length<=g&&(s=null),{done:!1,value:e}}}},typeListGet=(e,t)=>{e.doc??warnPrematureAccess();let s=findMarker(e,t),g=e._start;for(s!==null&&(g=s.p,t-=s.index);g!==null;g=g.right)if(!g.deleted&&g.countable){if(t<g.length)return g.content.getContent()[t];t-=g.length}},typeListInsertGenericsAfter=(e,t,s,g)=>{let S=s,w=e.doc,E=w.clientID,D=w.store,O=s===null?t._start:s.right,k=[],j=()=>{k.length>0&&(S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentAny(k)),S.integrate(e,0),k=[])};g.forEach(s=>{if(s===null)k.push(s);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:k.push(s);break;default:switch(j(),s.constructor){case Uint8Array:case ArrayBuffer:S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentBinary(new Uint8Array(s))),S.integrate(e,0);break;case Doc:S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentDoc(s)),S.integrate(e,0);break;default:if(s instanceof AbstractType)S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentType(s)),S.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),j()},lengthExceeded=()=>create$6(`Length exceeded!`),typeListInsertGenerics=(e,t,s,g)=>{if(s>t._length)throw lengthExceeded();if(s===0)return t._searchMarker&&updateMarkerChanges(t._searchMarker,s,g.length),typeListInsertGenericsAfter(e,t,null,g);let S=s,w=findMarker(t,s),E=t._start;for(w!==null&&(E=w.p,s-=w.index,s===0&&(E=E.prev,s+=E&&E.countable&&!E.deleted?E.length:0));E!==null;E=E.right)if(!E.deleted&&E.countable){if(s<=E.length){s<E.length&&getItemCleanStart(e,createID(E.id.client,E.id.clock+s));break}s-=E.length}return t._searchMarker&&updateMarkerChanges(t._searchMarker,S,g.length),typeListInsertGenericsAfter(e,t,E,g)},typeListPushGenerics=(e,t,s)=>{let g=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(g)for(;g.right;)g=g.right;return typeListInsertGenericsAfter(e,t,g,s)},typeListDelete=(e,t,s,g)=>{if(g===0)return;let S=s,w=g,E=findMarker(t,s),D=t._start;for(E!==null&&(D=E.p,s-=E.index);D!==null&&s>0;D=D.right)!D.deleted&&D.countable&&(s<D.length&&getItemCleanStart(e,createID(D.id.client,D.id.clock+s)),s-=D.length);for(;g>0&&D!==null;)D.deleted||(g<D.length&&getItemCleanStart(e,createID(D.id.client,D.id.clock+g)),D.delete(e),g-=D.length),D=D.right;if(g>0)throw lengthExceeded();t._searchMarker&&updateMarkerChanges(t._searchMarker,S,-w+g)},typeMapDelete=(e,t,s)=>{let g=t._map.get(s);g!==void 0&&g.delete(e)},typeMapSet=(e,t,s,g)=>{let S=t._map.get(s)||null,w=e.doc,E=w.clientID,D;if(g==null)D=new ContentAny([g]);else switch(g.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:D=new ContentAny([g]);break;case Uint8Array:D=new ContentBinary(g);break;case Doc:D=new ContentDoc(g);break;default:if(g instanceof AbstractType)D=new ContentType(g);else throw Error(`Unexpected content type`)}new Item(createID(E,getState(w.store,E)),S,S&&S.lastId,null,null,t,s,D).integrate(e,0)},typeMapGet=(e,t)=>{e.doc??warnPrematureAccess();let s=e._map.get(t);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},typeMapGetAll=e=>{let t={};return e.doc??warnPrematureAccess(),e._map.forEach((e,s)=>{e.deleted||(t[s]=e.content.getContent()[e.length-1])}),t},typeMapHas=(e,t)=>{e.doc??warnPrematureAccess();let s=e._map.get(t);return s!==void 0&&!s.deleted},typeMapGetAllSnapshot=(e,t)=>{let s={};return e._map.forEach((e,g)=>{let S=e;for(;S!==null&&(!t.sv.has(S.id.client)||S.id.clock>=(t.sv.get(S.id.client)||0));)S=S.left;S!==null&&isVisible$1(S,t)&&(s[g]=S.content.getContent()[S.length-1])}),s},createMapIterator=e=>(e.doc??warnPrematureAccess(),iteratorFilter(e._map.entries(),e=>!e[1].deleted));var YArrayEvent=class extends YEvent{},YArray=class e extends AbstractType{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let s=new e;return s.push(t),s}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._length}_callObserver(e,t){super._callObserver(e,t),callTypeObservers(this,e,new YArrayEvent(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,s=>{typeListInsertGenerics(s,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):transact(this.doc,t=>{typeListPushGenerics(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,s=>{typeListDelete(s,this,e,t)})}get(e){return typeListGet(this,e)}toArray(){return typeListToArray(this)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}toJSON(){return this.map(e=>e instanceof AbstractType?e.toJSON():e)}map(e){return typeListMap(this,e)}forEach(e){typeListForEach(this,e)}[Symbol.iterator](){return typeListCreateIterator(this)}_write(e){e.writeTypeRef(YArrayRefID)}};const readYArray=e=>new YArray;var YMapEvent=class extends YEvent{constructor(e,t,s){super(e,t),this.keysChanged=s}},YMap=class e extends AbstractType{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,s)=>{t.set(s,e instanceof AbstractType?e.clone():e)}),t}_callObserver(e,t){callTypeObservers(this,e,new YMapEvent(this,e,t))}toJSON(){this.doc??warnPrematureAccess();let e={};return this._map.forEach((t,s)=>{if(!t.deleted){let g=t.content.getContent()[t.length-1];e[s]=g instanceof AbstractType?g.toJSON():g}}),e}get size(){return[...createMapIterator(this)].length}keys(){return iteratorMap(createMapIterator(this),e=>e[0])}values(){return iteratorMap(createMapIterator(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return iteratorMap(createMapIterator(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??warnPrematureAccess(),this._map.forEach((t,s)=>{t.deleted||e(t.content.getContent()[t.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):transact(this.doc,s=>{typeMapSet(s,this,e,t)}),t}get(e){return typeMapGet(this,e)}has(e){return typeMapHas(this,e)}clear(){this.doc===null?this._prelimContent.clear():transact(this.doc,e=>{this.forEach(function(t,s,g){typeMapDelete(e,g,s)})})}_write(e){e.writeTypeRef(YMapRefID)}};const readYMap=e=>new YMap,equalAttrs$1=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&equalFlat(e,t);var ItemTextListPosition=class{constructor(e,t,s,g){this.left=e,this.right=t,this.index=s,this.currentAttributes=g}forward(){switch(this.right===null&&unexpectedCase(),this.right.content.constructor){case ContentFormat:this.right.deleted||updateCurrentAttributes(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const findNextPosition=(e,t,s)=>{for(;t.right!==null&&s>0;){switch(t.right.content.constructor){case ContentFormat:t.right.deleted||updateCurrentAttributes(t.currentAttributes,t.right.content);break;default:t.right.deleted||(s<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+s)),t.index+=t.right.length,s-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},findPosition=(e,t,s,g)=>{let S=new Map,w=g?findMarker(t,s):null;return w?findNextPosition(e,new ItemTextListPosition(w.p.left,w.p,w.index,S),s-w.index):findNextPosition(e,new ItemTextListPosition(null,t._start,0,S),s)},insertNegatedAttributes=(e,t,s,g)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===ContentFormat&&equalAttrs$1(g.get(s.right.content.key),s.right.content.value));)s.right.deleted||g.delete(s.right.content.key),s.forward();let S=e.doc,w=S.clientID;g.forEach((g,E)=>{let D=s.left,O=s.right,k=new Item(createID(w,getState(S.store,w)),D,D&&D.lastId,O,O&&O.id,t,null,new ContentFormat(E,g));k.integrate(e,0),s.right=k,s.forward()})},updateCurrentAttributes=(e,t)=>{let{key:s,value:g}=t;g===null?e.delete(s):e.set(s,g)},minimizeAttributeChanges=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ContentFormat&&equalAttrs$1(t[e.right.content.key]??null,e.right.content.value));)e.forward()},insertAttributes=(e,t,s,g)=>{let S=e.doc,w=S.clientID,E=new Map;for(let D in g){let O=g[D],k=s.currentAttributes.get(D)??null;if(!equalAttrs$1(k,O)){E.set(D,k);let{left:g,right:j}=s;s.right=new Item(createID(w,getState(S.store,w)),g,g&&g.lastId,j,j&&j.id,t,null,new ContentFormat(D,O)),s.right.integrate(e,0),s.forward()}}return E},insertText=(e,t,s,g,S)=>{s.currentAttributes.forEach((e,t)=>{S[t]===void 0&&(S[t]=null)});let w=e.doc,E=w.clientID;minimizeAttributeChanges(s,S);let D=insertAttributes(e,t,s,S),O=g.constructor===String?new ContentString(g):g instanceof AbstractType?new ContentType(g):new ContentEmbed(g),{left:k,right:j,index:F}=s;t._searchMarker&&updateMarkerChanges(t._searchMarker,s.index,O.getLength()),j=new Item(createID(E,getState(w.store,E)),k,k&&k.lastId,j,j&&j.id,t,null,O),j.integrate(e,0),s.right=j,s.index=F,s.forward(),insertNegatedAttributes(e,t,s,D)},formatText=(e,t,s,g,S)=>{let w=e.doc,E=w.clientID;minimizeAttributeChanges(s,S);let D=insertAttributes(e,t,s,S);iterationLoop:for(;s.right!==null&&(g>0||D.size>0&&(s.right.deleted||s.right.content.constructor===ContentFormat));){if(!s.right.deleted)switch(s.right.content.constructor){case ContentFormat:{let{key:t,value:w}=s.right.content,E=S[t];if(E!==void 0){if(equalAttrs$1(E,w))D.delete(t);else{if(g===0)break iterationLoop;D.set(t,w)}s.right.delete(e)}else s.currentAttributes.set(t,w);break}default:g<s.right.length&&getItemCleanStart(e,createID(s.right.id.client,s.right.id.clock+g)),g-=s.right.length;break}s.forward()}if(g>0){let S=``;for(;g>0;g--)S+=`
|
|
14
|
+
`,(0,g.getConflictResolutionRecipe)(S,e))}return w}}})),require_MultiWritableMetricStorage$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,s,g){this._backingStorages.forEach(S=>{S.record(e,t,s,g)})}}})),require_ObservableResult$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_HashMap$2(),g=require_Instruments$2();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new s.AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,s={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(s,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,S,w={}){if(!(0,g.isObservableInstrument)(e))return;let E=this._buffer.get(e);if(E??(E=new s.AttributeHashMap,this._buffer.set(e,E)),typeof S!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${S}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(S)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),S=Math.trunc(S),!Number.isInteger(S))||E.set(w,S)}}})),require_ObservableRegistry$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Instruments$2(),g=require_ObservableResult$2(),S=require_utils$13();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let s=this._findCallback(e,t);s<0||this._callbacks.splice(s,1)}addBatchCallback(e,g){let S=new Set(g.filter(s.isObservableInstrument));if(S.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,g);return}this._findBatchCallback(e,S)>=0||this._batchCallbacks.push({callback:e,instruments:S})}removeBatchCallback(e,t){let g=new Set(t.filter(s.isObservableInstrument)),S=this._findBatchCallback(e,g);S<0||this._batchCallbacks.splice(S,1)}async observe(e,t){let s=this._observeCallbacks(e,t),g=this._observeBatchCallbacks(e,t);return(await(0,S.PromiseAllSettled)([...s,...g])).filter(S.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:s,instrument:w})=>{let E=new g.ObservableResultImpl(w._descriptor.name,w._descriptor.valueType),D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w._metricStorages.forEach(t=>{t.record(E._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:s,instruments:w})=>{let E=new g.BatchObservableResultImpl,D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w.forEach(t=>{let s=E._buffer.get(t);s!=null&&t._metricStorages.forEach(t=>{t.record(s,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(s=>s.callback===e&&s.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(s=>s.callback===e&&(0,S.setEquals)(s.instruments,t))}}})),require_SyncMetricStorage$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage$2(),s=require_DeltaMetricProcessor$2(),g=require_TemporalMetricProcessor$2();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,S,w,E){super(e),this._attributesProcessor=S,this._aggregationCardinalityLimit=E,this._deltaMetricStorage=new s.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new g.TemporalMetricProcessor(t,w)}record(e,t,s,g){t=this._attributesProcessor.process(t,s),this._deltaMetricStorage.record(e,t,s,g)}collect(e,t){let s=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,s,t)}}})),require_AttributesProcessor$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},s=class{_processors;constructor(e){this._processors=e}process(e,t){let s=e;for(let e of this._processors)s=e.process(s,t);return s}},g=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let s={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>s[t]=e[t]),s}},S=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let s={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>s[t]=e[t]),s}};function w(){return k}e.createNoopAttributesProcessor=w;function E(e){return new s(e)}e.createMultiAttributesProcessor=E;function D(e){return new g(e)}e.createAllowListAttributesProcessor=D;function O(e){return new S(e)}e.createDenyListAttributesProcessor=O;let k=new t})),require_MeterSharedState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor$2(),s=require_Meter$2(),g=require_utils$13(),S=require_AsyncMetricStorage$2(),w=require_MetricStorageRegistry$2(),E=require_MultiWritableMetricStorage$2(),D=require_ObservableRegistry$2(),O=require_SyncMetricStorage$2(),k=require_AttributesProcessor$2();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new w.MetricStorageRegistry;observableRegistry=new D.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new s.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,O.SyncMetricStorage);return t.length===1?t[0]:new E.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,S.AsyncMetricStorage)}async collect(e,t,s){let S=await this.observableRegistry.observe(t,s?.timeoutMillis),w=this.metricStorageRegistry.getStorages(e);if(w.length===0)return null;let E=w.map(s=>s.collect(e,t)).filter(g.isNotNullish);return E.length===0?{errors:S}:{scopeMetrics:{scope:this._instrumentationScope,metrics:E},errors:S}}_registerMetricStorage(e,s){let g=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(g=>{let S=(0,t.createInstrumentDescriptorWithView)(g,e),w=this.metricStorageRegistry.findOrUpdateCompatibleStorage(S);if(w!=null)return w;let E=new s(S,g.aggregation.createAggregator(S),g.attributesProcessor,this._meterProviderSharedState.metricCollectors,g.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(g.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,g])=>{let S=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(S!=null)return S;let w=g.createAggregator(e),E=t.selectCardinalityLimit(e.type),D=new s(e,w,(0,k.createNoopAttributesProcessor)(),[t],E);return this.metricStorageRegistry.registerForCollector(t,D),D});g=g.concat(t)}return g}}})),require_MeterProviderSharedState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$13(),s=require_ViewRegistry$2(),g=require_MeterSharedState$2(),S=require_AggregationOption$2();e.MeterProviderSharedState=class{resource;viewRegistry=new s.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let s=(0,t.instrumentationScopeId)(e),S=this.meterSharedStates.get(s);return S??(S=new g.MeterSharedState(this,e),this.meterSharedStates.set(s,S)),S}selectAggregations(e){let t=[];for(let s of this.metricCollectors)t.push([s,(0,S.toAggregation)(s.selectAggregation(e))]);return t}}})),require_MetricCollector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$13();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let s=(0,t.millisToHrTime)(Date.now()),g=[],S=[],w=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let w=await t.collect(this,s,e);w?.scopeMetrics!=null&&g.push(w.scopeMetrics),w?.errors!=null&&S.push(...w.errors)});return await Promise.all(w),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:g},errors:S}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate$2();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate$2();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate$2(),s=require_AttributesProcessor$2(),g=require_InstrumentSelector$2(),S=require_MeterSelector$2(),w=require_AggregationOption$2();function E(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function D(e){if(E(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){D(e),e.attributesProcessors==null?this.attributesProcessor=(0,s.createNoopAttributesProcessor)():this.attributesProcessor=(0,s.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,w.toAggregation)(e.aggregation??{type:w.AggregationType.DEFAULT}),this.instrumentSelector=new g.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new S.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$12(),g=require_MeterProviderSharedState$2(),S=require_MetricCollector$2(),w=require_View$2();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new g.MeterProviderSharedState(e?.resource??(0,s.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new w.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new S.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,s=``,g={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:s,schemaUrl:g.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality$2();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var s=require_MetricData$2();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return s.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return s.InstrumentType}});var g=require_MetricReader$2();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return g.MetricReader}});var S=require_PeriodicExportingMetricReader$2();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return S.PeriodicExportingMetricReader}});var w=require_InMemoryMetricExporter$2();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return w.InMemoryMetricExporter}});var E=require_ConsoleMetricExporter$2();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return E.ConsoleMetricExporter}});var D=require_MeterProvider$2();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return D.MeterProvider}});var O=require_AggregationOption$2();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return O.AggregationType}});var k=require_AttributesProcessor$2();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return k.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return k.createDenyListAttributesProcessor}});var j=require_utils$13();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return j.TimeoutError}})})),require_internal_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.EAggregationTemporality=void 0,(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(e.EAggregationTemporality||={})})),require_internal$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportMetricsServiceRequest=e.toMetric=e.toScopeMetrics=e.toResourceMetrics=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$11(),g=require_internal_types(),S=require_utils$14(),w=require_internal$3();function E(e,t){let s=(0,S.getOtlpEncoder)(t),g=(0,w.createResource)(e.resource);return{resource:g,schemaUrl:g.schemaUrl,scopeMetrics:D(e.scopeMetrics,s)}}e.toResourceMetrics=E;function D(e,t){return Array.from(e.map(e=>({scope:(0,w.createInstrumentationScope)(e.scope),metrics:e.metrics.map(e=>O(e,t)),schemaUrl:e.scope.schemaUrl})))}e.toScopeMetrics=D;function O(e,t){let g={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},S=B(e.aggregationTemporality);switch(e.dataPointType){case s.DataPointType.SUM:g.sum={aggregationTemporality:S,isMonotonic:e.isMonotonic,dataPoints:j(e,t)};break;case s.DataPointType.GAUGE:g.gauge={dataPoints:j(e,t)};break;case s.DataPointType.HISTOGRAM:g.histogram={aggregationTemporality:S,dataPoints:F(e,t)};break;case s.DataPointType.EXPONENTIAL_HISTOGRAM:g.exponentialHistogram={aggregationTemporality:S,dataPoints:L(e,t)};break}return g}e.toMetric=O;function k(e,s,g){let S={attributes:(0,w.toAttributes)(e.attributes),startTimeUnixNano:g.encodeHrTime(e.startTime),timeUnixNano:g.encodeHrTime(e.endTime)};switch(s){case t.ValueType.INT:S.asInt=e.value;break;case t.ValueType.DOUBLE:S.asDouble=e.value;break}return S}function j(e,t){return e.dataPoints.map(s=>k(s,e.descriptor.valueType,t))}function F(e,t){return e.dataPoints.map(e=>{let s=e.value;return{attributes:(0,w.toAttributes)(e.attributes),bucketCounts:s.buckets.counts,explicitBounds:s.buckets.boundaries,count:s.count,sum:s.sum,min:s.min,max:s.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function L(e,t){return e.dataPoints.map(e=>{let s=e.value;return{attributes:(0,w.toAttributes)(e.attributes),count:s.count,min:s.min,max:s.max,sum:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},scale:s.scale,zeroCount:s.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function B(e){switch(e){case s.AggregationTemporality.DELTA:return g.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;case s.AggregationTemporality.CUMULATIVE:return g.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE}}function H(e,t){return{resourceMetrics:e.map(e=>E(e,t))}}e.createExportMetricsServiceRequest=H})),require_metrics$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;let t=require_root(),s=require_internal$1(),g=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,S=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.ProtobufMetricsSerializer={serializeRequest:e=>{let t=(0,s.createExportMetricsServiceRequest)([e]);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;var t=require_metrics$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return t.ProtobufMetricsSerializer}})})),require_internal=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportTraceServiceRequest=e.toOtlpSpanEvent=e.toOtlpLink=e.sdkSpanToOtlpSpan=void 0;let t=require_internal$3(),s=require_utils$14();function g(e,s){let g=e.spanContext(),E=e.status,D=e.parentSpanContext?.spanId?s.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:s.encodeSpanContext(g.traceId),spanId:s.encodeSpanContext(g.spanId),parentSpanId:D,traceState:g.traceState?.serialize(),name:e.name,kind:e.kind==null?0:e.kind+1,startTimeUnixNano:s.encodeHrTime(e.startTime),endTimeUnixNano:s.encodeHrTime(e.endTime),attributes:(0,t.toAttributes)(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>w(e,s)),droppedEventsCount:e.droppedEventsCount,status:{code:E.code,message:E.message},links:e.links.map(e=>S(e,s)),droppedLinksCount:e.droppedLinksCount}}e.sdkSpanToOtlpSpan=g;function S(e,s){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],spanId:s.encodeSpanContext(e.context.spanId),traceId:s.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpLink=S;function w(e,s){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],name:e.name,timeUnixNano:s.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpSpanEvent=w;function E(e,t){return{resourceSpans:O(e,(0,s.getOtlpEncoder)(t))}}e.createExportTraceServiceRequest=E;function D(e){let t=new Map;for(let s of e){let e=t.get(s.resource);e||(e=new Map,t.set(s.resource,e));let g=`${s.instrumentationScope.name}@${s.instrumentationScope.version||``}:${s.instrumentationScope.schemaUrl||``}`,S=e.get(g);S||(S=[],e.set(g,S)),S.push(s)}return t}function O(e,s){let S=D(e),w=[],E=S.entries(),O=E.next();for(;!O.done;){let[e,S]=O.value,D=[],k=S.values(),j=k.next();for(;!j.done;){let e=j.value;if(e.length>0){let S=e.map(e=>g(e,s));D.push({scope:(0,t.createInstrumentationScope)(e[0].instrumentationScope),spans:S,schemaUrl:e[0].instrumentationScope.schemaUrl})}j=k.next()}let F=(0,t.createResource)(e),L={resource:F,scopeSpans:D,schemaUrl:F.schemaUrl};w.push(L),O=E.next()}return w}})),require_trace$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;let t=require_root(),s=require_internal(),g=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,S=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.ProtobufTraceSerializer={serializeRequest:e=>{let t=(0,s.createExportTraceServiceRequest)(e);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;var t=require_trace$1();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return t.ProtobufTraceSerializer}})})),require_logs=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;let t=require_internal$2();e.JsonLogsSerializer={serializeRequest:e=>{let s=(0,t.createExportLogsServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;var t=require_logs();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return t.JsonLogsSerializer}})})),require_metrics=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;let t=require_internal$1();e.JsonMetricsSerializer={serializeRequest:e=>{let s=(0,t.createExportMetricsServiceRequest)([e],{useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;var t=require_metrics();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return t.JsonMetricsSerializer}})})),require_trace=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;let t=require_internal();e.JsonTraceSerializer={serializeRequest:e=>{let s=(0,t.createExportTraceServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(s))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;var t=require_trace();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return t.JsonTraceSerializer}})})),require_src$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=e.JsonMetricsSerializer=e.JsonLogsSerializer=e.ProtobufTraceSerializer=e.ProtobufMetricsSerializer=e.ProtobufLogsSerializer=void 0;var t=require_protobuf$2();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}});var s=require_protobuf$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return s.ProtobufMetricsSerializer}});var g=require_protobuf();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return g.ProtobufTraceSerializer}});var S=require_json$2();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return S.JsonLogsSerializer}});var w=require_json$1();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return w.JsonMetricsSerializer}});var E=require_json();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return E.JsonTraceSerializer}})}));const create$8=()=>new Map,copy=e=>{let t=create$8();return e.forEach((e,s)=>{t.set(s,e)}),t},setIfUndefined$1=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g},any=(e,t)=>{for(let[s,g]of e)if(t(g,s))return!0;return!1},create$7=()=>new Set,last=e=>e[e.length-1],appendTo=(e,t)=>{for(let s=0;s<t.length;s++)e.push(t[s])},from$1=Array.from,some=(e,t)=>{for(let s=0;s<e.length;s++)if(t(e[s],s,e))return!0;return!1},isArray$1=Array.isArray;var ObservableV2=class{constructor(){this._observers=create$8()}on(e,t){return setIfUndefined$1(this._observers,e,create$7).add(t),t}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from$1((this._observers.get(e)||create$8()).values()).forEach(e=>e(...t))}destroy(){this._observers=create$8()}};const floor$2=Math.floor,abs=Math.abs,min$2=(e,t)=>e<t?e:t,max$2=(e,t)=>e>t?e:t,isNaN$2=Number.isNaN,isNegativeZero=e=>e===0?1/e<0:e<0,BIT1=1,BIT2=2,BIT3=4,BIT4=8,BIT6=32,BIT7=64,BIT8$2=128,BIT18$2=1<<17,BIT19$2=1<<18,BIT20$2=1<<19,BIT21$2=1<<20,BIT22$2=1<<21,BIT23$2=1<<22,BIT24$2=1<<23,BIT25$2=1<<24,BIT26$2=1<<25,BIT27$2=1<<26,BIT28$2=1<<27,BIT29$2=1<<28,BIT30$2=1<<29,BIT31$2=1<<30,BITS5=31,BITS6=63,BITS7$2=127,BITS17=BIT18$2-1,BITS18=BIT19$2-1,BITS19=BIT20$2-1,BITS20=BIT21$2-1,BITS21=BIT22$2-1,BITS22=BIT23$2-1,BITS23=BIT24$2-1,BITS24=BIT25$2-1,BITS25=BIT26$2-1,BITS26=BIT27$2-1,BITS27=BIT28$2-1,BITS28=BIT29$2-1,BITS29=BIT30$2-1,BITS30=BIT31$2-1,BITS31=2147483647,BITS32=4294967295,MAX_SAFE_INTEGER$2=2**53-1,MIN_SAFE_INTEGER=-(2**53-1),HIGHEST_INT32=BITS31,HIGHEST_UINT32=BITS32,isInteger=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&floor$2(e)===e),isNaN$1=Number.isNaN,parseInt$1=Number.parseInt,fromCharCode$2=String.fromCharCode,fromCodePoint=String.fromCodePoint,MAX_UTF16_CHARACTER=fromCharCode$2(65535),toLowerCase=e=>e.toLowerCase(),trimLeftRegex=/^\s*/g,trimLeft=e=>e.replace(trimLeftRegex,``),fromCamelCaseRegex=/([A-Z])/g,fromCamelCase=(e,t)=>trimLeft(e.replace(fromCamelCaseRegex,e=>`${t}${toLowerCase(e)}`)),_encodeUtf8Polyfill$2=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$2=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$2=e=>utf8TextEncoder$2.encode(e),encodeUtf8$2=utf8TextEncoder$2?_encodeUtf8Native$2:_encodeUtf8Polyfill$2;let utf8TextDecoder$2=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$2&&utf8TextDecoder$2.decode(new Uint8Array).length===1&&(utf8TextDecoder$2=null);var Encoder$1=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder$1=()=>new Encoder$1,encode=e=>{let t=createEncoder$1();return e(t),toUint8Array$1(t)},length$1=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array$1=e=>{let t=new Uint8Array(length$1(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},verifyLen=(e,t)=>{let s=e.cbuf.length;s-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(max$2(s,t)*2),e.cpos=0)},write$2=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeUint8=write$2,writeVarUint$2=(e,t)=>{for(;t>127;)write$2(e,128|127&t),t=floor$2(t/128);write$2(e,127&t)},writeVarInt=(e,t)=>{let s=isNegativeZero(t);for(s&&(t=-t),write$2(e,(t>63?128:0)|(s?64:0)|63&t),t=floor$2(t/64);t>0;)write$2(e,(t>127?128:0)|127&t),t=floor$2(t/128)},_strBuffer$2=new Uint8Array(3e4),_maxStrBSize$2=_strBuffer$2.length/3,_writeVarStringNative$2=(e,t)=>{if(t.length<_maxStrBSize$2){let s=utf8TextEncoder$2.encodeInto(t,_strBuffer$2).written||0;writeVarUint$2(e,s);for(let t=0;t<s;t++)write$2(e,_strBuffer$2[t])}else writeVarUint8Array$2(e,encodeUtf8$2(t))},_writeVarStringPolyfill$2=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$2(e,g);for(let t=0;t<g;t++)write$2(e,s.codePointAt(t))},writeVarString$2=utf8TextEncoder$2&&utf8TextEncoder$2.encodeInto?_writeVarStringNative$2:_writeVarStringPolyfill$2,writeUint8Array$2=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$2(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$2(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$2=(e,t)=>{writeVarUint$2(e,t.byteLength),writeUint8Array$2(e,t)},writeOnDataView=(e,t)=>{verifyLen(e,t);let s=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,s},writeFloat32=(e,t)=>writeOnDataView(e,4).setFloat32(0,t,!1),writeFloat64=(e,t)=>writeOnDataView(e,8).setFloat64(0,t,!1),writeBigInt64=(e,t)=>writeOnDataView(e,8).setBigInt64(0,t,!1),floatTestBed=new DataView(new ArrayBuffer(4)),isFloat32=e=>(floatTestBed.setFloat32(0,e),floatTestBed.getFloat32(0)===e),writeAny=(e,t)=>{switch(typeof t){case`string`:write$2(e,119),writeVarString$2(e,t);break;case`number`:isInteger(t)&&abs(t)<=2147483647?(write$2(e,125),writeVarInt(e,t)):isFloat32(t)?(write$2(e,124),writeFloat32(e,t)):(write$2(e,123),writeFloat64(e,t));break;case`bigint`:write$2(e,122),writeBigInt64(e,t);break;case`object`:if(t===null)write$2(e,126);else if(isArray$1(t)){write$2(e,117),writeVarUint$2(e,t.length);for(let s=0;s<t.length;s++)writeAny(e,t[s])}else if(t instanceof Uint8Array)write$2(e,116),writeVarUint8Array$2(e,t);else{write$2(e,118);let s=Object.keys(t);writeVarUint$2(e,s.length);for(let g=0;g<s.length;g++){let S=s[g];writeVarString$2(e,S),writeAny(e,t[S])}}break;case`boolean`:write$2(e,t?120:121);break;default:write$2(e,127)}};var RleEncoder=class extends Encoder$1{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&writeVarUint$2(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const flushUintOptRleEncoder=e=>{e.count>0&&(writeVarInt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&writeVarUint$2(e.encoder,e.count-2))};var UintOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0}write(e){this.s===e?this.count++:(flushUintOptRleEncoder(this),this.count=1,this.s=e)}toUint8Array(){return flushUintOptRleEncoder(this),toUint8Array$1(this.encoder)}};const flushIntDiffOptRleEncoder=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);writeVarInt(e.encoder,t),e.count>1&&writeVarUint$2(e.encoder,e.count-2)}};var IntDiffOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(flushIntDiffOptRleEncoder(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return flushIntDiffOptRleEncoder(this),toUint8Array$1(this.encoder)}},StringEncoder=class{constructor(){this.sarr=[],this.s=``,this.lensE=new UintOptRleEncoder}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Encoder$1;return this.sarr.push(this.s),this.s=``,writeVarString$2(e,this.sarr.join(``)),writeUint8Array$2(e,this.lensE.toUint8Array()),toUint8Array$1(e)}};const create$6=e=>Error(e),methodUnimplemented=()=>{throw create$6(`Method unimplemented`)},unexpectedCase=()=>{throw create$6(`Unexpected case`)},errorUnexpectedEndOfArray$2=create$6(`Unexpected end of array`),errorIntegerOutOfRange$2=create$6(`Integer out of Range`);var Decoder$1=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder$1=e=>new Decoder$1(e),hasContent$1=e=>e.pos!==e.arr.length,readUint8Array$1=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array$1=e=>readUint8Array$1(e,readVarUint$1(e)),readUint8$1=e=>e.arr[e.pos++],readVarUint$1=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&127)*s,s*=128,g<128)return t;if(t>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},readVarInt=e=>{let t=e.arr[e.pos++],s=t&63,g=64,S=(t&64)>0?-1:1;if(!(t&128))return S*s;let w=e.arr.length;for(;e.pos<w;){if(t=e.arr[e.pos++],s+=(t&127)*g,g*=128,t<128)return S*s;if(s>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},_readVarStringPolyfill$1=e=>{let t=readVarUint$1(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8$1(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8$1(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative$1=e=>utf8TextDecoder$2.decode(readVarUint8Array$1(e)),readVarString$1=utf8TextDecoder$2?_readVarStringNative$1:_readVarStringPolyfill$1,readFromDataView=(e,t)=>{let s=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,s},readFloat32=e=>readFromDataView(e,4).getFloat32(0,!1),readFloat64=e=>readFromDataView(e,8).getFloat64(0,!1),readBigInt64=e=>readFromDataView(e,8).getBigInt64(0,!1),readAnyLookupTable=[e=>void 0,e=>null,readVarInt,readFloat32,readFloat64,readBigInt64,e=>!1,e=>!0,readVarString$1,e=>{let t=readVarUint$1(e),s={};for(let g=0;g<t;g++){let t=readVarString$1(e);s[t]=readAny(e)}return s},e=>{let t=readVarUint$1(e),s=[];for(let g=0;g<t;g++)s.push(readAny(e));return s},readVarUint8Array$1],readAny=e=>readAnyLookupTable[127-readUint8$1(e)](e);var RleDecoder=class extends Decoder$1{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hasContent$1(this)?this.count=readVarUint$1(this)+1:this.count=-1),this.count--,this.s}},UintOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=readVarInt(this);let e=isNegativeZero(this.s);this.count=1,e&&(this.s=-this.s,this.count=readVarUint$1(this)+2)}return this.count--,this.s}},IntDiffOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=readVarInt(this),t=e&1;this.diff=floor$2(e/2),this.count=1,t&&(this.count=readVarUint$1(this)+2)}return this.s+=this.diff,this.count--,this.s}},StringDecoder=class{constructor(e){this.decoder=new UintOptRleDecoder(e),this.str=readVarString$1(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};const subtle=webcrypto.subtle,getRandomValues=webcrypto.getRandomValues.bind(webcrypto),uint32=()=>getRandomValues(new Uint32Array(1))[0],uuidv4Template=`10000000-1000-4000-8000-100000000000`,uuidv4=()=>uuidv4Template.replace(/[018]/g,e=>(e^uint32()&15>>e/4).toString(16)),getUnixTime$1=Date.now,create$5=e=>new Promise(e),all=Promise.all.bind(Promise),undefinedToNull=e=>e===void 0?null:e;var VarStoragePolyfill=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};let _localStorage=new VarStoragePolyfill,usePolyfill=!0;try{typeof localStorage<`u`&&localStorage&&(_localStorage=localStorage)}catch{}const varStorage=_localStorage,EqualityTraitSymbol$1=Symbol(`Equality`),equals=(e,t)=>e===t||!!e?.[EqualityTraitSymbol$1]?.(t)||!1,assign=Object.assign,keys$1=Object.keys,forEach=(e,t)=>{for(let s in e)t(e[s],s)},size$1=e=>keys$1(e).length,isEmpty$3=e=>{for(let t in e)return!1;return!0},every=(e,t)=>{for(let s in e)if(!t(e[s],s))return!1;return!0},hasProperty$1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalFlat=(e,t)=>e===t||size$1(e)===size$1(t)&&every(e,(e,s)=>(e!==void 0||hasProperty$1(t,s))&&equals(t[s],e)),freeze=Object.freeze,deepFreeze=e=>{for(let t in e){let s=e[t];(typeof s==`object`||typeof s==`function`)&&deepFreeze(e[t])}return freeze(e)},callAll=(e,t,s=0)=>{try{for(;s<e.length;s++)e[s](...t)}finally{s<e.length&&callAll(e,t,s+1)}},id=e=>e,isOneOf=(e,t)=>t.includes(e),isArray=isArray$1,isNode=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,isBrowser=typeof window<`u`&&typeof document<`u`&&!isNode,isMac=typeof navigator<`u`?/Mac/.test(navigator.platform):!1;let params;const args=[],computeParams=()=>{if(params===void 0)if(isNode){params=create$8();let e=process.argv,t=null;for(let s=0;s<e.length;s++){let g=e[s];g[0]===`-`?(t!==null&¶ms.set(t,``),t=g):t===null?args.push(g):(params.set(t,g),t=null)}t!==null&¶ms.set(t,``)}else typeof location==`object`?(params=create$8(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,s]=e.split(`=`);params.set(`--${fromCamelCase(t,`-`)}`,s),params.set(`-${fromCamelCase(t,`-`)}`,s)}})):params=create$8();return params},hasParam=e=>computeParams().has(e),getVariable=e=>undefinedToNull(isNode?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:varStorage.getItem(e)),hasConf=e=>hasParam(`--`+e)||getVariable(e)!==null,production=hasConf(`production`),forceColor=isNode&&isOneOf(process.env.FORCE_COLOR,[`true`,`1`,`2`]),supportsColor=forceColor||!hasParam(`--no-colors`)&&!hasConf(`no-color`)&&(!isNode||process.stdout.isTTY)&&(!isNode||hasParam(`--color`)||getVariable(`COLORTERM`)!==null||(getVariable(`TERM`)||``).includes(`color`)),createUint8ArrayFromLen=e=>new Uint8Array(e),createUint8ArrayViewFromArrayBuffer=(e,t,s)=>new Uint8Array(e,t,s),toBase64Browser=e=>{let t=``;for(let s=0;s<e.byteLength;s++)t+=fromCharCode$2(e[s]);return btoa(t)},toBase64Node=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),fromBase64Browser=e=>{let t=atob(e),s=createUint8ArrayFromLen(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s},fromBase64Node=e=>{let t=Buffer.from(e,`base64`);return createUint8ArrayViewFromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)},toBase64=isBrowser?toBase64Browser:toBase64Node,fromBase64=isBrowser?fromBase64Browser:fromBase64Node,copyUint8Array=e=>{let t=createUint8ArrayFromLen(e.byteLength);return t.set(e),t},encodeAny=e=>encode(t=>writeAny(t,e)),create$4=Symbol,BOLD=create$4(),UNBOLD=create$4(),BLUE=create$4(),GREY=create$4(),GREEN=create$4(),RED=create$4(),PURPLE=create$4(),ORANGE=create$4(),UNCOLOR=create$4(),computeNoColorLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],s=[],g=0;for(;g<e.length;g++){let s=e[g];if(s===void 0)break;if(s.constructor===String||s.constructor===Number)t.push(s);else if(s.constructor===Object)break}for(g>0&&s.push(t.join(``));g<e.length;g++){let t=e[g];t instanceof Symbol||s.push(t)}return s};let lastLoggingTime=getUnixTime$1();const _nodeStyleMap={[BOLD]:`\x1B[1m`,[UNBOLD]:`\x1B[2m`,[BLUE]:`\x1B[34m`,[GREEN]:`\x1B[32m`,[GREY]:`\x1B[37m`,[RED]:`\x1B[31m`,[PURPLE]:`\x1B[35m`,[ORANGE]:`\x1B[38;5;208m`,[UNCOLOR]:`\x1B[0m`},computeNodeLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],s=[],g=0;for(;g<e.length;g++){let s=e[g],S=_nodeStyleMap[s];if(S!==void 0)t.push(S);else if(s===void 0)break;else if(s.constructor===String||s.constructor===Number)t.push(s);else break}for(g>0&&(t.push(`\x1B[0m`),s.push(t.join(``)));g<e.length;g++){let t=e[g];t instanceof Symbol||s.push(t)}return s},computeLoggingArgs=supportsColor?computeNodeLoggingArgs:computeNoColorLoggingArgs,print=(...e)=>{console.log(...computeLoggingArgs(e))},warn=(...e)=>{console.warn(...computeLoggingArgs(e))},createIterator=e=>({[Symbol.iterator](){return this},next:e}),iteratorFilter=(e,t)=>createIterator(()=>{let s;do s=e.next();while(!s.done&&!t(s.value));return s}),iteratorMap=(e,t)=>createIterator(()=>{let{done:s,value:g}=e.next();return{done:s,value:s?void 0:t(g)}});var DeleteItem=class{constructor(e,t){this.clock=e,this.len=t}},DeleteSet=class{constructor(){this.clients=new Map}};const iterateDeletedStructs=(e,t,s)=>t.clients.forEach((t,g)=>{let S=e.doc.store.clients.get(g);if(S!=null){let g=S[S.length-1],w=g.id.clock+g.length;for(let g=0,E=t[g];g<t.length&&E.clock<w;E=t[++g])iterateStructs(e,S,E.clock,E.len,s)}}),findIndexDS=(e,t)=>{let s=0,g=e.length-1;for(;s<=g;){let S=floor$2((s+g)/2),w=e[S],E=w.clock;if(E<=t){if(t<E+w.len)return S;s=S+1}else g=S-1}return null},isDeleted=(e,t)=>{let s=e.clients.get(t.client);return s!==void 0&&findIndexDS(s,t.clock)!==null},sortAndMergeDeleteSet=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,s;for(t=1,s=1;t<e.length;t++){let g=e[s-1],S=e[t];g.clock+g.len>=S.clock?e[s-1]=new DeleteItem(g.clock,max$2(g.len,S.clock+S.len-g.clock)):(s<t&&(e[s]=S),s++)}e.length=s})},mergeDeleteSets=e=>{let t=new DeleteSet;for(let s=0;s<e.length;s++)e[s].clients.forEach((g,S)=>{if(!t.clients.has(S)){let w=g.slice();for(let t=s+1;t<e.length;t++)appendTo(w,e[t].clients.get(S)||[]);t.clients.set(S,w)}});return sortAndMergeDeleteSet(t),t},addToDeleteSet=(e,t,s,g)=>{setIfUndefined$1(e.clients,t,()=>[]).push(new DeleteItem(s,g))},createDeleteSet=()=>new DeleteSet,createDeleteSetFromStructStore=e=>{let t=createDeleteSet();return e.clients.forEach((e,s)=>{let g=[];for(let t=0;t<e.length;t++){let s=e[t];if(s.deleted){let S=s.id.clock,w=s.length;if(t+1<e.length)for(let s=e[t+1];t+1<e.length&&s.deleted;s=e[++t+1])w+=s.length;g.push(new DeleteItem(S,w))}}g.length>0&&t.clients.set(s,g)}),t},writeDeleteSet=(e,t)=>{writeVarUint$2(e.restEncoder,t.clients.size),from$1(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,s])=>{e.resetDsCurVal(),writeVarUint$2(e.restEncoder,t);let g=s.length;writeVarUint$2(e.restEncoder,g);for(let t=0;t<g;t++){let g=s[t];e.writeDsClock(g.clock),e.writeDsLen(g.len)}})},readDeleteSet=e=>{let t=new DeleteSet,s=readVarUint$1(e.restDecoder);for(let g=0;g<s;g++){e.resetDsCurVal();let s=readVarUint$1(e.restDecoder),g=readVarUint$1(e.restDecoder);if(g>0){let S=setIfUndefined$1(t.clients,s,()=>[]);for(let t=0;t<g;t++)S.push(new DeleteItem(e.readDsClock(),e.readDsLen()))}}return t},readAndApplyDeleteSet=(e,t,s)=>{let g=new DeleteSet,S=readVarUint$1(e.restDecoder);for(let w=0;w<S;w++){e.resetDsCurVal();let S=readVarUint$1(e.restDecoder),w=readVarUint$1(e.restDecoder),E=s.clients.get(S)||[],D=getState(s,S);for(let s=0;s<w;s++){let s=e.readDsClock(),w=s+e.readDsLen();if(s<D){D<w&&addToDeleteSet(g,S,D,w-D);let e=findIndexSS(E,s),O=E[e];for(!O.deleted&&O.id.clock<s&&(E.splice(e+1,0,splitItem(t,O,s-O.id.clock)),e++);e<E.length&&(O=E[e++],O.id.clock<w);)O.deleted||(w<O.id.clock+O.length&&E.splice(e,0,splitItem(t,O,w-O.id.clock)),O.delete(t))}else addToDeleteSet(g,S,s,w-s)}}if(g.clients.size>0){let e=new UpdateEncoderV2;return writeVarUint$2(e.restEncoder,0),writeDeleteSet(e,g),e.toUint8Array()}return null},equalDeleteSets=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[s,g]of e.clients.entries()){let e=t.clients.get(s);if(e===void 0||g.length!==e.length)return!1;for(let t=0;t<g.length;t++){let s=g[t],S=e[t];if(s.clock!==S.clock||s.len!==S.len)return!1}}return!0},generateNewClientId=uint32;var Doc=class e extends ObservableV2{constructor({guid:e=uuidv4(),collectionid:t=null,gc:s=!0,gcFilter:g=()=>!0,meta:S=null,autoLoad:w=!1,shouldLoad:E=!0}={}){super(),this.gc=s,this.gcFilter=g,this.clientID=generateNewClientId(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new StructStore,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=E,this.autoLoad=w,this.meta=S,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=create$5(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let D=()=>create$5(e=>{let t=s=>{(s===void 0||s===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=D()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=D()}load(){let e=this._item;e!==null&&!this.shouldLoad&&transact(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(from$1(this.subdocs).map(e=>e.guid))}transact(e,t=null){return transact(this,e,t)}get(e,t=AbstractType){let s=setIfUndefined$1(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),g=s.constructor;if(t!==AbstractType&&g!==t)if(g===AbstractType){let g=new t;g._map=s._map,s._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=g}),g._start=s._start;for(let e=g._start;e!==null;e=e.right)e.parent=g;return g._length=s._length,this.share.set(e,g),g._integrate(this,null),g}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=``){return this.get(e,YArray)}getText(e=``){return this.get(e,YText)}getMap(e=``){return this.get(e,YMap)}getXmlElement(e=``){return this.get(e,YXmlElement)}getXmlFragment(e=``){return this.get(e,YXmlFragment)}toJSON(){let e={};return this.share.forEach((t,s)=>{e[s]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,from$1(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let s=t.content;s.doc=new e({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=t,transact(t.parent.doc,e=>{let g=s.doc;t.deleted||e.subdocsAdded.add(g),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},DSDecoderV1=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return readVarUint$1(this.restDecoder)}readDsLen(){return readVarUint$1(this.restDecoder)}},UpdateDecoderV1=class extends DSDecoderV1{readLeftID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readRightID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readClient(){return readVarUint$1(this.restDecoder)}readInfo(){return readUint8$1(this.restDecoder)}readString(){return readVarString$1(this.restDecoder)}readParentInfo(){return readVarUint$1(this.restDecoder)===1}readTypeRef(){return readVarUint$1(this.restDecoder)}readLen(){return readVarUint$1(this.restDecoder)}readAny(){return readAny(this.restDecoder)}readBuf(){return copyUint8Array(readVarUint8Array$1(this.restDecoder))}readJSON(){return JSON.parse(readVarString$1(this.restDecoder))}readKey(){return readVarString$1(this.restDecoder)}},DSDecoderV2=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=readVarUint$1(this.restDecoder),this.dsCurrVal}readDsLen(){let e=readVarUint$1(this.restDecoder)+1;return this.dsCurrVal+=e,e}},UpdateDecoderV2=class extends DSDecoderV2{constructor(e){super(e),this.keys=[],readVarUint$1(e),this.keyClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.clientDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.leftClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.rightClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.infoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.stringDecoder=new StringDecoder(readVarUint8Array$1(e)),this.parentInfoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.typeRefDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.lenDecoder=new UintOptRleDecoder(readVarUint8Array$1(e))}readLeftID(){return new ID(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ID(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return readAny(this.restDecoder)}readBuf(){return readVarUint8Array$1(this.restDecoder)}readJSON(){return readAny(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},DSEncoderV1=class{constructor(){this.restEncoder=createEncoder$1()}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){writeVarUint$2(this.restEncoder,e)}writeDsLen(e){writeVarUint$2(this.restEncoder,e)}},UpdateEncoderV1=class extends DSEncoderV1{writeLeftID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeRightID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeClient(e){writeVarUint$2(this.restEncoder,e)}writeInfo(e){writeUint8(this.restEncoder,e)}writeString(e){writeVarString$2(this.restEncoder,e)}writeParentInfo(e){writeVarUint$2(this.restEncoder,e?1:0)}writeTypeRef(e){writeVarUint$2(this.restEncoder,e)}writeLen(e){writeVarUint$2(this.restEncoder,e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeVarString$2(this.restEncoder,JSON.stringify(e))}writeKey(e){writeVarString$2(this.restEncoder,e)}},DSEncoderV2=class{constructor(){this.restEncoder=createEncoder$1(),this.dsCurrVal=0}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,writeVarUint$2(this.restEncoder,t)}writeDsLen(e){e===0&&unexpectedCase(),writeVarUint$2(this.restEncoder,e-1),this.dsCurrVal+=e}},UpdateEncoderV2=class extends DSEncoderV2{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new IntDiffOptRleEncoder,this.clientEncoder=new UintOptRleEncoder,this.leftClockEncoder=new IntDiffOptRleEncoder,this.rightClockEncoder=new IntDiffOptRleEncoder,this.infoEncoder=new RleEncoder(writeUint8),this.stringEncoder=new StringEncoder,this.parentInfoEncoder=new RleEncoder(writeUint8),this.typeRefEncoder=new UintOptRleEncoder,this.lenEncoder=new UintOptRleEncoder}toUint8Array(){let e=createEncoder$1();return writeVarUint$2(e,0),writeVarUint8Array$2(e,this.keyClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.clientEncoder.toUint8Array()),writeVarUint8Array$2(e,this.leftClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.rightClockEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.infoEncoder)),writeVarUint8Array$2(e,this.stringEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.parentInfoEncoder)),writeVarUint8Array$2(e,this.typeRefEncoder.toUint8Array()),writeVarUint8Array$2(e,this.lenEncoder.toUint8Array()),writeUint8Array$2(e,toUint8Array$1(this.restEncoder)),toUint8Array$1(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeAny(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const writeStructs=(e,t,s,g)=>{g=max$2(g,t[0].id.clock);let S=findIndexSS(t,g);writeVarUint$2(e.restEncoder,t.length-S),e.writeClient(s),writeVarUint$2(e.restEncoder,g);let w=t[S];w.write(e,g-w.id.clock);for(let s=S+1;s<t.length;s++)t[s].write(e,0)},writeClientsStructs=(e,t,s)=>{let g=new Map;s.forEach((e,s)=>{getState(t,s)>e&&g.set(s,e)}),getStateVector(t).forEach((e,t)=>{s.has(t)||g.set(t,0)}),writeVarUint$2(e.restEncoder,g.size),from$1(g.entries()).sort((e,t)=>t[0]-e[0]).forEach(([s,g])=>{writeStructs(e,t.clients.get(s),s,g)})},readClientsStructRefs=(e,t)=>{let s=create$8(),g=readVarUint$1(e.restDecoder);for(let S=0;S<g;S++){let g=readVarUint$1(e.restDecoder),S=Array(g),w=e.readClient(),E=readVarUint$1(e.restDecoder);s.set(w,{i:0,refs:S});for(let s=0;s<g;s++){let g=e.readInfo();switch(31&g){case 0:{let t=e.readLen();S[s]=new GC(createID(w,E),t),E+=t;break}case 10:{let t=readVarUint$1(e.restDecoder);S[s]=new Skip(createID(w,E),t),E+=t;break}default:{let D=(g&192)==0,O=new Item(createID(w,E),null,(g&128)==128?e.readLeftID():null,null,(g&64)==64?e.readRightID():null,D?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,D&&(g&32)==32?e.readString():null,readItemContent(e,g));S[s]=O,E+=O.length}}}}return s},integrateStructs=(e,t,s)=>{let g=[],S=from$1(s.keys()).sort((e,t)=>e-t);if(S.length===0)return null;let w=()=>{if(S.length===0)return null;let e=s.get(S[S.length-1]);for(;e.refs.length===e.i;)if(S.pop(),S.length>0)e=s.get(S[S.length-1]);else return null;return e},E=w();if(E===null)return null;let D=new StructStore,O=new Map,k=(e,t)=>{let s=O.get(e);(s==null||s>t)&&O.set(e,t)},j=E.refs[E.i++],F=new Map,L=()=>{for(let e of g){let t=e.id.client,g=s.get(t);g?(g.i--,D.clients.set(t,g.refs.slice(g.i)),s.delete(t),g.i=0,g.refs=[]):D.clients.set(t,[e]),S=S.filter(e=>e!==t)}g.length=0};for(;;){if(j.constructor!==Skip){let S=setIfUndefined$1(F,j.id.client,()=>getState(t,j.id.client))-j.id.clock;if(S<0)g.push(j),k(j.id.client,j.id.clock-1),L();else{let w=j.getMissing(e,t);if(w!==null){g.push(j);let e=s.get(w)||{refs:[],i:0};if(e.refs.length===e.i)k(w,getState(t,w)),L();else{j=e.refs[e.i++];continue}}else (S===0||S<j.length)&&(j.integrate(e,S),F.set(j.id.client,j.id.clock+j.length))}}if(g.length>0)j=g.pop();else if(E!==null&&E.i<E.refs.length)j=E.refs[E.i++];else{if(E=w(),E===null)break;j=E.refs[E.i++]}}if(D.clients.size>0){let e=new UpdateEncoderV2;return writeClientsStructs(e,D,new Map),writeVarUint$2(e.restEncoder,0),{missing:O,update:e.toUint8Array()}}return null},writeStructsFromTransaction=(e,t)=>writeClientsStructs(e,t.doc.store,t.beforeState),readUpdateV2=(e,t,s,g=new UpdateDecoderV2(e))=>transact(t,e=>{e.local=!1;let t=!1,s=e.doc,S=s.store,w=integrateStructs(e,S,readClientsStructRefs(g,s)),E=S.pendingStructs;if(E){for(let[e,s]of E.missing)if(s<getState(S,e)){t=!0;break}if(w){for(let[e,t]of w.missing){let s=E.missing.get(e);(s==null||s>t)&&E.missing.set(e,t)}E.update=mergeUpdatesV2([E.update,w.update])}}else S.pendingStructs=w;let D=readAndApplyDeleteSet(g,e,S);if(S.pendingDs){let t=new UpdateDecoderV2(createDecoder$1(S.pendingDs));readVarUint$1(t.restDecoder);let s=readAndApplyDeleteSet(t,e,S);D&&s?S.pendingDs=mergeUpdatesV2([D,s]):S.pendingDs=D||s}else S.pendingDs=D;if(t){let t=S.pendingStructs.update;S.pendingStructs=null,applyUpdateV2(e.doc,t)}},s,!1),applyUpdateV2=(e,t,s,g=UpdateDecoderV2)=>{let S=createDecoder$1(t);readUpdateV2(S,e,s,new g(S))},applyUpdate=(e,t,s)=>applyUpdateV2(e,t,s,UpdateDecoderV1),writeStateAsUpdate=(e,t,s=new Map)=>{writeClientsStructs(e,t.store,s),writeDeleteSet(e,createDeleteSetFromStructStore(t.store))},encodeStateAsUpdateV2=(e,t=new Uint8Array([0]),s=new UpdateEncoderV2)=>{writeStateAsUpdate(s,e,decodeStateVector(t));let g=[s.toUint8Array()];if(e.store.pendingDs&&g.push(e.store.pendingDs),e.store.pendingStructs&&g.push(diffUpdateV2(e.store.pendingStructs.update,t)),g.length>1){if(s.constructor===UpdateEncoderV1)return mergeUpdates(g.map((e,t)=>t===0?e:convertUpdateFormatV2ToV1(e)));if(s.constructor===UpdateEncoderV2)return mergeUpdatesV2(g)}return g[0]},encodeStateAsUpdate=(e,t)=>encodeStateAsUpdateV2(e,t,new UpdateEncoderV1),readStateVector=e=>{let t=new Map,s=readVarUint$1(e.restDecoder);for(let g=0;g<s;g++){let s=readVarUint$1(e.restDecoder),g=readVarUint$1(e.restDecoder);t.set(s,g)}return t},decodeStateVector=e=>readStateVector(new DSDecoderV1(createDecoder$1(e))),writeStateVector=(e,t)=>(writeVarUint$2(e.restEncoder,t.size),from$1(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,s])=>{writeVarUint$2(e.restEncoder,t),writeVarUint$2(e.restEncoder,s)}),e),writeDocumentStateVector=(e,t)=>writeStateVector(e,getStateVector(t.store)),encodeStateVectorV2=(e,t=new DSEncoderV2)=>(e instanceof Map?writeStateVector(t,e):writeDocumentStateVector(t,e),t.toUint8Array()),encodeStateVector=e=>encodeStateVectorV2(e,new DSEncoderV1);var EventHandler=class{constructor(){this.l=[]}};const createEventHandler=()=>new EventHandler,addEventHandlerListener=(e,t)=>e.l.push(t),removeEventHandlerListener=(e,t)=>{let s=e.l,g=s.length;e.l=s.filter(e=>t!==e),g===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},callEventHandlerListeners=(e,t,s)=>callAll(e.l,[t,s]);var ID=class{constructor(e,t){this.client=e,this.clock=t}};const compareIDs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,createID=(e,t)=>new ID(e,t),findRootTypeKey=e=>{for(let[t,s]of e.doc.share.entries())if(s===e)return t;throw unexpectedCase()},isParentOf=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Snapshot=class{constructor(e,t){this.ds=e,this.sv=t}};const createSnapshot=(e,t)=>new Snapshot(e,t),emptySnapshot=createSnapshot(createDeleteSet(),new Map),snapshot=e=>createSnapshot(createDeleteSetFromStructStore(e.store),getStateVector(e.store)),isVisible$1=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!isDeleted(t.ds,e.id),splitSnapshotAffectedStructs=(e,t)=>{let s=setIfUndefined$1(e.meta,splitSnapshotAffectedStructs,create$7),g=e.doc.store;s.has(t)||(t.sv.forEach((t,s)=>{t<getState(g,s)&&getItemCleanStart(e,createID(s,t))}),iterateDeletedStructs(e,t.ds,e=>{}),s.add(t))},snapshotContainsUpdateV2=(e,t,s=UpdateDecoderV2)=>{let g=new s(createDecoder$1(t)),S=new LazyStructReader(g,!1);for(let t=S.curr;t!==null;t=S.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let w=mergeDeleteSets([e.ds,readDeleteSet(g)]);return equalDeleteSets(e.ds,w)},snapshotContainsUpdate=(e,t)=>snapshotContainsUpdateV2(e,t,UpdateDecoderV1);var StructStore=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const getStateVector=e=>{let t=new Map;return e.clients.forEach((e,s)=>{let g=e[e.length-1];t.set(s,g.id.clock+g.length)}),t},getState=(e,t)=>{let s=e.clients.get(t);if(s===void 0)return 0;let g=s[s.length-1];return g.id.clock+g.length},addStruct=(e,t)=>{let s=e.clients.get(t.id.client);if(s===void 0)s=[],e.clients.set(t.id.client,s);else{let e=s[s.length-1];if(e.id.clock+e.length!==t.id.clock)throw unexpectedCase()}s.push(t)},findIndexSS=(e,t)=>{let s=0,g=e.length-1,S=e[g],w=S.id.clock;if(w===t)return g;let E=floor$2(t/(w+S.length-1)*g);for(;s<=g;){if(S=e[E],w=S.id.clock,w<=t){if(t<w+S.length)return E;s=E+1}else g=E-1;E=floor$2((s+g)/2)}throw unexpectedCase()},find=(e,t)=>{let s=e.clients.get(t.client);return s[findIndexSS(s,t.clock)]},getItem=find,findIndexCleanStart=(e,t,s)=>{let g=findIndexSS(t,s),S=t[g];return S.id.clock<s&&S instanceof Item?(t.splice(g+1,0,splitItem(e,S,s-S.id.clock)),g+1):g},getItemCleanStart=(e,t)=>{let s=e.doc.store.clients.get(t.client);return s[findIndexCleanStart(e,s,t.clock)]},getItemCleanEnd=(e,t,s)=>{let g=t.clients.get(s.client),S=findIndexSS(g,s.clock),w=g[S];return s.clock!==w.id.clock+w.length-1&&w.constructor!==GC&&g.splice(S+1,0,splitItem(e,w,s.clock-w.id.clock+1)),w},replaceStruct=(e,t,s)=>{let g=e.clients.get(t.id.client);g[findIndexSS(g,t.id.clock)]=s},iterateStructs=(e,t,s,g,S)=>{if(g===0)return;let w=s+g,E=findIndexCleanStart(e,t,s),D;do D=t[E++],w<D.id.clock+D.length&&findIndexCleanStart(e,t,w),S(D);while(E<t.length&&t[E].id.clock<w)};var Transaction=class{constructor(e,t,s){this.doc=e,this.deleteSet=new DeleteSet,this.beforeState=getStateVector(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const writeUpdateMessageFromTransaction=(e,t)=>t.deleteSet.clients.size===0&&!any(t.afterState,(e,s)=>t.beforeState.get(s)!==e)?!1:(sortAndMergeDeleteSet(t.deleteSet),writeStructsFromTransaction(e,t),writeDeleteSet(e,t.deleteSet),!0),addChangedTypeToTransaction=(e,t,s)=>{let g=t._item;(g===null||g.id.clock<(e.beforeState.get(g.id.client)||0)&&!g.deleted)&&setIfUndefined$1(e.changed,t,create$7).add(s)},tryToMergeWithLefts=(e,t)=>{let s=e[t],g=e[t-1],S=t;for(;S>0;s=g,g=e[--S-1]){if(g.deleted===s.deleted&&g.constructor===s.constructor&&g.mergeWith(s)){s instanceof Item&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,g);continue}break}let w=t-S;return w&&e.splice(t+1-w,w),w},tryGcDeleteSet=(e,t,s)=>{for(let[g,S]of e.clients.entries()){let e=t.clients.get(g);for(let g=S.length-1;g>=0;g--){let w=S[g],E=w.clock+w.len;for(let g=findIndexSS(e,w.clock),S=e[g];g<e.length&&S.id.clock<E;S=e[++g]){let S=e[g];if(w.clock+w.len<=S.id.clock)break;S instanceof Item&&S.deleted&&!S.keep&&s(S)&&S.gc(t,!1)}}}},tryMergeDeleteSet=(e,t)=>{e.clients.forEach((e,s)=>{let g=t.clients.get(s);for(let t=e.length-1;t>=0;t--){let s=e[t],S=min$2(g.length-1,1+findIndexSS(g,s.clock+s.len-1));for(let e=S,t=g[e];e>0&&t.id.clock>=s.clock;t=g[e])e-=1+tryToMergeWithLefts(g,e)}})},cleanupTransactions=(e,t)=>{if(t<e.length){let s=e[t],g=s.doc,S=g.store,w=s.deleteSet,E=s._mergeStructs;try{sortAndMergeDeleteSet(w),s.afterState=getStateVector(s.doc.store),g.emit(`beforeObserverCalls`,[s,g]);let e=[];s.changed.forEach((t,g)=>e.push(()=>{(g._item===null||!g._item.deleted)&&g._callObserver(s,t)})),e.push(()=>{s.changedParentTypes.forEach((t,g)=>{g._dEH.l.length>0&&(g._item===null||!g._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=g,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{callEventHandlerListeners(g._dEH,t,s)}))}),e.push(()=>g.emit(`afterTransaction`,[s,g])),e.push(()=>{s._needFormattingCleanup&&cleanupYTextAfterTransaction(s)})}),callAll(e,[])}finally{g.gc&&tryGcDeleteSet(w,S,g.gcFilter),tryMergeDeleteSet(w,S),s.afterState.forEach((e,t)=>{let g=s.beforeState.get(t)||0;if(g!==e){let e=S.clients.get(t),s=max$2(findIndexSS(e,g),1);for(let t=e.length-1;t>=s;)t-=1+tryToMergeWithLefts(e,t)}});for(let e=E.length-1;e>=0;e--){let{client:t,clock:s}=E[e].id,g=S.clients.get(t),w=findIndexSS(g,s);w+1<g.length&&tryToMergeWithLefts(g,w+1)>1||w>0&&tryToMergeWithLefts(g,w)}if(!s.local&&s.afterState.get(g.clientID)!==s.beforeState.get(g.clientID)&&(print(ORANGE,BOLD,`[yjs] `,UNBOLD,RED,`Changed the client-id because another client seems to be using it.`),g.clientID=generateNewClientId()),g.emit(`afterTransactionCleanup`,[s,g]),g._observers.has(`update`)){let e=new UpdateEncoderV1;writeUpdateMessageFromTransaction(e,s)&&g.emit(`update`,[e.toUint8Array(),s.origin,g,s])}if(g._observers.has(`updateV2`)){let e=new UpdateEncoderV2;writeUpdateMessageFromTransaction(e,s)&&g.emit(`updateV2`,[e.toUint8Array(),s.origin,g,s])}let{subdocsAdded:D,subdocsLoaded:O,subdocsRemoved:k}=s;(D.size>0||k.size>0||O.size>0)&&(D.forEach(e=>{e.clientID=g.clientID,e.collectionid??=g.collectionid,g.subdocs.add(e)}),k.forEach(e=>g.subdocs.delete(e)),g.emit(`subdocs`,[{loaded:O,added:D,removed:k},g,s]),k.forEach(e=>e.destroy())),e.length<=t+1?(g._transactionCleanups=[],g.emit(`afterAllTransactions`,[g,e])):cleanupTransactions(e,t+1)}}},transact=(e,t,s=null,g=!0)=>{let S=e._transactionCleanups,w=!1,E=null;e._transaction===null&&(w=!0,e._transaction=new Transaction(e,s,g),S.push(e._transaction),S.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{E=t(e._transaction)}finally{if(w){let t=e._transaction===S[0];e._transaction=null,t&&cleanupTransactions(S,0)}}return E};var StackItem=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const clearUndoManagerStackItem=(e,t,s)=>{iterateDeletedStructs(e,s.deletions,s=>{s instanceof Item&&t.scope.some(t=>t===e.doc||isParentOf(t,s))&&keepItem(s,!1)})},popStackItem=(e,t,s)=>{let g=null,S=e.doc,w=e.scope;transact(S,s=>{for(;t.length>0&&e.currStackItem===null;){let g=S.store,E=t.pop(),D=new Set,O=[],k=!1;iterateDeletedStructs(s,E.insertions,e=>{if(e instanceof Item){if(e.redone!==null){let{item:t,diff:S}=followRedone(g,e.id);S>0&&(t=getItemCleanStart(s,createID(t.id.client,t.id.clock+S))),e=t}!e.deleted&&w.some(t=>t===s.doc||isParentOf(t,e))&&O.push(e)}}),iterateDeletedStructs(s,E.deletions,e=>{e instanceof Item&&w.some(t=>t===s.doc||isParentOf(t,e))&&!isDeleted(E.insertions,e.id)&&D.add(e)}),D.forEach(t=>{k=redoItem(s,t,D,E.insertions,e.ignoreRemoteMapChanges,e)!==null||k});for(let t=O.length-1;t>=0;t--){let g=O[t];e.deleteFilter(g)&&(g.delete(s),k=!0)}e.currStackItem=k?E:null}s.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),g=s},e);let E=e.currStackItem;if(E!=null){let t=g.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:E,type:s,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return E};var UndoManager=class extends ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:s=e=>!0,deleteFilter:g=()=>!0,trackedOrigins:S=new Set([null]),ignoreRemoteMapChanges:w=!1,doc:E=isArray$1(e)?e[0].doc:e instanceof Doc?e:e.doc}={}){super(),this.scope=[],this.doc=E,this.addToScope(e),this.deleteFilter=g,S.add(this),this.trackedOrigins=S,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=w,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,s=this.redoing,g=t?this.redoStack:this.undoStack;t?this.stopCapturing():s||this.clear(!1,!0);let S=new DeleteSet;e.afterState.forEach((t,s)=>{let g=e.beforeState.get(s)||0,w=t-g;w>0&&addToDeleteSet(S,s,g,w)});let w=getUnixTime$1(),E=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&g.length>0&&!t&&!s){let t=g[g.length-1];t.deletions=mergeDeleteSets([t.deletions,e.deleteSet]),t.insertions=mergeDeleteSets([t.insertions,S])}else g.push(new StackItem(e.deleteSet,S)),E=!0;!t&&!s&&(this.lastChange=w),iterateDeletedStructs(e,e.deleteSet,t=>{t instanceof Item&&this.scope.some(s=>s===e.doc||isParentOf(s,t))&&keepItem(t,!0)});let D=[{stackItem:g[g.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];E?this.emit(`stack-item-added`,D):this.emit(`stack-item-updated`,D)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=isArray$1(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof AbstractType?e.doc!==this.doc:e!==this.doc)&&warn(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(e=>clearUndoManagerStackItem(s,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>clearUndoManagerStackItem(s,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=popStackItem(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=popStackItem(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*lazyStructReaderGenerator(e){let t=readVarUint$1(e.restDecoder);for(let s=0;s<t;s++){let t=readVarUint$1(e.restDecoder),s=e.readClient(),g=readVarUint$1(e.restDecoder);for(let S=0;S<t;S++){let t=e.readInfo();if(t===10){let t=readVarUint$1(e.restDecoder);yield new Skip(createID(s,g),t),g+=t}else if(31&t){let S=(t&192)==0,w=new Item(createID(s,g),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,S?e.readParentInfo()?e.readString():e.readLeftID():null,S&&(t&32)==32?e.readString():null,readItemContent(e,t));yield w,g+=w.length}else{let t=e.readLen();yield new GC(createID(s,g),t),g+=t}}}}var LazyStructReader=class{constructor(e,t){this.gen=lazyStructReaderGenerator(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Skip);return this.curr}},LazyStructWriter=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const mergeUpdates=e=>mergeUpdatesV2(e,UpdateDecoderV1,UpdateEncoderV1),sliceStruct=(e,t)=>{if(e.constructor===GC){let{client:s,clock:g}=e.id;return new GC(createID(s,g+t),e.length-t)}else if(e.constructor===Skip){let{client:s,clock:g}=e.id;return new Skip(createID(s,g+t),e.length-t)}else{let s=e,{client:g,clock:S}=s.id;return new Item(createID(g,S+t),null,createID(g,S+t-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(t))}},mergeUpdatesV2=(e,t=UpdateDecoderV2,s=UpdateEncoderV2)=>{if(e.length===1)return e[0];let g=e.map(e=>new t(createDecoder$1(e))),S=g.map(e=>new LazyStructReader(e,!0)),w=null,E=new s,D=new LazyStructWriter(E);for(;S=S.filter(e=>e.curr!==null),S.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let s=e.curr.id.clock-t.curr.id.clock;return s===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Skip?1:-1:s}else return t.curr.id.client-e.curr.id.client}),S.length!==0;){let e=S[0],t=e.curr.id.client;if(w!==null){let s=e.curr,g=!1;for(;s!==null&&s.id.clock+s.length<=w.struct.id.clock+w.struct.length&&s.id.client>=w.struct.id.client;)s=e.next(),g=!0;if(s===null||s.id.client!==t||g&&s.id.clock>w.struct.id.clock+w.struct.length)continue;if(t!==w.struct.id.client)writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0},e.next();else if(w.struct.id.clock+w.struct.length<s.id.clock)if(w.struct.constructor===Skip)w.struct.length=s.id.clock+s.length-w.struct.id.clock;else{writeStructToLazyStructWriter(D,w.struct,w.offset);let e=s.id.clock-w.struct.id.clock-w.struct.length;w={struct:new Skip(createID(t,w.struct.id.clock+w.struct.length),e),offset:0}}else{let t=w.struct.id.clock+w.struct.length-s.id.clock;t>0&&(w.struct.constructor===Skip?w.struct.length-=t:s=sliceStruct(s,t)),w.struct.mergeWith(s)||(writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0},e.next())}}else w={struct:e.curr,offset:0},e.next();for(let s=e.curr;s!==null&&s.id.client===t&&s.id.clock===w.struct.id.clock+w.struct.length&&s.constructor!==Skip;s=e.next())writeStructToLazyStructWriter(D,w.struct,w.offset),w={struct:s,offset:0}}return w!==null&&(writeStructToLazyStructWriter(D,w.struct,w.offset),w=null),finishLazyStructWriting(D),writeDeleteSet(E,mergeDeleteSets(g.map(e=>readDeleteSet(e)))),E.toUint8Array()},diffUpdateV2=(e,t,s=UpdateDecoderV2,g=UpdateEncoderV2)=>{let S=decodeStateVector(t),w=new g,E=new LazyStructWriter(w),D=new s(createDecoder$1(e)),O=new LazyStructReader(D,!1);for(;O.curr;){let e=O.curr,t=e.id.client,s=S.get(t)||0;if(O.curr.constructor===Skip){O.next();continue}if(e.id.clock+e.length>s)for(writeStructToLazyStructWriter(E,e,max$2(s-e.id.clock,0)),O.next();O.curr&&O.curr.id.client===t;)writeStructToLazyStructWriter(E,O.curr,0),O.next();else for(;O.curr&&O.curr.id.client===t&&O.curr.id.clock+O.curr.length<=s;)O.next()}return finishLazyStructWriting(E),writeDeleteSet(w,readDeleteSet(D)),w.toUint8Array()},flushLazyStructWriter=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:toUint8Array$1(e.encoder.restEncoder)}),e.encoder.restEncoder=createEncoder$1(),e.written=0)},writeStructToLazyStructWriter=(e,t,s)=>{e.written>0&&e.currClient!==t.id.client&&flushLazyStructWriter(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),writeVarUint$2(e.encoder.restEncoder,t.id.clock+s)),t.write(e.encoder,s),e.written++},finishLazyStructWriting=e=>{flushLazyStructWriter(e);let t=e.encoder.restEncoder;writeVarUint$2(t,e.clientStructs.length);for(let s=0;s<e.clientStructs.length;s++){let g=e.clientStructs[s];writeVarUint$2(t,g.written),writeUint8Array$2(t,g.restEncoder)}},convertUpdateFormat=(e,t,s,g)=>{let S=new s(createDecoder$1(e)),w=new LazyStructReader(S,!1),E=new g,D=new LazyStructWriter(E);for(let e=w.curr;e!==null;e=w.next())writeStructToLazyStructWriter(D,t(e),0);return finishLazyStructWriting(D),writeDeleteSet(E,readDeleteSet(S)),E.toUint8Array()},convertUpdateFormatV2ToV1=e=>convertUpdateFormat(e,id,UpdateDecoderV2,UpdateEncoderV1),errorComputeChanges=`You must not compute changes after the event-handler fired.`;var YEvent=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=getPathTo(this.currentTarget,this.target)}deletes(e){return isDeleted(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){let g=t._map.get(s),S,w;if(this.adds(g)){let e=g.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(g))if(e!==null&&this.deletes(e))S=`delete`,w=last(e.content.getContent());else return;else e!==null&&this.deletes(e)?(S=`update`,w=last(e.content.getContent())):(S=`add`,w=void 0)}else if(this.deletes(g))S=`delete`,w=last(g.content.getContent());else return;e.set(s,{action:S,oldValue:w})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let t=this.target,s=create$7(),g=create$7(),S=[];if(e={added:s,deleted:g,delta:S,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,w=()=>{e&&S.push(e)};for(let S=t._start;S!==null;S=S.right)S.deleted?this.deletes(S)&&!this.adds(S)&&((e===null||e.delete===void 0)&&(w(),e={delete:0}),e.delete+=S.length,g.add(S)):this.adds(S)?((e===null||e.insert===void 0)&&(w(),e={insert:[]}),e.insert=e.insert.concat(S.content.getContent()),s.add(S)):((e===null||e.retain===void 0)&&(w(),e={retain:0}),e.retain+=S.length);e!==null&&e.retain===void 0&&w()}this._changes=e}return e}};const getPathTo=(e,t)=>{let s=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)s.unshift(t._item.parentSub);else{let e=0,g=t._item.parent._start;for(;g!==t._item&&g!==null;)!g.deleted&&g.countable&&(e+=g.length),g=g.right;s.unshift(e)}t=t._item.parent}return s},warnPrematureAccess=()=>{warn(`Invalid access: Add Yjs type to a document before reading data.`)},maxSearchMarker=80;let globalSearchMarkerTimestamp=0;var ArraySearchMarker=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=globalSearchMarkerTimestamp++}};const refreshMarkerTimestamp=e=>{e.timestamp=globalSearchMarkerTimestamp++},overwriteMarker=(e,t,s)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=s,e.timestamp=globalSearchMarkerTimestamp++},markPosition=(e,t,s)=>{if(e.length>=maxSearchMarker){let g=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return overwriteMarker(g,t,s),g}else{let g=new ArraySearchMarker(t,s);return e.push(g),g}},findMarker=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let s=e._searchMarker.length===0?null:e._searchMarker.reduce((e,s)=>abs(t-e.index)<abs(t-s.index)?e:s),g=e._start,S=0;for(s!==null&&(g=s.p,S=s.index,refreshMarkerTimestamp(s));g.right!==null&&S<t;){if(!g.deleted&&g.countable){if(t<S+g.length)break;S+=g.length}g=g.right}for(;g.left!==null&&S>t;)g=g.left,!g.deleted&&g.countable&&(S-=g.length);for(;g.left!==null&&g.left.id.client===g.id.client&&g.left.id.clock+g.left.length===g.id.clock;)g=g.left,!g.deleted&&g.countable&&(S-=g.length);return s!==null&&abs(s.index-S)<g.parent.length/maxSearchMarker?(overwriteMarker(s,g,S),s):markPosition(e._searchMarker,g,S)},updateMarkerChanges=(e,t,s)=>{for(let g=e.length-1;g>=0;g--){let S=e[g];if(s>0){let t=S.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(S.index-=t.length);if(t===null||t.marker===!0){e.splice(g,1);continue}S.p=t,t.marker=!0}(t<S.index||s>0&&t===S.index)&&(S.index=max$2(t,S.index+s))}},callTypeObservers=(e,t,s)=>{let g=e,S=t.changedParentTypes;for(;setIfUndefined$1(S,e,()=>[]).push(s),e._item!==null;)e=e._item.parent;callEventHandlerListeners(g._eH,s,t)};var AbstractType=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=createEventHandler(),this._dEH=createEventHandler(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw methodUnimplemented()}clone(){throw methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){addEventHandlerListener(this._eH,e)}observeDeep(e){addEventHandlerListener(this._dEH,e)}unobserve(e){removeEventHandlerListener(this._eH,e)}unobserveDeep(e){removeEventHandlerListener(this._dEH,e)}toJSON(){}};const typeListSlice=(e,t,s)=>{e.doc??warnPrematureAccess(),t<0&&(t=e._length+t),s<0&&(s=e._length+s);let g=s-t,S=[],w=e._start;for(;w!==null&&g>0;){if(w.countable&&!w.deleted){let e=w.content.getContent();if(e.length<=t)t-=e.length;else{for(let s=t;s<e.length&&g>0;s++)S.push(e[s]),g--;t=0}}w=w.right}return S},typeListToArray=e=>{e.doc??warnPrematureAccess();let t=[],s=e._start;for(;s!==null;){if(s.countable&&!s.deleted){let e=s.content.getContent();for(let s=0;s<e.length;s++)t.push(e[s])}s=s.right}return t},typeListToArraySnapshot=(e,t)=>{let s=[],g=e._start;for(;g!==null;){if(g.countable&&isVisible$1(g,t)){let e=g.content.getContent();for(let t=0;t<e.length;t++)s.push(e[t])}g=g.right}return s},typeListForEach=(e,t)=>{let s=0,g=e._start;for(e.doc??warnPrematureAccess();g!==null;){if(g.countable&&!g.deleted){let S=g.content.getContent();for(let g=0;g<S.length;g++)t(S[g],s++,e)}g=g.right}},typeListMap=(e,t)=>{let s=[];return typeListForEach(e,(g,S)=>{s.push(t(g,S,e))}),s},typeListCreateIterator=e=>{let t=e._start,s=null,g=0;return{[Symbol.iterator](){return this},next:()=>{if(s===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};s=t.content.getContent(),g=0,t=t.right}let e=s[g++];return s.length<=g&&(s=null),{done:!1,value:e}}}},typeListGet=(e,t)=>{e.doc??warnPrematureAccess();let s=findMarker(e,t),g=e._start;for(s!==null&&(g=s.p,t-=s.index);g!==null;g=g.right)if(!g.deleted&&g.countable){if(t<g.length)return g.content.getContent()[t];t-=g.length}},typeListInsertGenericsAfter=(e,t,s,g)=>{let S=s,w=e.doc,E=w.clientID,D=w.store,O=s===null?t._start:s.right,k=[],j=()=>{k.length>0&&(S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentAny(k)),S.integrate(e,0),k=[])};g.forEach(s=>{if(s===null)k.push(s);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:k.push(s);break;default:switch(j(),s.constructor){case Uint8Array:case ArrayBuffer:S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentBinary(new Uint8Array(s))),S.integrate(e,0);break;case Doc:S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentDoc(s)),S.integrate(e,0);break;default:if(s instanceof AbstractType)S=new Item(createID(E,getState(D,E)),S,S&&S.lastId,O,O&&O.id,t,null,new ContentType(s)),S.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),j()},lengthExceeded=()=>create$6(`Length exceeded!`),typeListInsertGenerics=(e,t,s,g)=>{if(s>t._length)throw lengthExceeded();if(s===0)return t._searchMarker&&updateMarkerChanges(t._searchMarker,s,g.length),typeListInsertGenericsAfter(e,t,null,g);let S=s,w=findMarker(t,s),E=t._start;for(w!==null&&(E=w.p,s-=w.index,s===0&&(E=E.prev,s+=E&&E.countable&&!E.deleted?E.length:0));E!==null;E=E.right)if(!E.deleted&&E.countable){if(s<=E.length){s<E.length&&getItemCleanStart(e,createID(E.id.client,E.id.clock+s));break}s-=E.length}return t._searchMarker&&updateMarkerChanges(t._searchMarker,S,g.length),typeListInsertGenericsAfter(e,t,E,g)},typeListPushGenerics=(e,t,s)=>{let g=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(g)for(;g.right;)g=g.right;return typeListInsertGenericsAfter(e,t,g,s)},typeListDelete=(e,t,s,g)=>{if(g===0)return;let S=s,w=g,E=findMarker(t,s),D=t._start;for(E!==null&&(D=E.p,s-=E.index);D!==null&&s>0;D=D.right)!D.deleted&&D.countable&&(s<D.length&&getItemCleanStart(e,createID(D.id.client,D.id.clock+s)),s-=D.length);for(;g>0&&D!==null;)D.deleted||(g<D.length&&getItemCleanStart(e,createID(D.id.client,D.id.clock+g)),D.delete(e),g-=D.length),D=D.right;if(g>0)throw lengthExceeded();t._searchMarker&&updateMarkerChanges(t._searchMarker,S,-w+g)},typeMapDelete=(e,t,s)=>{let g=t._map.get(s);g!==void 0&&g.delete(e)},typeMapSet=(e,t,s,g)=>{let S=t._map.get(s)||null,w=e.doc,E=w.clientID,D;if(g==null)D=new ContentAny([g]);else switch(g.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:D=new ContentAny([g]);break;case Uint8Array:D=new ContentBinary(g);break;case Doc:D=new ContentDoc(g);break;default:if(g instanceof AbstractType)D=new ContentType(g);else throw Error(`Unexpected content type`)}new Item(createID(E,getState(w.store,E)),S,S&&S.lastId,null,null,t,s,D).integrate(e,0)},typeMapGet=(e,t)=>{e.doc??warnPrematureAccess();let s=e._map.get(t);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},typeMapGetAll=e=>{let t={};return e.doc??warnPrematureAccess(),e._map.forEach((e,s)=>{e.deleted||(t[s]=e.content.getContent()[e.length-1])}),t},typeMapHas=(e,t)=>{e.doc??warnPrematureAccess();let s=e._map.get(t);return s!==void 0&&!s.deleted},typeMapGetAllSnapshot=(e,t)=>{let s={};return e._map.forEach((e,g)=>{let S=e;for(;S!==null&&(!t.sv.has(S.id.client)||S.id.clock>=(t.sv.get(S.id.client)||0));)S=S.left;S!==null&&isVisible$1(S,t)&&(s[g]=S.content.getContent()[S.length-1])}),s},createMapIterator=e=>(e.doc??warnPrematureAccess(),iteratorFilter(e._map.entries(),e=>!e[1].deleted));var YArrayEvent=class extends YEvent{},YArray=class e extends AbstractType{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let s=new e;return s.push(t),s}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._length}_callObserver(e,t){super._callObserver(e,t),callTypeObservers(this,e,new YArrayEvent(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,s=>{typeListInsertGenerics(s,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):transact(this.doc,t=>{typeListPushGenerics(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,s=>{typeListDelete(s,this,e,t)})}get(e){return typeListGet(this,e)}toArray(){return typeListToArray(this)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}toJSON(){return this.map(e=>e instanceof AbstractType?e.toJSON():e)}map(e){return typeListMap(this,e)}forEach(e){typeListForEach(this,e)}[Symbol.iterator](){return typeListCreateIterator(this)}_write(e){e.writeTypeRef(YArrayRefID)}};const readYArray=e=>new YArray;var YMapEvent=class extends YEvent{constructor(e,t,s){super(e,t),this.keysChanged=s}},YMap=class e extends AbstractType{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,s)=>{t.set(s,e instanceof AbstractType?e.clone():e)}),t}_callObserver(e,t){callTypeObservers(this,e,new YMapEvent(this,e,t))}toJSON(){this.doc??warnPrematureAccess();let e={};return this._map.forEach((t,s)=>{if(!t.deleted){let g=t.content.getContent()[t.length-1];e[s]=g instanceof AbstractType?g.toJSON():g}}),e}get size(){return[...createMapIterator(this)].length}keys(){return iteratorMap(createMapIterator(this),e=>e[0])}values(){return iteratorMap(createMapIterator(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return iteratorMap(createMapIterator(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??warnPrematureAccess(),this._map.forEach((t,s)=>{t.deleted||e(t.content.getContent()[t.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):transact(this.doc,s=>{typeMapSet(s,this,e,t)}),t}get(e){return typeMapGet(this,e)}has(e){return typeMapHas(this,e)}clear(){this.doc===null?this._prelimContent.clear():transact(this.doc,e=>{this.forEach(function(t,s,g){typeMapDelete(e,g,s)})})}_write(e){e.writeTypeRef(YMapRefID)}};const readYMap=e=>new YMap,equalAttrs$1=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&equalFlat(e,t);var ItemTextListPosition=class{constructor(e,t,s,g){this.left=e,this.right=t,this.index=s,this.currentAttributes=g}forward(){switch(this.right===null&&unexpectedCase(),this.right.content.constructor){case ContentFormat:this.right.deleted||updateCurrentAttributes(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const findNextPosition=(e,t,s)=>{for(;t.right!==null&&s>0;){switch(t.right.content.constructor){case ContentFormat:t.right.deleted||updateCurrentAttributes(t.currentAttributes,t.right.content);break;default:t.right.deleted||(s<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+s)),t.index+=t.right.length,s-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},findPosition=(e,t,s,g)=>{let S=new Map,w=g?findMarker(t,s):null;return w?findNextPosition(e,new ItemTextListPosition(w.p.left,w.p,w.index,S),s-w.index):findNextPosition(e,new ItemTextListPosition(null,t._start,0,S),s)},insertNegatedAttributes=(e,t,s,g)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===ContentFormat&&equalAttrs$1(g.get(s.right.content.key),s.right.content.value));)s.right.deleted||g.delete(s.right.content.key),s.forward();let S=e.doc,w=S.clientID;g.forEach((g,E)=>{let D=s.left,O=s.right,k=new Item(createID(w,getState(S.store,w)),D,D&&D.lastId,O,O&&O.id,t,null,new ContentFormat(E,g));k.integrate(e,0),s.right=k,s.forward()})},updateCurrentAttributes=(e,t)=>{let{key:s,value:g}=t;g===null?e.delete(s):e.set(s,g)},minimizeAttributeChanges=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ContentFormat&&equalAttrs$1(t[e.right.content.key]??null,e.right.content.value));)e.forward()},insertAttributes=(e,t,s,g)=>{let S=e.doc,w=S.clientID,E=new Map;for(let D in g){let O=g[D],k=s.currentAttributes.get(D)??null;if(!equalAttrs$1(k,O)){E.set(D,k);let{left:g,right:j}=s;s.right=new Item(createID(w,getState(S.store,w)),g,g&&g.lastId,j,j&&j.id,t,null,new ContentFormat(D,O)),s.right.integrate(e,0),s.forward()}}return E},insertText=(e,t,s,g,S)=>{s.currentAttributes.forEach((e,t)=>{S[t]===void 0&&(S[t]=null)});let w=e.doc,E=w.clientID;minimizeAttributeChanges(s,S);let D=insertAttributes(e,t,s,S),O=g.constructor===String?new ContentString(g):g instanceof AbstractType?new ContentType(g):new ContentEmbed(g),{left:k,right:j,index:F}=s;t._searchMarker&&updateMarkerChanges(t._searchMarker,s.index,O.getLength()),j=new Item(createID(E,getState(w.store,E)),k,k&&k.lastId,j,j&&j.id,t,null,O),j.integrate(e,0),s.right=j,s.index=F,s.forward(),insertNegatedAttributes(e,t,s,D)},formatText=(e,t,s,g,S)=>{let w=e.doc,E=w.clientID;minimizeAttributeChanges(s,S);let D=insertAttributes(e,t,s,S);iterationLoop:for(;s.right!==null&&(g>0||D.size>0&&(s.right.deleted||s.right.content.constructor===ContentFormat));){if(!s.right.deleted)switch(s.right.content.constructor){case ContentFormat:{let{key:t,value:w}=s.right.content,E=S[t];if(E!==void 0){if(equalAttrs$1(E,w))D.delete(t);else{if(g===0)break iterationLoop;D.set(t,w)}s.right.delete(e)}else s.currentAttributes.set(t,w);break}default:g<s.right.length&&getItemCleanStart(e,createID(s.right.id.client,s.right.id.clock+g)),g-=s.right.length;break}s.forward()}if(g>0){let S=``;for(;g>0;g--)S+=`
|
|
15
15
|
`;s.right=new Item(createID(E,getState(w.store,E)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,t,null,new ContentString(S)),s.right.integrate(e,0),s.forward()}insertNegatedAttributes(e,t,s,D)},cleanupFormattingGap=(e,t,s,g,S)=>{let w=t,E=create$8();for(;w&&(!w.countable||w.deleted);){if(!w.deleted&&w.content.constructor===ContentFormat){let e=w.content;E.set(e.key,e)}w=w.right}let D=0,O=!1;for(;t!==w;){if(s===t&&(O=!0),!t.deleted){let s=t.content;switch(s.constructor){case ContentFormat:{let{key:w,value:k}=s,j=g.get(w)??null;(E.get(w)!==s||j===k)&&(t.delete(e),D++,!O&&(S.get(w)??null)===k&&j!==k&&(j===null?S.delete(w):S.set(w,j))),!O&&!t.deleted&&updateCurrentAttributes(S,s);break}}}t=t.right}return D},cleanupContextlessFormattingGap=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let s=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ContentFormat){let g=t.content.key;s.has(g)?t.delete(e):s.add(g)}t=t.left}},cleanupYTextFormatting=e=>{let t=0;return transact(e.doc,s=>{let g=e._start,S=e._start,w=create$8(),E=copy(w);for(;S;){if(S.deleted===!1)switch(S.content.constructor){case ContentFormat:updateCurrentAttributes(E,S.content);break;default:t+=cleanupFormattingGap(s,g,S,w,E),w=copy(E),g=S;break}S=S.right}}),t},cleanupYTextAfterTransaction=e=>{let t=new Set,s=e.doc;for(let[g,S]of e.afterState.entries()){let w=e.beforeState.get(g)||0;S!==w&&iterateStructs(e,s.store.clients.get(g),w,S,e=>{!e.deleted&&e.content.constructor===ContentFormat&&e.constructor!==GC&&t.add(e.parent)})}transact(s,s=>{iterateDeletedStructs(e,e.deleteSet,e=>{if(e instanceof GC||!e.parent._hasFormatting||t.has(e.parent))return;let g=e.parent;e.content.constructor===ContentFormat?t.add(g):cleanupContextlessFormattingGap(s,e)});for(let e of t)cleanupYTextFormatting(e)})},deleteText=(e,t,s)=>{let g=s,S=copy(t.currentAttributes),w=t.right;for(;s>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case ContentType:case ContentEmbed:case ContentString:s<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+s)),s-=t.right.length,t.right.delete(e);break}t.forward()}w&&cleanupFormattingGap(e,w,t.right,S,t.currentAttributes);let E=(t.left||t.right).parent;return E._searchMarker&&updateMarkerChanges(E._searchMarker,t.index,-g+s),t};var YTextEvent=class extends YEvent{constructor(e,t,s){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){return this._changes===null&&(this._changes={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set}),this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];transact(e,e=>{let s=new Map,g=new Map,S=this.target._start,w=null,E={},D=``,O=0,k=0,j=()=>{if(w!==null){let e=null;switch(w){case`delete`:k>0&&(e={delete:k}),k=0;break;case`insert`:(typeof D==`object`||D.length>0)&&(e={insert:D},s.size>0&&(e.attributes={},s.forEach((t,s)=>{t!==null&&(e.attributes[s]=t)}))),D=``;break;case`retain`:O>0&&(e={retain:O},isEmpty$3(E)||(e.attributes=assign({},E))),O=0;break}e&&t.push(e),w=null}};for(;S!==null;){switch(S.content.constructor){case ContentType:case ContentEmbed:this.adds(S)?this.deletes(S)||(j(),w=`insert`,D=S.content.getContent()[0],j()):this.deletes(S)?(w!==`delete`&&(j(),w=`delete`),k+=1):S.deleted||(w!==`retain`&&(j(),w=`retain`),O+=1);break;case ContentString:this.adds(S)?this.deletes(S)||(w!==`insert`&&(j(),w=`insert`),D+=S.content.str):this.deletes(S)?(w!==`delete`&&(j(),w=`delete`),k+=S.length):S.deleted||(w!==`retain`&&(j(),w=`retain`),O+=S.length);break;case ContentFormat:{let{key:t,value:D}=S.content;if(this.adds(S))this.deletes(S)||(equalAttrs$1(s.get(t)??null,D)?D!==null&&S.delete(e):(w===`retain`&&j(),equalAttrs$1(D,g.get(t)??null)?delete E[t]:E[t]=D));else if(this.deletes(S)){g.set(t,D);let e=s.get(t)??null;equalAttrs$1(e,D)||(w===`retain`&&j(),E[t]=e)}else if(!S.deleted){g.set(t,D);let s=E[t];s!==void 0&&(equalAttrs$1(s,D)?s!==null&&S.delete(e):(w===`retain`&&j(),D===null?delete E[t]:E[t]=D))}S.deleted||(w===`insert`&&j(),updateCurrentAttributes(s,S.content));break}}S=S.right}for(j();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},YText=class e extends AbstractType{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??warnPrematureAccess(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let s=new YTextEvent(this,e,t);callTypeObservers(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??warnPrematureAccess();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===ContentString&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):transact(this.doc,s=>{let g=new ItemTextListPosition(null,this._start,0,new Map);for(let S=0;S<e.length;S++){let w=e[S];if(w.insert!==void 0){let E=!t&&typeof w.insert==`string`&&S===e.length-1&&g.right===null&&w.insert.slice(-1)===`
|
|
16
16
|
`?w.insert.slice(0,-1):w.insert;(typeof E!=`string`||E.length>0)&&insertText(s,this,g,E,w.attributes||{})}else w.retain===void 0?w.delete!==void 0&&deleteText(s,g,w.delete):formatText(s,this,g,w.retain,w.attributes||{})}})}toDelta(e,t,s){this.doc??warnPrematureAccess();let g=[],S=new Map,w=this.doc,E=``,D=this._start;function O(){if(E.length>0){let e={},t=!1;S.forEach((s,g)=>{t=!0,e[g]=s});let s={insert:E};t&&(s.attributes=e),g.push(s),E=``}}let k=()=>{for(;D!==null;){if(isVisible$1(D,e)||t!==void 0&&isVisible$1(D,t))switch(D.content.constructor){case ContentString:{let g=S.get(`ychange`);e!==void 0&&!isVisible$1(D,e)?(g===void 0||g.user!==D.id.client||g.type!==`removed`)&&(O(),S.set(`ychange`,s?s(`removed`,D.id):{type:`removed`})):t!==void 0&&!isVisible$1(D,t)?(g===void 0||g.user!==D.id.client||g.type!==`added`)&&(O(),S.set(`ychange`,s?s(`added`,D.id):{type:`added`})):g!==void 0&&(O(),S.delete(`ychange`)),E+=D.content.str;break}case ContentType:case ContentEmbed:{O();let e={insert:D.content.getContent()[0]};if(S.size>0){let t={};e.attributes=t,S.forEach((e,s)=>{t[s]=e})}g.push(e);break}case ContentFormat:isVisible$1(D,e)&&(O(),updateCurrentAttributes(S,D.content));break}D=D.right}O()};return e||t?transact(w,s=>{e&&splitSnapshotAffectedStructs(s,e),t&&splitSnapshotAffectedStructs(s,t),k()},`cleanup`):k(),g}insert(e,t,s){if(t.length<=0)return;let g=this.doc;g===null?this._pending.push(()=>this.insert(e,t,s)):transact(g,g=>{let S=findPosition(g,this,e,!s);s||(s={},S.currentAttributes.forEach((e,t)=>{s[t]=e})),insertText(g,this,S,t,s)})}insertEmbed(e,t,s){let g=this.doc;g===null?this._pending.push(()=>this.insertEmbed(e,t,s||{})):transact(g,g=>{let S=findPosition(g,this,e,!s);insertText(g,this,S,t,s||{})})}delete(e,t){if(t===0)return;let s=this.doc;s===null?this._pending.push(()=>this.delete(e,t)):transact(s,s=>{deleteText(s,findPosition(s,this,e,!0),t)})}format(e,t,s){if(t===0)return;let g=this.doc;g===null?this._pending.push(()=>this.format(e,t,s)):transact(g,g=>{let S=findPosition(g,this,e,!1);S.right!==null&&formatText(g,this,S,t,s)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):transact(this.doc,t=>{typeMapDelete(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):transact(this.doc,s=>{typeMapSet(s,this,e,t)})}getAttribute(e){return typeMapGet(this,e)}getAttributes(){return typeMapGetAll(this)}_write(e){e.writeTypeRef(YTextRefID)}};const readYText=e=>new YText;var YXmlTreeWalker=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??warnPrematureAccess()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===YXmlElement||t.constructor===YXmlFragment)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},YXmlFragment=class e extends AbstractType{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new YXmlTreeWalker(this,e)}querySelector(e){e=e.toUpperCase();let t=new YXmlTreeWalker(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),from$1(new YXmlTreeWalker(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){callTypeObservers(this,e,new YXmlEvent(this,t,e))}toString(){return typeListMap(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},s){let g=e.createDocumentFragment();return s!==void 0&&s._createAssociation(g,this),typeListForEach(this,S=>{g.insertBefore(S.toDOM(e,t,s),null)}),g}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,s=>{typeListInsertGenerics(s,this,e,t)})}insertAfter(e,t){if(this.doc!==null)transact(this.doc,s=>{let g=e&&e instanceof AbstractType?e._item:e;typeListInsertGenericsAfter(s,this,g,t)});else{let s=this._prelimContent,g=e===null?0:s.findIndex(t=>t===e)+1;if(g===0&&e!==null)throw create$6(`Reference item not found`);s.splice(g,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,s=>{typeListDelete(s,this,e,t)})}toArray(){return typeListToArray(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return typeListGet(this,e)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}forEach(e){typeListForEach(this,e)}_write(e){e.writeTypeRef(YXmlFragmentRefID)}};const readYXmlFragment=e=>new YXmlFragment;var YXmlElement=class e extends YXmlFragment{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return forEach(this.getAttributes(),(e,s)=>{t.setAttribute(s,e)}),t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],s=[];for(let t in e)s.push(t);s.sort();let g=s.length;for(let S=0;S<g;S++){let g=s[S];t.push(g+`="`+e[g]+`"`)}let S=this.nodeName.toLocaleLowerCase();return`<${S}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${S}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):transact(this.doc,s=>{typeMapSet(s,this,e,t)})}getAttribute(e){return typeMapGet(this,e)}hasAttribute(e){return typeMapHas(this,e)}getAttributes(e){return e?typeMapGetAllSnapshot(this,e):typeMapGetAll(this)}toDOM(e=document,t={},s){let g=e.createElement(this.nodeName),S=this.getAttributes();for(let e in S){let t=S[e];typeof t==`string`&&g.setAttribute(e,t)}return typeListForEach(this,S=>{g.appendChild(S.toDOM(e,t,s))}),s!==void 0&&s._createAssociation(g,this),g}_write(e){e.writeTypeRef(YXmlElementRefID),e.writeKey(this.nodeName)}};const readYXmlElement=e=>new YXmlElement(e.readKey());var YXmlEvent=class extends YEvent{constructor(e,t,s){super(e,s),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},YXmlHook=class e extends YMap{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,s)=>{t.set(s,e)}),t}toDOM(e=document,t={},s){let g=t[this.hookName],S;return S=g===void 0?document.createElement(this.hookName):g.createDom(this),S.setAttribute(`data-yjs-hook`,this.hookName),s!==void 0&&s._createAssociation(S,this),S}_write(e){e.writeTypeRef(YXmlHookRefID),e.writeKey(this.hookName)}};const readYXmlHook=e=>new YXmlHook(e.readKey());var YXmlText=class e extends YText{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,s){let g=e.createTextNode(this.toString());return s!==void 0&&s._createAssociation(g,this),g}toString(){return this.toDelta().map(e=>{let t=[];for(let s in e.attributes){let g=[];for(let t in e.attributes[s])g.push({key:t,value:e.attributes[s][t]});g.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:s,attrs:g})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let s=``;for(let e=0;e<t.length;e++){let g=t[e];s+=`<${g.nodeName}`;for(let e=0;e<g.attrs.length;e++){let t=g.attrs[e];s+=` ${t.key}="${t.value}"`}s+=`>`}s+=e.insert;for(let e=t.length-1;e>=0;e--)s+=`</${t[e].nodeName}>`;return s}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(YXmlTextRefID)}};const readYXmlText=e=>new YXmlText;var AbstractStruct=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw methodUnimplemented()}mergeWith(e){return!1}write(e,t,s){throw methodUnimplemented()}integrate(e,t){throw methodUnimplemented()}};const structGCRefNumber=0;var GC=class extends AbstractStruct{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),addStruct(e.doc.store,this)}write(e,t){e.writeInfo(structGCRefNumber),e.writeLen(this.length-t)}getMissing(e,t){return null}},ContentBinary=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const readContentBinary=e=>new ContentBinary(e.readBuf());var ContentDeleted=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let s=new e(this.len-t);return this.len=t,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){addToDeleteSet(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const readContentDeleted=e=>new ContentDeleted(e.readLen()),createDocFromOpts=(e,t)=>new Doc({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var ContentDoc=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(createDocFromOpts(this.doc.guid,this.opts))}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const readContentDoc=e=>new ContentDoc(createDocFromOpts(e.readString(),e.readAny()));var ContentEmbed=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const readContentEmbed=e=>new ContentEmbed(e.readJSON());var ContentFormat=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){let s=t.parent;s._searchMarker=null,s._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const readContentFormat=e=>new ContentFormat(e.readKey(),e.readJSON());var ContentJSON=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let s=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let s=this.arr.length;e.writeLen(s-t);for(let g=t;g<s;g++){let t=this.arr[g];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const readContentJSON=e=>{let t=e.readLen(),s=[];for(let g=0;g<t;g++){let t=e.readString();t===`undefined`?s.push(void 0):s.push(JSON.parse(t))}return new ContentJSON(s)},isDevMode=getVariable(`node_env`)===`development`;var ContentAny=class e{constructor(e){this.arr=e,isDevMode&&deepFreeze(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let s=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let s=this.arr.length;e.writeLen(s-t);for(let g=t;g<s;g++){let t=this.arr[g];e.writeAny(t)}}getRef(){return 8}};const readContentAny=e=>{let t=e.readLen(),s=[];for(let g=0;g<t;g++)s.push(e.readAny());return new ContentAny(s)};var ContentString=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let s=new e(this.str.slice(t));this.str=this.str.slice(0,t);let g=this.str.charCodeAt(t-1);return g>=55296&&g<=56319&&(this.str=this.str.slice(0,t-1)+`�`,s.str=`�`+s.str.slice(1)),s}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const readContentString=e=>new ContentString(e.readString()),typeRefs=[readYArray,readYMap,readYText,readYXmlElement,readYXmlFragment,readYXmlHook,readYXmlText],YArrayRefID=0,YMapRefID=1,YTextRefID=2,YXmlElementRefID=3,YXmlFragmentRefID=4,YXmlHookRefID=5,YXmlTextRefID=6;var ContentType=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const readContentType=e=>new ContentType(typeRefs[e.readTypeRef()](e)),followRedone=(e,t)=>{let s=t,g=0,S;do g>0&&(s=createID(s.client,s.clock+g)),S=getItem(e,s),g=s.clock-S.id.clock,s=S.redone;while(s!==null&&S instanceof Item);return{item:S,diff:g}},keepItem=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},splitItem=(e,t,s)=>{let{client:g,clock:S}=t.id,w=new Item(createID(g,S+s),t,createID(g,S+s-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(s));return t.deleted&&w.markDeleted(),t.keep&&(w.keep=!0),t.redone!==null&&(w.redone=createID(t.redone.client,t.redone.clock+s)),t.right=w,w.right!==null&&(w.right.left=w),e._mergeStructs.push(w),w.parentSub!==null&&w.right===null&&w.parent._map.set(w.parentSub,w),t.length=s,w},isDeletedByUndoStack=(e,t)=>some(e,e=>isDeleted(e.deletions,t)),redoItem=(e,t,s,g,S,w)=>{let E=e.doc,D=E.store,O=E.clientID,k=t.redone;if(k!==null)return getItemCleanStart(e,k);let j=t.parent._item,F=null,L;if(j!==null&&j.deleted===!0){if(j.redone===null&&(!s.has(j)||redoItem(e,j,s,g,S,w)===null))return null;for(;j.redone!==null;)j=getItemCleanStart(e,j.redone)}let B=j===null?t.parent:j.content.type;if(t.parentSub===null){for(F=t.left,L=t;F!==null;){let t=F;for(;t!==null&&t.parent._item!==j;)t=t.redone===null?null:getItemCleanStart(e,t.redone);if(t!==null&&t.parent._item===j){F=t;break}F=F.left}for(;L!==null;){let t=L;for(;t!==null&&t.parent._item!==j;)t=t.redone===null?null:getItemCleanStart(e,t.redone);if(t!==null&&t.parent._item===j){L=t;break}L=L.right}}else if(L=null,t.right&&!S){for(F=t;F!==null&&F.right!==null&&(F.right.redone||isDeleted(g,F.right.id)||isDeletedByUndoStack(w.undoStack,F.right.id)||isDeletedByUndoStack(w.redoStack,F.right.id));)for(F=F.right;F.redone;)F=getItemCleanStart(e,F.redone);if(F&&F.right!==null)return null}else F=B._map.get(t.parentSub)||null;let H=createID(O,getState(D,O)),q=new Item(H,F,F&&F.lastId,L,L&&L.id,B,t.parentSub,t.content.copy());return t.redone=H,keepItem(q,!0),q.integrate(e,0),q};var Item=class e extends AbstractStruct{constructor(e,t,s,g,S,w,E,D){super(e,D.getLength()),this.origin=s,this.left=t,this.right=g,this.rightOrigin=S,this.parent=w,this.parentSub=E,this.redone=null,this.content=D,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=getState(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=getState(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ID&&this.id.client!==this.parent.client&&this.parent.clock>=getState(s,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=getItemCleanEnd(t,s,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=getItemCleanStart(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===GC||this.right&&this.right.constructor===GC)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ID){let e=getItem(s,this.parent);e.constructor===GC?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=getItemCleanEnd(e,e.doc.store,createID(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,s;if(t!==null)s=t.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;let g=new Set,S=new Set;for(;s!==null&&s!==this.right;){if(S.add(s),g.add(s),compareIDs(this.origin,s.origin)){if(s.id.client<this.id.client)t=s,g.clear();else if(compareIDs(this.rightOrigin,s.rightOrigin))break}else if(s.origin!==null&&S.has(getItem(e.doc.store,s.origin)))g.has(getItem(e.doc.store,s.origin))||(t=s,g.clear());else break;s=s.right}this.left=t}if(this.left!==null)this.right=this.left.right,this.left.right=this;else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),addStruct(e.doc.store,this),this.content.integrate(e,this),addChangedTypeToTransaction(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new GC(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:createID(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&compareIDs(e.origin,this.lastId)&&this.right===e&&compareIDs(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),addToDeleteSet(e.deleteSet,this.id.client,this.id.clock,this.length),addChangedTypeToTransaction(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw unexpectedCase();this.content.gc(e),t?replaceStruct(e,this,new GC(this.id,this.length)):this.content=new ContentDeleted(this.length)}write(e,t){let s=t>0?createID(this.id.client,this.id.clock+t-1):this.origin,g=this.rightOrigin,S=this.parentSub,w=this.content.getRef()&31|(s===null?0:128)|(g===null?0:64)|(S===null?0:32);if(e.writeInfo(w),s!==null&&e.writeLeftID(s),g!==null&&e.writeRightID(g),s===null&&g===null){let t=this.parent;if(t._item!==void 0){let s=t._item;if(s===null){let s=findRootTypeKey(t);e.writeParentInfo(!0),e.writeString(s)}else e.writeParentInfo(!1),e.writeLeftID(s.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===ID?(e.writeParentInfo(!1),e.writeLeftID(t)):unexpectedCase();S!==null&&e.writeString(S)}this.content.write(e,t)}};const readItemContent=(e,t)=>contentRefs[t&31](e),contentRefs=[()=>{unexpectedCase()},readContentDeleted,readContentJSON,readContentBinary,readContentString,readContentEmbed,readContentFormat,readContentType,readContentAny,readContentDoc,()=>{unexpectedCase()}],structSkipRefNumber=10;var Skip=class extends AbstractStruct{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){unexpectedCase()}write(e,t){e.writeInfo(structSkipRefNumber),writeVarUint$2(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const glo=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},importIdentifier=`__ $YJS$ __`;glo[importIdentifier]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),glo[importIdentifier]=!0;const highSurrogateRegex=/[\uD800-\uDBFF]/,lowSurrogateRegex=/[\uDC00-\uDFFF]/,simpleDiffString=(e,t)=>{let s=0,g=0;for(;s<e.length&&s<t.length&&e[s]===t[s];)s++;for(s>0&&highSurrogateRegex.test(e[s-1])&&s--;g+s<e.length&&g+s<t.length&&e[e.length-g-1]===t[t.length-g-1];)g++;return g>0&&lowSurrogateRegex.test(e[e.length-g])&&g--,{index:s,remove:e.length-s-g,insert:t.slice(s,t.length-g)}},simpleDiff=simpleDiffString,digest=e=>{let t=createHash(`sha256`);return t.update(e),t.digest()},ySyncPluginKey=new PluginKey(`y-sync`),yUndoPluginKey=new PluginKey(`y-undo`),yCursorPluginKey=new PluginKey(`yjs-cursor`),_convolute=e=>{let t=6;for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},hashOfJSON=e=>toBase64(_convolute(digest(encodeAny(e)))),createEmptyMeta=()=>({mapping:new Map,isOMark:new Map}),isVisible=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!isDeleted(t.ds,e.id),createNodeIfNotExists=(e,t,s,g,S,w)=>{let E=s.mapping.get(e);if(E===void 0){if(e instanceof YXmlElement)return createNodeFromYElement(e,t,s,g,S,w);throw methodUnimplemented()}return E},createNodeFromYElement=(e,t,s,g,S,w)=>{let E=[],D=e=>{if(e instanceof YXmlElement){let D=createNodeIfNotExists(e,t,s,g,S,w);D!==null&&E.push(D)}else{let D=e._item.right?.content?.type;D instanceof YText&&!D._item.deleted&&D._item.id.client===D.doc.clientID&&(e.applyDelta([{retain:e.length},...D.toDelta()]),D.doc.transact(e=>{D._item.delete(e)}));let O=createTextNodesFromYText(e,t,s,g,S,w);O!==null&&O.forEach(e=>{e!==null&&E.push(e)})}};g===void 0||S===void 0?e.toArray().forEach(D):typeListToArraySnapshot(e,new Snapshot(S.ds,g.sv)).forEach(D);try{let D=e.getAttributes(g);g!==void 0&&(isVisible(e._item,g)?isVisible(e._item,S)||(D.ychange=w?w(`added`,e._item.id):{type:`added`}):D.ychange=w?w(`removed`,e._item.id):{type:`removed`});let O=t.node(e.nodeName,D,E);return s.mapping.set(e,O),O}catch(g){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(g&&g.message||g));let S=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)S.inline++;else if(S.block++,t.nodes.rawMdxFallback)try{let S=t.node(`rawMdxFallback`,{reason:String(g&&g.message||g)},[t.text(e.nodeName)]);return s.mapping.set(e,S),S}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return s.mapping.delete(e),null}},createTextNodesFromYText=(e,t,s,g,S,w)=>{let E=[],D=e.toDelta(g,S,w);try{for(let e=0;e<D.length;e++){let s=D[e];E.push(t.text(s.insert,attributesToMarks(s.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return E},createTypeFromTextNodes=(e,t)=>{let s=new YXmlText,g=e.map(e=>({insert:e.text,attributes:marksToAttributes(e.marks,t)}));return s.applyDelta(g),t.mapping.set(s,e),s},createTypeFromElementNode=(e,t)=>{let s=new YXmlElement(e.type.name);for(let t in e.attrs){let g=e.attrs[t];g!==null&&t!==`ychange`&&s.setAttribute(t,g)}return s.insert(0,normalizePNodeContent(e).map(e=>createTypeFromTextOrElementNode(e,t))),t.mapping.set(s,e),s},createTypeFromTextOrElementNode=(e,t)=>e instanceof Array?createTypeFromTextNodes(e,t):createTypeFromElementNode(e,t),isObject$1=e=>typeof e==`object`&&!!e,equalAttrs=(e,t)=>{let s=Object.keys(e).filter(t=>e[t]!==null),g=s.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let S=0;S<s.length&&g;S++){let w=s[S],E=e[w],D=t[w];g=w===`ychange`||E===D||isObject$1(E)&&isObject$1(D)&&equalAttrs(E,D)}return g},normalizePNodeContent=e=>{let t=e.content.content,s=[];for(let e=0;e<t.length;e++){let g=t[e];if(g.isText){let g=[];for(let s=t[e];e<t.length&&s.isText;s=t[++e])g.push(s);e--,s.push(g)}else s.push(g)}return s},equalYTextPText=(e,t)=>{let s=e.toDelta();return s.length===t.length&&s.every((e,s)=>e.insert===t[s].text&&keys$1(e.attributes||{}).length===t[s].marks.length&&every(e.attributes,(e,g)=>{let S=yattr2markname(g),w=t[s].marks;return w.find(e=>e.type.name===S)?equalAttrs(e,w.find(e=>e.type.name===S)?.attrs):!1}))},equalYTypePNode=(e,t)=>{if(e instanceof YXmlElement&&!(t instanceof Array)&&matchNodeName(e,t)){let s=normalizePNodeContent(t);return e._length===s.length&&equalAttrs(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>equalYTypePNode(e,s[t]))}return e instanceof YXmlText&&t instanceof Array&&equalYTextPText(e,t)},mappedIdentity=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,s)=>t[s]===e),computeChildEqualityFactor=(e,t,s)=>{let g=e.toArray(),S=normalizePNodeContent(t),w=S.length,E=g.length,D=min$2(E,w),O=0,k=0,j=!1;for(;O<D;O++){let e=g[O],t=S[O];if(mappedIdentity(s.mapping.get(e),t))j=!0;else if(!equalYTypePNode(e,t))break}for(;O+k<D;k++){let e=g[E-k-1],t=S[w-k-1];if(mappedIdentity(s.mapping.get(e),t))j=!0;else if(!equalYTypePNode(e,t))break}return{equalityFactor:O+k,foundMappedChild:j}},ytextTrans=e=>{let t=``,s=e._start,g={};for(;s!==null;)s.deleted||(s.countable&&s.content instanceof ContentString?t+=s.content.str:s.content instanceof ContentFormat&&(g[s.content.key]=null)),s=s.right;return{str:t,nAttrs:g}},updateYText=(e,t,s)=>{s.mapping.set(e,t);let{nAttrs:g,str:S}=ytextTrans(e),w=t.map(e=>({insert:e.text,attributes:Object.assign({},g,marksToAttributes(e.marks,s))})),{insert:E,remove:D,index:O}=simpleDiff(S,w.map(e=>e.insert).join(``));e.delete(O,D),e.insert(O,E),e.applyDelta(w.map(e=>({retain:e.insert.length,attributes:e.attributes})))},hashedMarkNameRegex=/(.*)(--[a-zA-Z0-9+/=]{8})$/,yattr2markname=e=>hashedMarkNameRegex.exec(e)?.[1]??e,attributesToMarks=(e,t)=>{let s=[];for(let g in e)s.push(t.mark(yattr2markname(g),e[g]));return s},marksToAttributes=(e,t)=>{let s={};return e.forEach(e=>{if(e.type.name!==`ychange`){let g=setIfUndefined$1(t.isOMark,e.type,()=>!e.type.excludes(e.type));s[g?`${e.type.name}--${hashOfJSON(e.toJSON())}`:e.type.name]=e.attrs}}),s},updateYFragment=(e,t,s,g)=>{if(t instanceof YXmlElement&&t.nodeName!==s.type.name)throw Error(`node name mismatch!`);if(g.mapping.set(t,s),t instanceof YXmlElement){let e=t.getAttributes(),g=s.attrs;for(let s in g)g[s]===null?t.removeAttribute(s):e[s]!==g[s]&&s!==`ychange`&&t.setAttribute(s,g[s]);for(let s in e)g[s]===void 0&&t.removeAttribute(s)}let S=normalizePNodeContent(s),w=S.length,E=t.toArray(),D=E.length,O=min$2(w,D),k=0,j=0;for(;k<O;k++){let e=E[k],t=S[k];if(!mappedIdentity(g.mapping.get(e),t))if(equalYTypePNode(e,t))g.mapping.set(e,t);else break}for(;j+k+1<O;j++){let e=E[D-j-1],t=S[w-j-1];if(!mappedIdentity(g.mapping.get(e),t))if(equalYTypePNode(e,t))g.mapping.set(e,t);else break}e.transact(()=>{for(;D-k-j>0&&w-k-j>0;){let s=E[k],O=S[k],F=E[D-j-1],L=S[w-j-1];if(s instanceof YXmlText&&O instanceof Array)equalYTextPText(s,O)||updateYText(s,O,g),k+=1;else{let S=s instanceof YXmlElement&&matchNodeName(s,O),w=F instanceof YXmlElement&&matchNodeName(F,L);if(S&&w){let e=computeChildEqualityFactor(s,O,g),t=computeChildEqualityFactor(F,L,g);e.foundMappedChild&&!t.foundMappedChild?w=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?S=!1:w=!1}S?(updateYFragment(e,s,O,g),k+=1):w?(updateYFragment(e,F,L,g),j+=1):(g.mapping.delete(t.get(k)),t.delete(k,1),t.insert(k,[createTypeFromTextOrElementNode(O,g)]),k+=1)}}let s=D-k-j;if(D===1&&w===0&&E[0]instanceof YXmlText?(g.mapping.delete(E[0]),E[0].delete(0,E[0].length)):s>0&&(t.slice(k,k+s).forEach(e=>g.mapping.delete(e)),t.delete(k,s)),k+j<w){let e=[];for(let t=k;t<w-j;t++)e.push(createTypeFromTextOrElementNode(S[t],g));t.insert(k,e)}},ySyncPluginKey)},matchNodeName=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,yXmlFragmentToProseMirrorFragment=(e,t)=>{let s=e.toArray().map(e=>createNodeFromYElement(e,t,createEmptyMeta())).filter(e=>e!==null);return Fragment.fromArray(s)},yXmlFragmentToProseMirrorRootNode=(e,t)=>t.topNodeType.create(null,yXmlFragmentToProseMirrorFragment(e,t));var import_dist$1=require_dist$1();const STALE_TMP_AGE_MS=3e4,DEFAULT_FS={writeFile:(e,t,s)=>writeFile(e,t,s),rename:(e,t)=>rename(e,t)};async function sweepStaleTmps(e){try{let t=dirname(e),s=`${basename(e)}.tmp.`,g=Date.now()-STALE_TMP_AGE_MS,S=await readdir(t);await Promise.all(S.map(async e=>{if(!e.startsWith(s))return;let S=join(t,e);try{(await stat$1(S)).mtimeMs<g&&await unlink(S)}catch{}}))}catch{}}function sweepStaleTmpsSync(e){try{let t=dirname(e),s=`${basename(e)}.tmp.`,g=Date.now()-STALE_TMP_AGE_MS;for(let e of readdirSync(t)){if(!e.startsWith(s))continue;let S=join(t,e);try{statSync(S).mtimeMs<g&&unlinkSync(S)}catch{}}}catch{}}async function atomicWriteFile(e,t,s={}){await sweepStaleTmps(e);let g=s.fs??DEFAULT_FS,S=`${e}.tmp.${crypto.randomUUID()}`;try{await g.writeFile(S,t,{encoding:`utf-8`,mode:s.mode??420}),await g.rename(S,e)}catch(e){try{unlinkSync(S)}catch{}throw e}}function atomicWriteFileSync(e,t,s={}){sweepStaleTmpsSync(e);let g=`${e}.tmp.${crypto.randomUUID()}`;try{writeFileSync(g,t,{encoding:`utf-8`,mode:s.mode??420}),renameSync(g,e)}catch(e){try{unlinkSync(g)}catch{}throw e}}var FileLockTimeoutError=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};const sleep=e=>new Promise(t=>{setTimeout(t,e)});async function withFileLock(e,t,s={}){let g=s.timeoutMs??5e3,S=s.retryIntervalMs??25,w=g*2,E=Date.now()+g;for(;;){let D;try{D=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let D;try{let t=statSync(e);D=Date.now()-t.mtimeMs}catch{continue}let O=!1;if(D>w){s.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:D,staleThresholdMs:w});try{unlinkSync(e),O=!0}catch{}}if(O)continue;if(Date.now()>=E)throw new FileLockTimeoutError(e,g);await sleep(S);continue}try{return await t()}finally{try{closeSync(D)}catch{}try{unlinkSync(e)}catch{}}}}function sleepSyncBusy(e){let t=Date.now()+e;for(;Date.now()<t;);}function withFileLockSync(e,t,s={}){let g=s.timeoutMs??5e3,S=s.retryIntervalMs??25,w=g*2,E=Date.now()+g;for(;;){let D;try{D=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let D;try{let t=statSync(e);D=Date.now()-t.mtimeMs}catch{continue}let O=!1;if(D>w){s.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:D,staleThresholdMs:w});try{unlinkSync(e),O=!0}catch{}}if(O)continue;if(Date.now()>=E)throw new FileLockTimeoutError(e,g);sleepSyncBusy(S);continue}try{return t()}finally{try{closeSync(D)}catch{}try{unlinkSync(e)}catch{}}}}const CONFIG_FILENAME$1=`config.yml`,USER_CONFIG_FILENAME=`global.yml`;function schemaUrl(e){return`https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/${e===`user`?`config.user.schema.json`:e===`project-local`?`config.project-local.schema.json`:`config.project.schema.json`}`}function defaultFirstWriteHeader(e){return`# yaml-language-server: $schema=${schemaUrl(e)}\n`}function resolveConfigPath(e,t,s){if(e===`user`)return resolve(s??homedir(),`.ok`,USER_CONFIG_FILENAME);let g=isAbsolute(t)?t:resolve(t);return e===`project-local`?resolve(g,`.ok`,LOCAL_DIR,CONFIG_FILENAME$1):resolve(g,`.ok`,CONFIG_FILENAME$1)}function err(e){return{ok:!1,error:e}}function ok(e){return{ok:!0,...e}}async function writeConfigPatch(e){return withConfigSpan(`config.patch`,{"config.scope":e.scope,"config.transport":`fs`},async t=>{let s=await writeConfigPatchInner(e);return t.setAttribute(`config.outcome`,s.ok?`success`:`rejected`),s.ok||t.setAttribute(`config.error.code`,s.error.code),s})}async function writeConfigPatchInner(e){let{cwd:t,scope:s,patch:g,homedirOverride:S}=e,w=resolveConfigPath(s,t,S),E=validatePatchScopes(g,s);if(E!==null)return err(E);try{await mkdir(dirname(w),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${w}: ${e instanceof Error?e.message:String(e)}`})}try{return await withFileLock(`${w}.lock`,()=>writeConfigPatchLocked(e,w))}catch(e){if(e instanceof FileLockTimeoutError)return err({code:`WRITE_ERROR`,detail:e.message});throw e}}async function writeConfigPatchLocked(e,t){let{patch:s,scope:g,firstWriteHeader:S}=e,w=``,E=!1;if(existsSync(t)){E=!0;try{w=readFileSync(t,`utf-8`)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not read existing config: ${e instanceof Error?e.message:String(e)}`})}}let D=(0,import_dist$1.parseDocument)(w);if(D.errors.length>0)return err({code:`YAML_PARSE`,detail:D.errors.map(e=>e.message).join(`; `)});if(D.contents===null)D.contents=D.createNode({});else if(!(0,import_dist$1.isMap)(D.contents))return err({code:`YAML_PARSE`,detail:`Top-level YAML value must be a mapping (object), got ${(0,import_dist$1.isSeq)(D.contents)?`sequence`:`scalar`}`});let O=applyPatchToDocument(D,s),k=D.toJSON(),j=withConfigSpanSync(`config.validate`,{"config.scope":g,"config.validation.layer":`L2`},e=>{let t=ConfigSchema$1.safeParse(k);if(e.setAttribute(`config.outcome`,t.success?`success`:`rejected`),!t.success)for(let e of t.error.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":e.path.map(e=>String(e)).join(`.`),"issue.message":e.message});return t});if(!j.success)return err({code:`SCHEMA_INVALID`,issues:j.error.issues.map(toConfigIssue)});let F=D.toString();if(!E){let e=S===void 0?defaultFirstWriteHeader(g):S??``;e.length>0&&(F=`${e.endsWith(`
|
|
17
17
|
`)?e:`${e}\n`}${F}`)}try{await mkdir(dirname(t),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${t}: ${e instanceof Error?e.message:String(e)}`})}try{await atomicWriteFile(t,F)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not write ${t}: ${e instanceof Error?e.message:String(e)}`})}return ok({effective:j.data,appliedPaths:O,path:t,created:!E})}function buildSchemaInvalidError(e,t,s,g){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let S=e.path.map(e=>typeof e==`symbol`?String(e):e),w=locateIssue({file:g,source:s,doc:t,path:S});return{path:S,message:e.message,issueCode:e.code,...w===void 0?{}:{source:w}}})}}function attemptSideline(e,t,s){let g=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return renameSync(e,g),g}catch(t){s(`[config] Could not sideline invalid config file ${e} → ${g}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function readConfigSafely(e){let{absPath:t,sideline:s=!0,timestamp:g=new Date().toISOString()}=e,S=e.warn??(e=>console.warn(e)),w=ConfigSchema$1.parse({});if(!existsSync(t))return{valid:!0,value:w,source:void 0};let E;try{E=readFileSync(t,`utf-8`)}catch(e){let s=e instanceof Error?e.message:String(e);return S(`[config] Could not read ${t}: ${s}. Using schema defaults.`),{valid:!1,value:w,error:{code:`UNKNOWN`,message:`Read failed: ${s}`}}}let D=(0,import_dist$1.parseDocument)(E);if(D.errors.length>0){let e=D.errors.map(e=>e.message).join(`; `);S(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(s?``:` Pass-through mode: file left in place.`));let E=s?attemptSideline(t,g,S):void 0;return{valid:!1,value:w,error:{code:`YAML_PARSE`,detail:e},...E===void 0?{}:{sidelinedTo:E}}}let O=D.toJSON()??{},k=ConfigSchema$1.safeParse(O);if(!k.success){let e=buildSchemaInvalidError(k,D,E,t);S(`[config] ${t} fails schema validation (${k.error.issues.length} issue(s)). Using schema defaults.`+(s?``:` Pass-through mode: file left in place.`));let O=s?attemptSideline(t,g,S):void 0;return{valid:!1,value:w,error:e,...O===void 0?{}:{sidelinedTo:O}}}let j=detectRemovedKeys({value:O,file:t,source:E,doc:D}),F=j[0];if(F!==void 0){S(`[config] ${t} carries removed config key(s):\n${j.map(humanFormat).join(`
|
|
@@ -47,7 +47,7 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
47
47
|
|| ${D} === "boolean" || ${w} === null`).assign(O,(0,S._)`[${w}]`)}}}function B({gen:e,parentData:t,parentDataProperty:s},g){e.if((0,S._)`${t} !== undefined`,()=>e.assign((0,S._)`${t}[${s}]`,g))}function H(e,t,s,g=E.Correct){let w=g===E.Correct?S.operators.EQ:S.operators.NEQ,D;switch(e){case`null`:return(0,S._)`${t} ${w} null`;case`array`:D=(0,S._)`Array.isArray(${t})`;break;case`object`:D=(0,S._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:D=O((0,S._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:D=O();break;default:return(0,S._)`typeof ${t} ${w} ${e}`}return g===E.Correct?D:(0,S.not)(D);function O(e=S.nil){return(0,S.and)((0,S._)`typeof ${t} == "number"`,e,s?(0,S._)`isFinite(${t})`:S.nil)}}e.checkDataType=H;function q(e,t,s,g){if(e.length===1)return H(e[0],t,s,g);let E,D=(0,w.toHash)(e);if(D.array&&D.object){let e=(0,S._)`typeof ${t} != "object"`;E=D.null?e:(0,S._)`!${t} || ${e}`,delete D.null,delete D.array,delete D.object}else E=S.nil;D.number&&delete D.integer;for(let e in D)E=(0,S.and)(E,H(e,t,s,g));return E}e.checkDataTypes=q;let ee={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,S._)`{type: ${e}}`:(0,S._)`{type: ${t}}`};function J(e){let t=Y(e);(0,g.reportError)(t,ee)}e.reportTypeError=J;function Y(e){let{gen:t,data:s,schema:g}=e,S=(0,w.schemaRefOrVal)(e,g,`type`);return{gen:t,keyword:`type`,data:s,schema:g.type,schemaCode:S,schemaValue:S,parentSchema:g,params:{},it:e}}})),require_defaults=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=require_codegen(),s=require_util();function g(e,t){let{properties:s,items:g}=e.schema;if(t===`object`&&s)for(let t in s)S(e,t,s[t].default);else t===`array`&&Array.isArray(g)&&g.forEach((t,s)=>S(e,s,t.default))}e.assignDefaults=g;function S(e,g,S){let{gen:w,compositeRule:E,data:D,opts:O}=e;if(S===void 0)return;let k=(0,t._)`${D}${(0,t.getProperty)(g)}`;if(E){(0,s.checkStrictMode)(e,`default is ignored for: ${k}`);return}let j=(0,t._)`${k} === undefined`;O.useDefaults===`empty`&&(j=(0,t._)`${j} || ${k} === null || ${k} === ""`),w.if(j,(0,t._)`${k} = ${(0,t.stringify)(S)}`)}})),require_code=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=require_codegen(),s=require_util(),g=require_names(),S=require_util();function w(e,s){let{gen:g,data:S,it:w}=e;g.if(F(g,S,s,w.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${s}`},!0),e.error()})}e.checkReportMissingProp=w;function E({gen:e,data:s,it:{opts:g}},S,w){return(0,t.or)(...S.map(S=>(0,t.and)(F(e,s,S,g.ownProperties),(0,t._)`${w} = ${S}`)))}e.checkMissingProp=E;function D(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=D;function O(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=O;function k(e,s,g){return(0,t._)`${O(e)}.call(${s}, ${g})`}e.isOwnProperty=k;function j(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} !== undefined`;return S?(0,t._)`${w} && ${k(e,s,g)}`:w}e.propertyInData=j;function F(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} === undefined`;return S?(0,t.or)(w,(0,t.not)(k(e,s,g))):w}e.noPropertyInData=F;function L(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=L;function B(e,t){return L(t).filter(g=>!(0,s.alwaysValidSchema)(e,t[g]))}e.schemaProperties=B;function H({schemaCode:e,data:s,it:{gen:S,topSchemaRef:w,schemaPath:E,errorPath:D},it:O},k,j,F){let L=F?(0,t._)`${e}, ${s}, ${w}${E}`:s,B=[[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,D)],[g.default.parentData,O.parentData],[g.default.parentDataProperty,O.parentDataProperty],[g.default.rootData,g.default.rootData]];O.opts.dynamicRef&&B.push([g.default.dynamicAnchors,g.default.dynamicAnchors]);let H=(0,t._)`${L}, ${S.object(...B)}`;return j===t.nil?(0,t._)`${k}(${H})`:(0,t._)`${k}.call(${j}, ${H})`}e.callValidateCode=H;let q=(0,t._)`new RegExp`;function ee({gen:e,it:{opts:s}},g){let w=s.unicodeRegExp?`u`:``,{regExp:E}=s.code,D=E(g,w);return e.scopeValue(`pattern`,{key:D.toString(),ref:D,code:(0,t._)`${E.code===`new RegExp`?q:(0,S.useFunc)(e,E)}(${g}, ${w})`})}e.usePattern=ee;function J(e){let{gen:g,data:S,keyword:w,it:E}=e,D=g.name(`valid`);if(E.allErrors){let e=g.let(`valid`,!0);return O(()=>g.assign(e,!1)),e}return g.var(D,!0),O(()=>g.break()),D;function O(E){let O=g.const(`len`,(0,t._)`${S}.length`);g.forRange(`i`,0,O,S=>{e.subschema({keyword:w,dataProp:S,dataPropType:s.Type.Num},D),g.if((0,t.not)(D),E)})}}e.validateArray=J;function Y(e){let{gen:g,schema:S,keyword:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(S.some(e=>(0,s.alwaysValidSchema)(E,e))&&!E.opts.unevaluated)return;let D=g.let(`valid`,!1),O=g.name(`_valid`);g.block(()=>S.forEach((s,S)=>{let E=e.subschema({keyword:w,schemaProp:S,compositeRule:!0},O);g.assign(D,(0,t._)`${D} || ${O}`),e.mergeValidEvaluated(E,O)||g.if((0,t.not)(D))})),e.result(D,()=>e.reset(),()=>e.error(!0))}e.validateUnion=Y})),require_keyword=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=require_codegen(),s=require_names(),g=require_code(),S=require_errors();function w(e,s){let{gen:g,keyword:S,schema:w,parentSchema:E,it:D}=e,O=s.macro.call(D.self,w,E,D),k=j(g,S,O);D.opts.validateSchema!==!1&&D.self.validateSchema(O,!0);let F=g.name(`valid`);e.subschema({schema:O,schemaPath:t.nil,errSchemaPath:`${D.errSchemaPath}/${S}`,topSchemaRef:k,compositeRule:!0},F),e.pass(F,()=>e.error(!0))}e.macroKeywordCode=w;function E(e,S){var w;let{gen:E,keyword:F,schema:L,parentSchema:B,$data:H,it:q}=e;k(q,S);let ee=j(E,F,!H&&S.compile?S.compile.call(q.self,L,B,q):S.validate),J=E.let(`valid`);e.block$data(J,Y),e.ok(S.valid??J);function Y(){if(S.errors===!1)ae(),S.modifying&&D(e),oe(()=>e.error());else{let t=S.async?te():ne();S.modifying&&D(e),oe(()=>O(e,t))}}function te(){let e=E.let(`ruleErrs`,null);return E.try(()=>ae((0,t._)`await `),s=>E.assign(J,!1).if((0,t._)`${s} instanceof ${q.ValidationError}`,()=>E.assign(e,(0,t._)`${s}.errors`),()=>E.throw(s))),e}function ne(){let e=(0,t._)`${ee}.errors`;return E.assign(e,null),ae(t.nil),e}function ae(w=S.async?(0,t._)`await `:t.nil){let D=q.opts.passContext?s.default.this:s.default.self,O=!(`compile`in S&&!H||S.schema===!1);E.assign(J,(0,t._)`${w}${(0,g.callValidateCode)(e,ee,D,O)}`,S.modifying)}function oe(e){var s;E.if((0,t.not)(S.valid??J),e)}}e.funcKeywordCode=E;function D(e){let{gen:s,data:g,it:S}=e;s.if(S.parentData,()=>s.assign(g,(0,t._)`${S.parentData}[${S.parentDataProperty}]`))}function O(e,g){let{gen:w}=e;w.if((0,t._)`Array.isArray(${g})`,()=>{w.assign(s.default.vErrors,(0,t._)`${s.default.vErrors} === null ? ${g} : ${s.default.vErrors}.concat(${g})`).assign(s.default.errors,(0,t._)`${s.default.vErrors}.length`),(0,S.extendErrors)(e)},()=>e.error())}function k({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function j(e,s,g){if(g===void 0)throw Error(`keyword "${s}" failed to compile`);return e.scopeValue(`keyword`,typeof g==`function`?{ref:g}:{ref:g,code:(0,t.stringify)(g)})}function F(e,t,s=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||s&&e===void 0)}e.validSchemaType=F;function L({schema:e,opts:t,self:s,errSchemaPath:g},S,w){if(Array.isArray(S.keyword)?!S.keyword.includes(w):S.keyword!==w)throw Error(`ajv implementation error`);let E=S.dependencies;if(E?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${w}: ${E.join(`,`)}`);if(S.validateSchema&&!S.validateSchema(e[w])){let e=`keyword "${w}" value is invalid at path "${g}": `+s.errorsText(S.validateSchema.errors);if(t.validateSchema===`log`)s.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=L})),require_subschema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=require_codegen(),s=require_util();function g(e,{keyword:g,schemaProp:S,schema:w,schemaPath:E,errSchemaPath:D,topSchemaRef:O}){if(g!==void 0&&w!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(g!==void 0){let w=e.schema[g];return S===void 0?{schema:w,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}`,errSchemaPath:`${e.errSchemaPath}/${g}`}:{schema:w[S],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}${(0,t.getProperty)(S)}`,errSchemaPath:`${e.errSchemaPath}/${g}/${(0,s.escapeFragment)(S)}`}}if(w!==void 0){if(E===void 0||D===void 0||O===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:w,schemaPath:E,topSchemaRef:O,errSchemaPath:D}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=g;function S(e,g,{dataProp:S,dataPropType:w,data:E,dataTypes:D,propertyName:O}){if(E!==void 0&&S!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:k}=g;if(S!==void 0){let{errorPath:E,dataPathArr:D,opts:O}=g;j(k.let(`data`,(0,t._)`${g.data}${(0,t.getProperty)(S)}`,!0)),e.errorPath=(0,t.str)`${E}${(0,s.getErrorPath)(S,w,O.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${S}`,e.dataPathArr=[...D,e.parentDataProperty]}E!==void 0&&(j(E instanceof t.Name?E:k.let(`data`,E,!0)),O!==void 0&&(e.propertyName=O)),D&&(e.dataTypes=D);function j(t){e.data=t,e.dataLevel=g.dataLevel+1,e.dataTypes=[],g.definedProperties=new Set,e.parentData=g.data,e.dataNames=[...g.dataNames,t]}}e.extendSubschemaData=S;function w(e,{jtdDiscriminator:t,jtdMetadata:s,compositeRule:g,createErrors:S,allErrors:w}){g!==void 0&&(e.compositeRule=g),S!==void 0&&(e.createErrors=S),w!==void 0&&(e.allErrors=w),e.jtdDiscriminator=t,e.jtdMetadata=s}e.extendSubschemaMode=w})),require_fast_deep_equal=__commonJSMin$2(((e,t)=>{t.exports=function e(t,s){if(t===s)return!0;if(t&&s&&typeof t==`object`&&typeof s==`object`){if(t.constructor!==s.constructor)return!1;var g,S,w;if(Array.isArray(t)){if(g=t.length,g!=s.length)return!1;for(S=g;S--!==0;)if(!e(t[S],s[S]))return!1;return!0}if(t.constructor===RegExp)return t.source===s.source&&t.flags===s.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===s.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===s.toString();if(w=Object.keys(t),g=w.length,g!==Object.keys(s).length)return!1;for(S=g;S--!==0;)if(!Object.prototype.hasOwnProperty.call(s,w[S]))return!1;for(S=g;S--!==0;){var E=w[S];if(!e(t[E],s[E]))return!1}return!0}return t!==t&&s!==s}})),require_json_schema_traverse=__commonJSMin$2(((e,t)=>{var s=t.exports=function(e,t,s){typeof t==`function`&&(s=t,t={}),s=t.cb||s;var S=typeof s==`function`?s:s.pre||function(){},w=s.post||function(){};g(t,S,w,e,``,e)};s.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},s.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},s.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},s.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function g(e,t,w,E,D,O,k,j,F,L){if(E&&typeof E==`object`&&!Array.isArray(E)){for(var B in t(E,D,O,k,j,F,L),E){var H=E[B];if(Array.isArray(H)){if(B in s.arrayKeywords)for(var q=0;q<H.length;q++)g(e,t,w,H[q],D+`/`+B+`/`+q,O,D,B,E,q)}else if(B in s.propsKeywords){if(H&&typeof H==`object`)for(var ee in H)g(e,t,w,H[ee],D+`/`+B+`/`+S(ee),O,D,B,E,ee)}else (B in s.keywords||e.allKeys&&!(B in s.skipKeywords))&&g(e,t,w,H,D+`/`+B,O,D,B,E)}w(E,D,O,k,j,F,L)}}function S(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),require_resolve=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=require_util(),s=require_fast_deep_equal(),g=require_json_schema_traverse(),S=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function w(e,t=!0){return typeof e==`boolean`?!0:t===!0?!D(e):t?O(e)<=t:!1}e.inlineRef=w;let E=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function D(e){for(let t in e){if(E.has(t))return!0;let s=e[t];if(Array.isArray(s)&&s.some(D)||typeof s==`object`&&D(s))return!0}return!1}function O(e){let s=0;for(let g in e)if(g===`$ref`||(s++,!S.has(g)&&(typeof e[g]==`object`&&(0,t.eachItem)(e[g],e=>s+=O(e)),s===1/0)))return 1/0;return s}function k(e,t=``,s){return s!==!1&&(t=L(t)),j(e,e.parse(t))}e.getFullPath=k;function j(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=j;let F=/#\/?$/;function L(e){return e?e.replace(F,``):``}e.normalizeId=L;function B(e,t,s){return s=L(s),e.resolve(t,s)}e.resolveUrl=B;let H=/^[a-z_][-a-z0-9._]*$/i;function q(e,t){if(typeof e==`boolean`)return{};let{schemaId:S,uriResolver:w}=this.opts,E=L(e[S]||t),D={"":E},O=k(w,E,!1),j={},F=new Set;return g(e,{allKeys:!0},(e,t,s,g)=>{if(g===void 0)return;let w=O+t,E=D[g];typeof e[S]==`string`&&(E=k.call(this,e[S])),ee.call(this,e.$anchor),ee.call(this,e.$dynamicAnchor),D[t]=E;function k(t){let s=this.opts.uriResolver.resolve;if(t=L(E?s(E,t):t),F.has(t))throw q(t);F.add(t);let g=this.refs[t];return typeof g==`string`&&(g=this.refs[g]),typeof g==`object`?B(e,g.schema,t):t!==L(w)&&(t[0]===`#`?(B(e,j[t],t),j[t]=e):this.refs[t]=w),t}function ee(e){if(typeof e==`string`){if(!H.test(e))throw Error(`invalid anchor "${e}"`);k.call(this,`#${e}`)}}}),j;function B(e,t,g){if(t!==void 0&&!s(e,t))throw q(g)}function q(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=q})),require_validate=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=require_boolSchema(),s=require_dataType(),g=require_applicability(),S=require_dataType(),w=require_defaults(),E=require_keyword(),D=require_subschema(),O=require_codegen(),k=require_names(),j=require_resolve(),F=require_util(),L=require_errors();function B(e){if(oe(e)&&(ce(e),ae(e))){J(e);return}H(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=B;function H({gen:e,validateName:t,schema:s,schemaEnv:g,opts:S},w){S.code.es5?e.func(t,(0,O._)`${k.default.data}, ${k.default.valCxt}`,g.$async,()=>{e.code((0,O._)`"use strict"; ${te(s,S)}`),ee(e,S),e.code(w)}):e.func(t,(0,O._)`${k.default.data}, ${q(S)}`,g.$async,()=>e.code(te(s,S)).code(w))}function q(e){return(0,O._)`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${e.dynamicRef?(0,O._)`, ${k.default.dynamicAnchors}={}`:O.nil}}={}`}function ee(e,t){e.if(k.default.valCxt,()=>{e.var(k.default.instancePath,(0,O._)`${k.default.valCxt}.${k.default.instancePath}`),e.var(k.default.parentData,(0,O._)`${k.default.valCxt}.${k.default.parentData}`),e.var(k.default.parentDataProperty,(0,O._)`${k.default.valCxt}.${k.default.parentDataProperty}`),e.var(k.default.rootData,(0,O._)`${k.default.valCxt}.${k.default.rootData}`),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{e.var(k.default.instancePath,(0,O._)`""`),e.var(k.default.parentData,(0,O._)`undefined`),e.var(k.default.parentDataProperty,(0,O._)`undefined`),e.var(k.default.rootData,k.default.data),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`{}`)})}function J(e){let{schema:t,opts:s,gen:g}=e;H(e,()=>{s.$comment&&t.$comment&&_e(e),fe(e),g.let(k.default.vErrors,null),g.let(k.default.errors,0),s.unevaluated&&Y(e),ue(e),ve(e)})}function Y(e){let{gen:t,validateName:s}=e;e.evaluated=t.const(`evaluated`,(0,O._)`${s}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}function te(e,t){let s=typeof e==`object`&&e[t.schemaId];return s&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${s} */`:O.nil}function ne(e,s){if(oe(e)&&(ce(e),ae(e))){se(e,s);return}(0,t.boolOrEmptySchema)(e,s)}function ae({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let s in e)if(t.RULES.all[s])return!0;return!1}function oe(e){return typeof e.schema!=`boolean`}function se(e,t){let{schema:s,gen:g,opts:S}=e;S.$comment&&s.$comment&&_e(e),me(e),ge(e);let w=g.const(`_errs`,k.default.errors);ue(e,w),g.var(t,(0,O._)`${w} === ${k.default.errors}`)}function ce(e){(0,F.checkUnknownRules)(e),de(e)}function ue(e,t){if(e.opts.jtd)return Ce(e,[],!1,t);let g=(0,s.getSchemaTypes)(e.schema);Ce(e,g,!(0,s.coerceAndCheckDataType)(e,g),t)}function de(e){let{schema:t,errSchemaPath:s,opts:g,self:S}=e;t.$ref&&g.ignoreKeywordsWithRef&&(0,F.schemaHasRulesButRef)(t,S.RULES)&&S.logger.warn(`$ref: keywords ignored in schema at path "${s}"`)}function fe(e){let{schema:t,opts:s}=e;t.default!==void 0&&s.useDefaults&&s.strictSchema&&(0,F.checkStrictMode)(e,`default is ignored in the schema root`)}function me(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,j.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ge(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function _e({gen:e,schemaEnv:t,schema:s,errSchemaPath:g,opts:S}){let w=s.$comment;if(S.$comment===!0)e.code((0,O._)`${k.default.self}.logger.log(${w})`);else if(typeof S.$comment==`function`){let s=(0,O.str)`${g}/$comment`,S=e.scopeValue(`root`,{ref:t.root});e.code((0,O._)`${k.default.self}.opts.$comment(${w}, ${s}, ${S}.schema)`)}}function ve(e){let{gen:t,schemaEnv:s,validateName:g,ValidationError:S,opts:w}=e;s.$async?t.if((0,O._)`${k.default.errors} === 0`,()=>t.return(k.default.data),()=>t.throw((0,O._)`new ${S}(${k.default.vErrors})`)):(t.assign((0,O._)`${g}.errors`,k.default.vErrors),w.unevaluated&&ye(e),t.return((0,O._)`${k.default.errors} === 0`))}function ye({gen:e,evaluated:t,props:s,items:g}){s instanceof O.Name&&e.assign((0,O._)`${t}.props`,s),g instanceof O.Name&&e.assign((0,O._)`${t}.items`,g)}function Ce(e,t,s,w){let{gen:E,schema:D,data:j,allErrors:L,opts:B,self:H}=e,{RULES:q}=H;if(D.$ref&&(B.ignoreKeywordsWithRef||!(0,F.schemaHasRulesButRef)(D,q))){E.block(()=>Ve(e,`$ref`,q.all.$ref.definition));return}B.jtd||Te(e,t),E.block(()=>{for(let e of q.rules)ee(e);ee(q.post)});function ee(F){(0,g.shouldUseGroup)(D,F)&&(F.type?(E.if((0,S.checkDataType)(F.type,j,B.strictNumbers)),we(e,F),t.length===1&&t[0]===F.type&&s&&(E.else(),(0,S.reportTypeError)(e)),E.endIf()):we(e,F),L||E.if((0,O._)`${k.default.errors} === ${w||0}`))}}function we(e,t){let{gen:s,schema:S,opts:{useDefaults:E}}=e;E&&(0,w.assignDefaults)(e,t.type),s.block(()=>{for(let s of t.rules)(0,g.shouldUseRule)(S,s)&&Ve(e,s.keyword,s.definition,t.type)})}function Te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(De(e,t),e.opts.allowUnionTypes||je(e,t),Me(e,e.dataTypes))}function De(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{Ie(e.dataTypes,t)||ze(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),Re(e,t)}}function je(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ze(e,`use allowUnionTypes to allow union type keyword`)}function Me(e,t){let s=e.self.RULES.all;for(let S in s){let w=s[S];if(typeof w==`object`&&(0,g.shouldUseRule)(e.schema,w)){let{type:s}=w.definition;s.length&&!s.some(e=>Pe(t,e))&&ze(e,`missing type "${s.join(`,`)}" for keyword "${S}"`)}}}function Pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function Ie(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function Re(e,t){let s=[];for(let g of e.dataTypes)Ie(t,g)?s.push(g):t.includes(`integer`)&&g===`number`&&s.push(`integer`);e.dataTypes=s}function ze(e,t){let s=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${s}" (strictTypes)`,(0,F.checkStrictMode)(e,t,e.opts.strictTypes)}var Be=class{constructor(e,t,s){if((0,E.validateKeywordUsage)(e,t,s),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=s,this.data=e.data,this.schema=e.schema[s],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,F.schemaRefOrVal)(e,this.schema,s,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Ge(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,E.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${s} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,k.default.errors))}result(e,t,s){this.failResult((0,O.not)(e),t,s)}failResult(e,t,s){this.gen.if(e),s?s():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,O.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,O._)`${t} !== undefined && (${(0,O.or)(this.invalid$data(),e)})`)}error(e,t,s){if(t){this.setParams(t),this._error(e,s),this.setParams({});return}this._error(e,s)}_error(e,t){(e?L.reportExtraError:L.reportError)(this,this.def.error,t)}$dataError(){(0,L.reportError)(this,this.def.$dataError||L.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,L.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,s=O.nil){this.gen.block(()=>{this.check$data(e,s),t()})}check$data(e=O.nil,t=O.nil){if(!this.$data)return;let{gen:s,schemaCode:g,schemaType:S,def:w}=this;s.if((0,O.or)((0,O._)`${g} === undefined`,t)),e!==O.nil&&s.assign(e,!0),(S.length||w.validateSchema)&&(s.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&s.assign(e,!1)),s.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:s,def:g,it:w}=this;return(0,O.or)(E(),D());function E(){if(s.length){if(!(t instanceof O.Name))throw Error(`ajv implementation error`);let e=Array.isArray(s)?s:[s];return(0,O._)`${(0,S.checkDataTypes)(e,t,w.opts.strictNumbers,S.DataType.Wrong)}`}return O.nil}function D(){if(g.validateSchema){let s=e.scopeValue(`validate$data`,{ref:g.validateSchema});return(0,O._)`!${s}(${t})`}return O.nil}}subschema(e,t){let s=(0,D.getSubschema)(this.it,e);(0,D.extendSubschemaData)(s,this.it,e),(0,D.extendSubschemaMode)(s,e);let g={...this.it,...s,items:void 0,props:void 0};return ne(g,t),g}mergeEvaluated(e,t){let{it:s,gen:g}=this;s.opts.unevaluated&&(s.props!==!0&&e.props!==void 0&&(s.props=F.mergeEvaluated.props(g,e.props,s.props,t)),s.items!==!0&&e.items!==void 0&&(s.items=F.mergeEvaluated.items(g,e.items,s.items,t)))}mergeValidEvaluated(e,t){let{it:s,gen:g}=this;if(s.opts.unevaluated&&(s.props!==!0||s.items!==!0))return g.if(t,()=>this.mergeEvaluated(e,O.Name)),!0}};e.KeywordCxt=Be;function Ve(e,t,s,g){let S=new Be(e,s,t);`code`in s?s.code(S,g):S.$data&&s.validate?(0,E.funcKeywordCode)(S,s):`macro`in s?(0,E.macroKeywordCode)(S,s):(s.compile||s.validate)&&(0,E.funcKeywordCode)(S,s)}let Ue=/^\/(?:[^~]|~0|~1)*$/,We=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ge(e,{dataLevel:t,dataNames:s,dataPathArr:g}){let S,w;if(e===``)return k.default.rootData;if(e[0]===`/`){if(!Ue.test(e))throw Error(`Invalid JSON-pointer: ${e}`);S=e,w=k.default.rootData}else{let E=We.exec(e);if(!E)throw Error(`Invalid JSON-pointer: ${e}`);let D=+E[1];if(S=E[2],S===`#`){if(D>=t)throw Error(j(`property/index`,D));return g[t-D]}if(D>t)throw Error(j(`data`,D));if(w=s[t-D],!S)return w}let E=w,D=S.split(`/`);for(let e of D)e&&(w=(0,O._)`${w}${(0,O.getProperty)((0,F.unescapeJsonPointer)(e))}`,E=(0,O._)`${E} && ${w}`);return E;function j(e,s){return`Cannot access ${e} ${s} levels up, current level is ${t}`}}e.getData=Ge})),require_validation_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),require_ref_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_resolve();e.default=class extends Error{constructor(e,s,g,S){super(S||`can't resolve reference ${g} from id ${s}`),this.missingRef=(0,t.resolveUrl)(e,s,g),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),require_compile=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=require_codegen(),s=require_validation_error(),g=require_names(),S=require_resolve(),w=require_util(),E=require_validate();var D=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let s;typeof e.schema==`object`&&(s=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,S.normalizeId)(s?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=s?.$async,this.refs={}}};e.SchemaEnv=D;function O(e){let w=F.call(this,e);if(w)return w;let D=(0,S.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:O,lines:k}=this.opts.code,{ownProperties:j}=this.opts,L=new t.CodeGen(this.scope,{es5:O,lines:k,ownProperties:j}),B;e.$async&&(B=L.scopeValue(`Error`,{ref:s.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let H=L.scopeName(`validate`);e.validateName=H;let q={gen:L,allErrors:this.opts.allErrors,data:g.default.data,parentData:g.default.parentData,parentDataProperty:g.default.parentDataProperty,dataNames:[g.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:L.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:H,ValidationError:B,schema:e.schema,schemaEnv:e,rootId:D,baseId:e.baseId||D,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},ee;try{this._compilations.add(e),(0,E.validateFunctionCode)(q),L.optimize(this.opts.code.optimize);let s=L.toString();ee=`${L.scopeRefs(g.default.scope)}return ${s}`,this.opts.code.process&&(ee=this.opts.code.process(ee,e));let S=Function(`${g.default.self}`,`${g.default.scope}`,ee)(this,this.scope.get());if(this.scope.value(H,{ref:S}),S.errors=null,S.schema=e.schema,S.schemaEnv=e,e.$async&&(S.$async=!0),this.opts.code.source===!0&&(S.source={validateName:H,validateCode:s,scopeValues:L._values}),this.opts.unevaluated){let{props:e,items:s}=q;S.evaluated={props:e instanceof t.Name?void 0:e,items:s instanceof t.Name?void 0:s,dynamicProps:e instanceof t.Name,dynamicItems:s instanceof t.Name},S.source&&(S.source.evaluated=(0,t.stringify)(S.evaluated))}return e.validate=S,e}catch(t){throw delete e.validate,delete e.validateName,ee&&this.logger.error(`Error compiling schema, function code:`,ee),t}finally{this._compilations.delete(e)}}e.compileSchema=O;function k(e,t,s){var g;s=(0,S.resolveUrl)(this.opts.uriResolver,t,s);let w=e.refs[s];if(w)return w;let E=B.call(this,e,s);if(E===void 0){let g=e.localRefs?.[s],{schemaId:S}=this.opts;g&&(E=new D({schema:g,schemaId:S,root:e,baseId:t}))}if(E!==void 0)return e.refs[s]=j.call(this,E)}e.resolveRef=k;function j(e){return(0,S.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:O.call(this,e)}function F(e){for(let t of this._compilations)if(L(t,e))return t}e.getCompilingSchema=F;function L(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function B(e,t){let s;for(;typeof(s=this.refs[t])==`string`;)t=s;return s||this.schemas[t]||H.call(this,e,t)}function H(e,t){let s=this.opts.uriResolver.parse(t),g=(0,S._getFullPath)(this.opts.uriResolver,s),w=(0,S.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&g===w)return ee.call(this,s,e);let E=(0,S.normalizeId)(g),k=this.refs[E]||this.schemas[E];if(typeof k==`string`){let t=H.call(this,e,k);return typeof t?.schema==`object`?ee.call(this,s,t):void 0}if(typeof k?.schema==`object`){if(k.validate||O.call(this,k),E===(0,S.normalizeId)(t)){let{schema:t}=k,{schemaId:s}=this.opts,g=t[s];return g&&(w=(0,S.resolveUrl)(this.opts.uriResolver,w,g)),new D({schema:t,schemaId:s,root:e,baseId:w})}return ee.call(this,s,k)}}e.resolveSchema=H;let q=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function ee(e,{baseId:t,schema:s,root:g}){var E;if(e.fragment?.[0]!==`/`)return;for(let g of e.fragment.slice(1).split(`/`)){if(typeof s==`boolean`)return;let e=s[(0,w.unescapeFragment)(g)];if(e===void 0)return;s=e;let E=typeof s==`object`&&s[this.opts.schemaId];!q.has(g)&&E&&(t=(0,S.resolveUrl)(this.opts.uriResolver,t,E))}let O;if(typeof s!=`boolean`&&s.$ref&&!(0,w.schemaHasRulesButRef)(s,this.RULES)){let e=(0,S.resolveUrl)(this.opts.uriResolver,t,s.$ref);O=H.call(this,g,e)}let{schemaId:k}=this.opts;if(O||=new D({schema:s,schemaId:k,root:g,baseId:t}),O.schema!==O.root.schema)return O}})),require_data=__commonJSMin$2(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),require_utils$1=__commonJSMin$2(((e,t)=>{let s=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),g=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function S(e){let t=``,s=0,g=0;for(g=0;g<e.length;g++)if(s=e[g].charCodeAt(0),s!==48){if(!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g];break}for(g+=1;g<e.length;g++){if(s=e[g].charCodeAt(0),!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g]}return t}let w=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function E(e){return e.length=0,!0}function D(e,t,s){if(e.length){let g=S(e);if(g!==``)t.push(g);else return s.error=!0,!1;e.length=0}return!0}function O(e){let t=0,s={error:!1,address:``,zone:``},g=[],w=[],O=!1,k=!1,j=D;for(let S=0;S<e.length;S++){let D=e[S];if(!(D===`[`||D===`]`))if(D===`:`){if(O===!0&&(k=!0),!j(w,g,s))break;if(++t>7){s.error=!0;break}S>0&&e[S-1]===`:`&&(O=!0),g.push(`:`);continue}else if(D===`%`){if(!j(w,g,s))break;j=E}else{w.push(D);continue}}return w.length&&(j===E?s.zone=w.join(``):k?g.push(w.join(``)):g.push(S(w))),s.address=g.join(``),s}function k(e){if(j(e,`:`)<2)return{host:e,isIPV6:!1};let t=O(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,s=t.address;return t.zone&&(e+=`%`+t.zone,s+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:s}}}function j(e,t){let s=0;for(let g=0;g<e.length;g++)e[g]===t&&s++;return s}function F(e){let t=e,s=[],g=-1,S=0;for(;S=t.length;){if(S===1){if(t===`.`)break;if(t===`/`){s.push(`/`);break}else{s.push(t);break}}else if(S===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){s.push(`/`);break}}else if(S===3&&t===`/..`){s.length!==0&&s.pop(),s.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),s.length!==0&&s.pop();continue}}if((g=t.indexOf(`/`,1))===-1){s.push(t);break}else s.push(t.slice(0,g)),t=t.slice(g)}return s.join(``)}function L(e,t){let s=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=s(e.scheme)),e.userinfo!==void 0&&(e.userinfo=s(e.userinfo)),e.host!==void 0&&(e.host=s(e.host)),e.path!==void 0&&(e.path=s(e.path)),e.query!==void 0&&(e.query=s(e.query)),e.fragment!==void 0&&(e.fragment=s(e.fragment)),e}function B(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let s=unescape(e.host);if(!g(s)){let t=k(s);s=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(s)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:w,recomposeAuthority:B,normalizeComponentEncoding:L,removeDotSegments:F,isIPv4:g,isUUID:s,normalizeIPv6:k,stringArrayToHexStripped:S}})),require_schemes=__commonJSMin$2(((e,t)=>{let{isUUID:s}=require_utils$1(),g=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function w(e){return S.indexOf(e)!==-1}function E(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function D(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function O(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function k(e){return e.secure=E(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function j(e){if((e.port===(E(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,s]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=s,e.resourceName=void 0}return e.fragment=void 0,e}function F(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let s=e.path.match(g);if(s){let g=t.scheme||e.scheme||`urn`;e.nid=s[1].toLowerCase(),e.nss=s[2];let S=oe(`${g}:${t.nid||e.nid}`);e.path=void 0,S&&(e=S.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function L(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let s=t.scheme||e.scheme||`urn`,g=e.nid.toLowerCase(),S=oe(`${s}:${t.nid||g}`);S&&(e=S.serialize(e,t));let w=e,E=e.nss;return w.path=`${g||t.nid}:${E}`,t.skipEscape=!0,w}function B(e,t){let g=e;return g.uuid=g.nss,g.nss=void 0,!t.tolerant&&(!g.uuid||!s(g.uuid))&&(g.error=g.error||`UUID is not valid.`),g}function H(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let q={scheme:`http`,domainHost:!0,parse:D,serialize:O},ee={scheme:`https`,domainHost:q.domainHost,parse:D,serialize:O},J={scheme:`ws`,domainHost:!0,parse:k,serialize:j},Y={scheme:`wss`,domainHost:J.domainHost,parse:J.parse,serialize:J.serialize},te={scheme:`urn`,parse:F,serialize:L,skipNormalize:!0},ne={scheme:`urn:uuid`,parse:B,serialize:H,skipNormalize:!0},ae={http:q,https:ee,ws:J,wss:Y,urn:te,"urn:uuid":ne};Object.setPrototypeOf(ae,null);function oe(e){return e&&(ae[e]||ae[e.toLowerCase()])||void 0}t.exports={wsIsSecure:E,SCHEMES:ae,isValidSchemeName:w,getSchemeHandler:oe}})),require_fast_uri=__commonJSMin$2(((e,t)=>{let{normalizeIPv6:s,removeDotSegments:g,recomposeAuthority:S,normalizeComponentEncoding:w,isIPv4:E,nonSimpleDomain:D}=require_utils$1(),{SCHEMES:O,getSchemeHandler:k}=require_schemes();function j(e,t){return typeof e==`string`?e=H(ee(e,t),t):typeof e==`object`&&(e=ee(H(e,t),t)),e}function F(e,t,s){let g=s?Object.assign({scheme:`null`},s):{scheme:`null`},S=L(ee(e,g),ee(t,g),g,!0);return g.skipEscape=!0,H(S,g)}function L(e,t,s,S){let w={};return S||(e=ee(H(e,s),s),t=ee(H(t,s),s)),s||={},!s.tolerant&&t.scheme?(w.scheme=t.scheme,w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.path?(t.path[0]===`/`?w.path=g(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?w.path=`/`+t.path:e.path?w.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:w.path=t.path,w.path=g(w.path)),w.query=t.query):(w.path=e.path,t.query===void 0?w.query=e.query:w.query=t.query),w.userinfo=e.userinfo,w.host=e.host,w.port=e.port),w.scheme=e.scheme),w.fragment=t.fragment,w}function B(e,t,s){return typeof e==`string`?(e=unescape(e),e=H(w(ee(e,s),!0),{...s,skipEscape:!0})):typeof e==`object`&&(e=H(w(e,!0),{...s,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=H(w(ee(t,s),!0),{...s,skipEscape:!0})):typeof t==`object`&&(t=H(w(t,!0),{...s,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function H(e,t){let s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},w=Object.assign({},t),E=[],D=k(w.scheme||s.scheme);D&&D.serialize&&D.serialize(s,w),s.path!==void 0&&(w.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),s.scheme!==void 0&&(s.path=s.path.split(`%3A`).join(`:`)))),w.reference!==`suffix`&&s.scheme&&E.push(s.scheme,`:`);let O=S(s);if(O!==void 0&&(w.reference!==`suffix`&&E.push(`//`),E.push(O),s.path&&s.path[0]!==`/`&&E.push(`/`)),s.path!==void 0){let e=s.path;!w.absolutePath&&(!D||!D.absolutePath)&&(e=g(e)),O===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),E.push(e)}return s.query!==void 0&&E.push(`?`,s.query),s.fragment!==void 0&&E.push(`#`,s.fragment),E.join(``)}let q=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ee(e,t){let g=Object.assign({},t),S={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},w=!1;g.reference===`suffix`&&(e=g.scheme?g.scheme+`:`+e:`//`+e);let O=e.match(q);if(O){if(S.scheme=O[1],S.userinfo=O[3],S.host=O[4],S.port=parseInt(O[5],10),S.path=O[6]||``,S.query=O[7],S.fragment=O[8],isNaN(S.port)&&(S.port=O[5]),S.host)if(E(S.host)===!1){let e=s(S.host);S.host=e.host.toLowerCase(),w=e.isIPV6}else w=!0;S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&S.query===void 0&&!S.path?S.reference=`same-document`:S.scheme===void 0?S.reference=`relative`:S.fragment===void 0?S.reference=`absolute`:S.reference=`uri`,g.reference&&g.reference!==`suffix`&&g.reference!==S.reference&&(S.error=S.error||`URI is not a `+g.reference+` reference.`);let t=k(g.scheme||S.scheme);if(!g.unicodeSupport&&(!t||!t.unicodeSupport)&&S.host&&(g.domainHost||t&&t.domainHost)&&w===!1&&D(S.host))try{S.host=URL.domainToASCII(S.host.toLowerCase())}catch(e){S.error=S.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(S.scheme!==void 0&&(S.scheme=unescape(S.scheme)),S.host!==void 0&&(S.host=unescape(S.host))),S.path&&=escape(unescape(S.path)),S.fragment&&=encodeURI(decodeURIComponent(S.fragment))),t&&t.parse&&t.parse(S,g)}else S.error=S.error||`URI can not be parsed.`;return S}let J={SCHEMES:O,normalize:j,resolve:F,resolveComponent:L,equal:B,serialize:H,parse:ee};t.exports=J,t.exports.default=J,t.exports.fastUri=J})),require_uri=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_uri();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),require_core$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var s=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return s._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return s.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return s.CodeGen}});let g=require_validation_error(),S=require_ref_error(),w=require_rules(),E=require_compile(),D=require_codegen(),O=require_resolve(),k=require_dataType(),j=require_util(),F=require_data(),L=require_uri(),B=(e,t)=>new RegExp(e,t);B.code=`new RegExp`;let H=[`removeAdditional`,`useDefaults`,`coerceTypes`],q=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),ee={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},J={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},Y=200;function te(e){var t,s,g,S,w,E,D,O,k,j,F,H,q,ee,J,Y,te,ne,ae,oe,se,ce,ue,de,fe;let me=e.strict,ge=e.code?.optimize,_e=ge===!0||ge===void 0?1:ge||0,ve=e.code?.regExp??B,ye=e.uriResolver??L.default;return{strictSchema:e.strictSchema??me??!0,strictNumbers:e.strictNumbers??me??!0,strictTypes:e.strictTypes??me??`log`,strictTuples:e.strictTuples??me??`log`,strictRequired:e.strictRequired??me??!1,code:e.code?{...e.code,optimize:_e,regExp:ve}:{optimize:_e,regExp:ve},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:ye}}var ne=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...te(e)};let{es5:t,lines:s}=this.opts.code;this.scope=new D.ValueScope({scope:{},prefixes:q,es5:t,lines:s}),this.logger=me(e.logger);let g=e.validateFormats;e.validateFormats=!1,this.RULES=(0,w.getRules)(),ae.call(this,ee,e,`NOT SUPPORTED`),ae.call(this,J,e,`DEPRECATED`,`warn`),this._metaOpts=de.call(this),e.formats&&ce.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ue.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),se.call(this),e.validateFormats=g}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:s}=this.opts,g=F;s===`id`&&(g={...F},g.id=g.$id,delete g.$id),t&&e&&this.addMetaSchema(g,g[s],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let s;if(typeof e==`string`){if(s=this.getSchema(e),!s)throw Error(`no schema with key or ref "${e}"`)}else s=this.compile(e);let g=s(t);return`$async`in s||(this.errors=s.errors),g}compile(e,t){let s=this._addSchema(e,t);return s.validate||this._compileSchemaEnv(s)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:s}=this.opts;return g.call(this,e,t);async function g(e,t){await w.call(this,e.$schema);let s=this._addSchema(e,t);return s.validate||E.call(this,s)}async function w(e){e&&!this.getSchema(e)&&await g.call(this,{$ref:e},!0)}async function E(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof S.default))throw t;return D.call(this,t),await O.call(this,t.missingSchema),E.call(this,e)}}function D({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function O(e){let s=await k.call(this,e);this.refs[e]||await w.call(this,s.$schema),this.refs[e]||this.addSchema(s,e,t)}async function k(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=s(e))}finally{delete this._loading[e]}}}addSchema(e,t,s,g=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,s,g);return this}let S;if(typeof e==`object`){let{schemaId:t}=this.opts;if(S=e[t],S!==void 0&&typeof S!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,O.normalizeId)(t||S),this._checkUnique(t),this.schemas[t]=this._addSchema(e,s,t,g,!0),this}addMetaSchema(e,t,s=this.opts.validateSchema){return this.addSchema(e,t,!0,s),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let s;if(s=e.$schema,s!==void 0&&typeof s!=`string`)throw Error(`$schema must be a string`);if(s=s||this.opts.defaultMeta||this.defaultMeta(),!s)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let g=this.validate(s,e);if(!g&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return g}getSchema(e){let t;for(;typeof(t=oe.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:s}=this.opts,g=new E.SchemaEnv({schema:{},schemaId:s});if(t=E.resolveSchema.call(this,g,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=oe.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let s=e[this.opts.schemaId];return s&&(s=(0,O.normalizeId)(s),delete this.schemas[s],delete this.refs[s]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let s;if(typeof e==`string`)s=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=s);else if(typeof e==`object`&&t===void 0){if(t=e,s=t.keyword,Array.isArray(s)&&!s.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(_e.call(this,s,t),!t)return(0,j.eachItem)(s,e=>ve.call(this,e)),this;Ce.call(this,t);let g={...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)};return(0,j.eachItem)(s,g.type.length===0?e=>ve.call(this,e,g):e=>g.type.forEach(t=>ve.call(this,e,g,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let s of t.rules){let t=s.rules.findIndex(t=>t.keyword===e);t>=0&&s.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:s=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${s}${e.instancePath} ${e.message}`).reduce((e,s)=>e+t+s)}$dataMetaSchema(e,t){let s=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let g of t){let t=g.split(`/`).slice(1),S=e;for(let e of t)S=S[e];for(let e in s){let t=s[e];if(typeof t!=`object`)continue;let{$data:g}=t.definition,w=S[e];g&&w&&(S[e]=Te(w))}}return e}_removeAllSchemas(e,t){for(let s in e){let g=e[s];(!t||t.test(s))&&(typeof g==`string`?delete e[s]:g&&!g.meta&&(this._cache.delete(g.schema),delete e[s]))}}_addSchema(e,t,s,g=this.opts.validateSchema,S=this.opts.addUsedSchema){let w,{schemaId:D}=this.opts;if(typeof e==`object`)w=e[D];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let k=this._cache.get(e);if(k!==void 0)return k;s=(0,O.normalizeId)(w||s);let j=O.getSchemaRefs.call(this,e,s);return k=new E.SchemaEnv({schema:e,schemaId:D,meta:t,baseId:s,localRefs:j}),this._cache.set(k.schema,k),S&&!s.startsWith(`#`)&&(s&&this._checkUnique(s),this.refs[s]=k),g&&this.validateSchema(e,!0),k}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):E.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{E.compileSchema.call(this,e)}finally{this.opts=t}}};ne.ValidationError=g.default,ne.MissingRefError=S.default,e.default=ne;function ae(e,t,s,g=`error`){for(let S in e){let w=S;w in t&&this.logger[g](`${s}: option ${S}. ${e[w]}`)}}function oe(e){return e=(0,O.normalizeId)(e),this.schemas[e]||this.refs[e]}function se(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ce(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ue(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let s=e[t];s.keyword||=t,this.addKeyword(s)}}function de(){let e={...this.opts};for(let t of H)delete e[t];return e}let fe={log(){},warn(){},error(){}};function me(e){if(e===!1)return fe;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ge=/^[a-z_$][a-z0-9_$:-]*$/i;function _e(e,t){let{RULES:s}=this;if((0,j.eachItem)(e,e=>{if(s.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ge.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ve(e,t,s){var g;let S=t?.post;if(s&&S)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:w}=this,E=S?w.post:w.rules.find(({type:e})=>e===s);if(E||(E={type:s,rules:[]},w.rules.push(E)),w.keywords[e]=!0,!t)return;let D={keyword:e,definition:{...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)}};t.before?ye.call(this,E,D,t.before):E.rules.push(D),w.all[e]=D,(g=t.implements)==null||g.forEach(e=>this.addKeyword(e))}function ye(e,t,s){let g=e.rules.findIndex(e=>e.keyword===s);g>=0?e.rules.splice(g,0,t):(e.rules.push(t),this.logger.warn(`rule ${s} is not defined`))}function Ce(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Te(t)),e.validateSchema=this.compile(t,!0))}let we={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function Te(e){return{anyOf:[e,we]}}})),require_id=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),require_ref=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=require_ref_error(),s=require_code(),g=require_codegen(),S=require_names(),w=require_compile(),E=require_util(),D={keyword:`$ref`,schemaType:`string`,code(e){let{gen:s,schema:S,it:E}=e,{baseId:D,schemaEnv:j,validateName:F,opts:L,self:B}=E,{root:H}=j;if((S===`#`||S===`#/`)&&D===H.baseId)return ee();let q=w.resolveRef.call(B,H,D,S);if(q===void 0)throw new t.default(E.opts.uriResolver,D,S);if(q instanceof w.SchemaEnv)return J(q);return Y(q);function ee(){if(j===H)return k(e,F,j,j.$async);let t=s.scopeValue(`root`,{ref:H});return k(e,(0,g._)`${t}.validate`,H,H.$async)}function J(t){k(e,O(e,t),t,t.$async)}function Y(t){let w=s.scopeValue(`schema`,L.code.source===!0?{ref:t,code:(0,g.stringify)(t)}:{ref:t}),E=s.name(`valid`),D=e.subschema({schema:t,dataTypes:[],schemaPath:g.nil,topSchemaRef:w,errSchemaPath:S},E);e.mergeEvaluated(D),e.ok(E)}}};function O(e,t){let{gen:s}=e;return t.validate?s.scopeValue(`validate`,{ref:t.validate}):(0,g._)`${s.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=O;function k(e,t,w,D){let{gen:O,it:k}=e,{allErrors:j,schemaEnv:F,opts:L}=k,B=L.passContext?S.default.this:g.nil;D?H():q();function H(){if(!F.$async)throw Error(`async schema referenced by sync schema`);let S=O.let(`valid`);O.try(()=>{O.code((0,g._)`await ${(0,s.callValidateCode)(e,t,B)}`),J(t),j||O.assign(S,!0)},e=>{O.if((0,g._)`!(${e} instanceof ${k.ValidationError})`,()=>O.throw(e)),ee(e),j||O.assign(S,!1)}),e.ok(S)}function q(){e.result((0,s.callValidateCode)(e,t,B),()=>J(t),()=>ee(t))}function ee(e){let t=(0,g._)`${e}.errors`;O.assign(S.default.vErrors,(0,g._)`${S.default.vErrors} === null ? ${t} : ${S.default.vErrors}.concat(${t})`),O.assign(S.default.errors,(0,g._)`${S.default.vErrors}.length`)}function J(e){var t;if(!k.opts.unevaluated)return;let s=w?.validate?.evaluated;if(k.props!==!0)if(s&&!s.dynamicProps)s.props!==void 0&&(k.props=E.mergeEvaluated.props(O,s.props,k.props));else{let t=O.var(`props`,(0,g._)`${e}.evaluated.props`);k.props=E.mergeEvaluated.props(O,t,k.props,g.Name)}if(k.items!==!0)if(s&&!s.dynamicItems)s.items!==void 0&&(k.items=E.mergeEvaluated.items(O,s.items,k.items));else{let t=O.var(`items`,(0,g._)`${e}.evaluated.items`);k.items=E.mergeEvaluated.items(O,t,k.items,g.Name)}}}e.callRef=k,e.default=D})),require_core=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_id(),s=require_ref();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,s.default]})),require_limitNumber=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=t.operators,g={maximum:{okStr:`<=`,ok:s.LTE,fail:s.GT},minimum:{okStr:`>=`,ok:s.GTE,fail:s.LT},exclusiveMaximum:{okStr:`<`,ok:s.LT,fail:s.GTE},exclusiveMinimum:{okStr:`>`,ok:s.GT,fail:s.LTE}};e.default={keyword:Object.keys(g),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:s})=>(0,t.str)`must be ${g[e].okStr} ${s}`,params:({keyword:e,schemaCode:s})=>(0,t._)`{comparison: ${g[e].okStr}, limit: ${s}}`},code(e){let{keyword:s,data:S,schemaCode:w}=e;e.fail$data((0,t._)`${S} ${g[s].fail} ${w} || isNaN(${S})`)}}})),require_multipleOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:s,data:g,schemaCode:S,it:w}=e,E=w.opts.multipleOfPrecision,D=s.let(`res`),O=E?(0,t._)`Math.abs(Math.round(${D}) - ${D}) > 1e-${E}`:(0,t._)`${D} !== parseInt(${D})`;e.fail$data((0,t._)`(${S} === 0 || (${D} = ${g}/${S}, ${O}))`)}}})),require_ucs2length=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,s=0,g=0,S;for(;g<t;)s++,S=e.charCodeAt(g++),S>=55296&&S<=56319&&g<t&&(S=e.charCodeAt(g),(S&64512)==56320&&g++);return s}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),require_limitLength=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_ucs2length();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:S,data:w,schemaCode:E,it:D}=e,O=S===`maxLength`?t.operators.GT:t.operators.LT,k=D.opts.unicode===!1?(0,t._)`${w}.length`:(0,t._)`${(0,s.useFunc)(e.gen,g.default)}(${w})`;e.fail$data((0,t._)`${k} ${O} ${E}`)}}})),require_pattern=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_util(),g=require_codegen();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,g.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,g._)`{pattern: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e,j=k.opts.unicodeRegExp?`u`:``;if(E){let{regExp:t}=k.opts.code,E=t.code===`new RegExp`?(0,g._)`new RegExp`:(0,s.useFunc)(S,t),D=S.let(`valid`);S.try(()=>S.assign(D,(0,g._)`${E}(${O}, ${j}).test(${w})`),()=>S.assign(D,!1)),e.fail$data((0,g._)`!${D}`)}else{let s=(0,t.usePattern)(e,D);e.fail$data((0,g._)`!${s}.test(${w})`)}}}})),require_limitProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${g}).length ${w} ${S}`)}}})),require_required=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,s.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,s._)`{missingProperty: ${e}}`},code(e){let{gen:S,schema:w,schemaCode:E,data:D,$data:O,it:k}=e,{opts:j}=k;if(!O&&w.length===0)return;let F=w.length>=j.loopRequired;if(k.allErrors?L():B(),j.strictRequired){let t=e.parentSchema.properties,{definedProperties:s}=e.it;for(let e of w)if(t?.[e]===void 0&&!s.has(e)){let t=`required property "${e}" is not defined at "${k.schemaEnv.baseId+k.errSchemaPath}" (strictRequired)`;(0,g.checkStrictMode)(k,t,k.opts.strictRequired)}}function L(){if(F||O)e.block$data(s.nil,H);else for(let s of w)(0,t.checkReportMissingProp)(e,s)}function B(){let s=S.let(`missing`);if(F||O){let t=S.let(`valid`,!0);e.block$data(t,()=>q(s,t)),e.ok(t)}else S.if((0,t.checkMissingProp)(e,w,s)),(0,t.reportMissingProp)(e,s),S.else()}function H(){S.forOf(`prop`,E,s=>{e.setParams({missingProperty:s}),S.if((0,t.noPropertyInData)(S,D,s,j.ownProperties),()=>e.error())})}function q(g,w){e.setParams({missingProperty:g}),S.forOf(g,E,()=>{S.assign(w,(0,t.propertyInData)(S,D,g,j.ownProperties)),S.if((0,s.not)(w),()=>{e.error(),S.break()})},s.nil)}}}})),require_limitItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${g}.length ${w} ${S}`)}}})),require_equal=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_deep_equal();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),require_uniqueItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_dataType(),s=require_codegen(),g=require_util(),S=require_equal();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,s.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,s._)`{i: ${e}, j: ${t}}`},code(e){let{gen:w,data:E,$data:D,schema:O,parentSchema:k,schemaCode:j,it:F}=e;if(!D&&!O)return;let L=w.let(`valid`),B=k.items?(0,t.getSchemaTypes)(k.items):[];e.block$data(L,H,(0,s._)`${j} === false`),e.ok(L);function H(){let t=w.let(`i`,(0,s._)`${E}.length`),g=w.let(`j`);e.setParams({i:t,j:g}),w.assign(L,!0),w.if((0,s._)`${t} > 1`,()=>(q()?ee:J)(t,g))}function q(){return B.length>0&&!B.some(e=>e===`object`||e===`array`)}function ee(g,S){let D=w.name(`item`),O=(0,t.checkDataTypes)(B,D,F.opts.strictNumbers,t.DataType.Wrong),k=w.const(`indices`,(0,s._)`{}`);w.for((0,s._)`;${g}--;`,()=>{w.let(D,(0,s._)`${E}[${g}]`),w.if(O,(0,s._)`continue`),B.length>1&&w.if((0,s._)`typeof ${D} == "string"`,(0,s._)`${D} += "_"`),w.if((0,s._)`typeof ${k}[${D}] == "number"`,()=>{w.assign(S,(0,s._)`${k}[${D}]`),e.error(),w.assign(L,!1).break()}).code((0,s._)`${k}[${D}] = ${g}`)})}function J(t,D){let O=(0,g.useFunc)(w,S.default),k=w.name(`outer`);w.label(k).for((0,s._)`;${t}--;`,()=>w.for((0,s._)`${D} = ${t}; ${D}--;`,()=>w.if((0,s._)`${O}(${E}[${t}], ${E}[${D}])`,()=>{e.error(),w.assign(L,!1).break(k)})))}}}})),require_const=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:S,data:w,$data:E,schemaCode:D,schema:O}=e;E||O&&typeof O==`object`?e.fail$data((0,t._)`!${(0,s.useFunc)(S,g.default)}(${w}, ${D})`):e.fail((0,t._)`${O} !== ${w}`)}}})),require_enum=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e;if(!E&&D.length===0)throw Error(`enum must have non-empty array`);let j=D.length>=k.opts.loopEnum,F,L=()=>F??=(0,s.useFunc)(S,g.default),B;if(j||E)B=S.let(`valid`),e.block$data(B,H);else{if(!Array.isArray(D))throw Error(`ajv implementation error`);let e=S.const(`vSchema`,O);B=(0,t.or)(...D.map((t,s)=>q(e,s)))}e.pass(B);function H(){S.assign(B,!1),S.forOf(`v`,O,e=>S.if((0,t._)`${L()}(${w}, ${e})`,()=>S.assign(B,!0).break()))}function q(e,s){let g=D[s];return typeof g==`object`&&g?(0,t._)`${L()}(${w}, ${e}[${s}])`:(0,t._)`${w} === ${g}`}}}})),require_validation$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_limitNumber(),s=require_multipleOf(),g=require_limitLength(),S=require_pattern(),w=require_limitProperties(),E=require_required(),D=require_limitItems(),O=require_uniqueItems(),k=require_const(),j=require_enum();e.default=[t.default,s.default,g.default,S.default,w.default,E.default,D.default,O.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},k.default,j.default]})),require_additionalItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=require_codegen(),s=require_util(),g={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:g}=e,{items:w}=t;if(!Array.isArray(w)){(0,s.checkStrictMode)(g,`"additionalItems" is ignored when "items" is not an array of schemas`);return}S(e,w)}};function S(e,g){let{gen:S,schema:w,data:E,keyword:D,it:O}=e;O.items=!0;let k=S.const(`len`,(0,t._)`${E}.length`);if(w===!1)e.setParams({len:g.length}),e.pass((0,t._)`${k} <= ${g.length}`);else if(typeof w==`object`&&!(0,s.alwaysValidSchema)(O,w)){let s=S.var(`valid`,(0,t._)`${k} <= ${g.length}`);S.if((0,t.not)(s),()=>j(s)),e.ok(s)}function j(w){S.forRange(`i`,g.length,k,g=>{e.subschema({keyword:D,dataProp:g,dataPropType:s.Type.Num},w),O.allErrors||S.if((0,t.not)(w),()=>S.break())})}}e.validateAdditionalItems=S,e.default=g})),require_items=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=require_codegen(),s=require_util(),g=require_code(),S={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:S}=e;if(Array.isArray(t))return w(e,`additionalItems`,t);S.items=!0,!(0,s.alwaysValidSchema)(S,t)&&e.ok((0,g.validateArray)(e))}};function w(e,g,S=e.schema){let{gen:w,parentSchema:E,data:D,keyword:O,it:k}=e;L(E),k.opts.unevaluated&&S.length&&k.items!==!0&&(k.items=s.mergeEvaluated.items(w,S.length,k.items));let j=w.name(`valid`),F=w.const(`len`,(0,t._)`${D}.length`);S.forEach((g,S)=>{(0,s.alwaysValidSchema)(k,g)||(w.if((0,t._)`${F} > ${S}`,()=>e.subschema({keyword:O,schemaProp:S,dataProp:S},j)),e.ok(j))});function L(e){let{opts:t,errSchemaPath:w}=k,E=S.length,D=E===e.minItems&&(E===e.maxItems||e[g]===!1);if(t.strictTuples&&!D){let e=`"${O}" is ${E}-tuple, but minItems or maxItems/${g} are not specified or different at path "${w}"`;(0,s.checkStrictMode)(k,e,t.strictTuples)}}}e.validateTuple=w,e.default=S})),require_prefixItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_items();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),require_items2020=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_code(),S=require_additionalItems();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:w,it:E}=e,{prefixItems:D}=w;E.items=!0,!(0,s.alwaysValidSchema)(E,t)&&(D?(0,S.validateAdditionalItems)(e,D):e.ok((0,g.validateArray)(e)))}}})),require_contains=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:s}})=>s===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${s} valid item(s)`,params:({params:{min:e,max:s}})=>s===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${s}}`},code(e){let{gen:g,schema:S,parentSchema:w,data:E,it:D}=e,O,k,{minContains:j,maxContains:F}=w;D.opts.next?(O=j===void 0?1:j,k=F):O=1;let L=g.const(`len`,(0,t._)`${E}.length`);if(e.setParams({min:O,max:k}),k===void 0&&O===0){(0,s.checkStrictMode)(D,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(k!==void 0&&O>k){(0,s.checkStrictMode)(D,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,s.alwaysValidSchema)(D,S)){let s=(0,t._)`${L} >= ${O}`;k!==void 0&&(s=(0,t._)`${s} && ${L} <= ${k}`),e.pass(s);return}D.items=!0;let B=g.name(`valid`);k===void 0&&O===1?q(B,()=>g.if(B,()=>g.break())):O===0?(g.let(B,!0),k!==void 0&&g.if((0,t._)`${E}.length > 0`,H)):(g.let(B,!1),H()),e.result(B,()=>e.reset());function H(){let e=g.name(`_valid`),t=g.let(`count`,0);q(e,()=>g.if(e,()=>ee(t)))}function q(t,S){g.forRange(`i`,0,L,g=>{e.subschema({keyword:`contains`,dataProp:g,dataPropType:s.Type.Num,compositeRule:!0},t),S()})}function ee(e){g.code((0,t._)`${e}++`),k===void 0?g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0).break()):(g.if((0,t._)`${e} > ${k}`,()=>g.assign(B,!1).break()),O===1?g.assign(B,!0):g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0)))}}}})),require_dependencies=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=require_codegen(),s=require_util(),g=require_code();e.error={message:({params:{property:e,depsCount:s,deps:g}})=>{let S=s===1?`property`:`properties`;return(0,t.str)`must have ${S} ${g} when property ${e} is present`},params:({params:{property:e,depsCount:s,deps:g,missingProperty:S}})=>(0,t._)`{property: ${e},
|
|
48
48
|
missingProperty: ${S},
|
|
49
49
|
depsCount: ${s},
|
|
50
|
-
deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Crypto);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
|
|
50
|
+
deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=crypto$2);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
|
|
51
51
|
`;return g&&(S+=`id: ${g}\n`),S+=`data: ${JSON.stringify(s)}\n\n`,e.enqueue(t.encode(S)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let s=e.headers.get(`accept`);if(!s?.includes(`application/json`)||!s.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let g=e.headers.get(`content-type`);if(!g||!g.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let S={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},w;if(t?.parsedBody!==void 0)w=t.parsedBody;else try{w=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let E;try{E=Array.isArray(w)?w.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(w)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let D=E.some(isInitializeRequest);if(D){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(E.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!D){let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s}if(!E.some(isJSONRPCRequest)){for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S});return new Response(null,{status:202})}let O=crypto.randomUUID(),k=E.find(e=>isInitializeRequest(e)),j=k?k.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(O,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(O)}});for(let e of E)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,O);for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S})});let F=new TextEncoder,L,B=new ReadableStream({start:e=>{L=e},cancel:()=>{this._streamMapping.delete(O)}}),H={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(H[`mcp-session-id`]=this.sessionId);for(let e of E)isJSONRPCRequest(e)&&(this._streamMapping.set(O,{controller:L,encoder:F,cleanup:()=>{this._streamMapping.delete(O);try{L.close()}catch{}}}),this._requestToStreamMapping.set(e.id,O));await this.writePrimingEvent(L,F,O,j);for(let e of E){let s,g;isJSONRPCRequest(e)&&this._eventStore&&j>=`2025-11-25`&&(s=()=>{this.closeSSEStream(e.id)},g=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S,closeSSEStream:s,closeStandaloneSSEStream:g})}return new Response(B,{status:200,headers:H})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let s=this._streamMapping.get(t);s&&s.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let s=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(s=e.id),s===void 0){if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,e,t);return}let g=this._requestToStreamMapping.get(s);if(!g)throw Error(`No connection established for request ID: ${String(s)}`);let S=this._streamMapping.get(g);if(!this._enableJsonResponse&&S?.controller&&S?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(g,e)),this.writeSSEEvent(S.controller,S.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(s,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===g).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!S)throw Error(`No connection established for request ID: ${String(s)}`);if(this._enableJsonResponse&&S.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let s=t.map(e=>this._requestResponseMap.get(e));s.length===1?S.resolveJson(new Response(JSON.stringify(s[0]),{status:200,headers:e})):S.resolveJson(new Response(JSON.stringify(s),{status:200,headers:e}))}else S.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},StreamableHTTPServerTransport=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new WebStandardStreamableHTTPServerTransport(e),this._requestListener=getRequestListener(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,s){let g=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:g,parsedBody:s}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}},Ye=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-B99ElfBo.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-Cqi4_PjZ.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-2Mks7IIT.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-CNZ_hN8P.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-Bl16kSBR.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-CFMuhNvO.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-DGiKr2c0.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-F9g7gQHU.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-VqiK1WcH.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-D9pw6nb9.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-Byit-TLI.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-C_dD-tNl.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-m5fzqroZ.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BMheCA1U.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DSAed845.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-knoYRbXD.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-Bof613yN.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DOG39Ce5.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-ViKChHv5.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-BfHBQ11q.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-6Q9HKhoL.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-DqMg1dll.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CiXMC2Qh.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-CTh1BUfn.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-BDAM8WY8.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C8EyimeA.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BDNDgux2.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-4azlKYu4.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-Bs_nMrMg.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Bx5XDGgK.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Bp3M0RnL.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BWFllY1p.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-l9kho9ff.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-DqhMcIGL.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-Bg1ZsVDm.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-BMnXfCXQ.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BgHEibOy.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-ZPOxwUwf.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-GWPOMupJ.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-VsUIxZwx.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-BK2c44-E.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Cq3dzRFU.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-BwBOMO5i.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CdKFilDT.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-C4DTv-gF.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-D3tmTL1R.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-bqN_UBX0.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DSY9AfjL.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-nDqDn5ZQ.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-BgSOeH2N.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-aaC7r4sX.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CXWA3kJ0.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BaUQfYSh.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-DrJUreFq.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-pTX2tfQd.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-NRAU83Yg.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-Cfe-w5CY.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-D07ChhI1.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-D7XdAo13.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-DCBusWam.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-DfnqWxtA.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-DMDGVNTy.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-_qJ9gN13.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-DhtD1OhF.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DwpkPMHp.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-Db9qg5B2.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-BXyMiYfX.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-I8yansvE.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-DNmhrHQv.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-B7_jrPM3.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-B7_jrPM3.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-ZESSNIAK.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-ZESSNIAK.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-ClMENMWY.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,s){let g=tn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-QT4N2Z44-BlPYKPtd.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function rn(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Gt)}function nn(){return sn.map(Gt)}function on(){return Zt.map(Gt)}function an(){return qt.map(Gt)}function ln(e){return`load`in e&&typeof e.load==`function`}function cn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,g){return t||=await e.load(),t.execute(s,g)}}}var ot=new TextEncoder;function Qi(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Le=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,s]of Object.entries(e))typeof s==`function`?this.writeFileLazy(t,s):Qi(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=m$1(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,s,g){h$1(e,`write`);let S=c$1(e);this.ensureParentDirs(S);let w=o(t,l$1(s));this.data.set(S,{type:`file`,content:w,mode:g?.mode??420,mtime:g?.mtime??new Date})}writeFileLazy(e,t,s){h$1(e,`write`);let g=c$1(e);this.ensureParentDirs(g),this.data.set(g,{type:`file`,lazy:t,mode:s?.mode??420,mtime:s?.mtime??new Date})}async materializeLazy(e,t){let s=await t.lazy(),g={type:`file`,content:typeof s==`string`?ot.encode(s):s,mode:t.mode,mtime:t.mtime};return this.data.set(e,g),g}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in s){let e=await this.materializeLazy(t,s);return e.content instanceof Uint8Array?e.content:ot.encode(e.content)}return s.content instanceof Uint8Array?s.content:ot.encode(s.content)}async writeFile(e,t,s){this.writeFileSync(e,t,s)}async appendFile(e,t,s){h$1(e,`append`);let g=c$1(e),S=this.data.get(g);if(S&&S.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let w=o(t,l$1(s));if(S?.type===`file`){let e=S;`lazy`in e&&(e=await this.materializeLazy(g,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),s=new Uint8Array(t.length+w.length);s.set(t),s.set(w,t.length),this.data.set(g,{type:`file`,content:s,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,s)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, stat '${e}'`);s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}async lstat(e){h$1(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(s.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:s.mode,size:s.target.length,mtime:s.mtime||new Date};s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`);if(s.length<=1)return t;let g=``,S=new Set;for(let t=0;t<s.length-1;t++){let w=s[t];g=`${g}/${w}`;let E=this.data.get(g),D=0,O=40;for(;E&&E.type===`symlink`&&D<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);S.add(g),g=v$1(g,E.target),E=this.data.get(g),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${g}/${s[s.length-1]}`}resolvePathWithSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`),g=``,S=new Set;for(let t of s){g=`${g}/${t}`;let s=this.data.get(g),w=0,E=40;for(;s&&s.type===`symlink`&&w<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);S.add(g),g=v$1(g,s.target),s=this.data.get(g),w++}if(w>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return g}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$1(e,`mkdir`);let s=c$1(e);if(this.data.has(s)){if(this.data.get(s)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let g=m$1(s);if(g!==`/`&&!this.data.has(g))if(t?.recursive)this.mkdirSync(g,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(s,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let g=new Set;for(;s&&s.type===`symlink`;){if(g.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);g.add(t),t=v$1(t,s.target),s=this.data.get(t)}if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let S=t===`/`?`/`:`${t}/`,w=new Map;for(let[e,s]of this.data.entries())if(e!==t&&e.startsWith(S)){let t=e.slice(S.length),g=t.split(`/`)[0];g&&!t.includes(`/`,g.length)&&!w.has(g)&&w.set(g,{name:g,isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:s.type===`symlink`})}return Array.from(w.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$1(e,`rm`);let s=c$1(e),g=this.data.get(s);if(!g){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(g.type===`directory`){let g=await this.readdir(s);if(g.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of g){let g=p$1(s,e);await this.rm(g,t)}}}this.data.delete(s)}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=c$1(e),S=c$1(t),w=this.data.get(g);if(!w)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(w.type===`file`)if(this.ensureParentDirs(S),`content`in w){let e=w.content instanceof Uint8Array?new Uint8Array(w.content):w.content;this.data.set(S,{...w,content:e})}else this.data.set(S,{...w});else if(w.type===`symlink`)this.ensureParentDirs(S),this.data.set(S,{...w});else if(w.type===`directory`){if(!s?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(S,{recursive:!0});let t=await this.readdir(g);for(let e of t){let t=p$1(g,e),w=p$1(S,e);await this.cp(t,w,s)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return y(e,t)}async chmod(e,t){h$1(e,`chmod`);let s=c$1(e),g=this.data.get(s);if(!g)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);g.mode=t}async symlink(e,t){h$1(t,`symlink`);let s=c$1(t);if(this.data.has(s))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(s),this.data.set(s,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=c$1(e),g=c$1(t),S=this.data.get(s);if(!S)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(S.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(g))throw Error(`EEXIST: file already exists, link '${t}'`);let w=S;`lazy`in w&&(w=await this.materializeLazy(s,w)),this.ensureParentDirs(g),this.data.set(g,{type:`file`,content:w.content,mode:w.mode,mtime:w.mtime})}async readlink(e){h$1(e,`readlink`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return s.target}async realpath(e){h$1(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,s){h$1(e,`utimes`);let g=c$1(e),S=this.resolvePathWithSymlinks(g),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);w.mtime=s}};function Ji(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function eo(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function to(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function so(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
|
|
52
52
|
`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
|
|
53
53
|
`),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>_i$1(t)):e.writeFileSync(`/proc/self/status`,_i$1(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function un(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){Ji(e)&&(eo(e,t),to(e),so(e,s))}var ro=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],no=[`braceexpand`,`hashall`,`interactive-comments`];function Ls(e){let t=[],s=[...no.map(e=>({name:e,enabled:!0})),...ro.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s)e.enabled&&t.push(e.name);return t.join(`:`)}function lt(e){e.state.env.set(`SHELLOPTS`,Ls(e.state.options))}var io=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function Fs(e){let t=[];for(let s of io)e[s]&&t.push(s);return t.join(`:`)}function Ms(e){e.state.env.set(`BASHOPTS`,Fs(e.state.shoptOptions))}var oo=`BASH_ALIAS_`;function fn(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function dn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function hn(e,t){return e.env.get(`${oo}${t}`)}function Ws(e,t,s){if(!t.name||!fn(t.name))return t;let g=dn(t.name);if(!g)return t;let S=hn(e,g);if(!S||s.has(g))return t;try{s.add(g);let w=new V,E=S,D=S.endsWith(` `);if(!D)for(let e of t.args){let t=mn(e);E+=` ${t}`}let O;try{O=w.parse(E)}catch(e){if(e instanceof G$1)throw e;return t}if(O.statements.length!==1||O.statements[0].pipelines.length!==1||O.statements[0].pipelines[0].commands.length!==1)return pn(t,S);let k=O.statements[0].pipelines[0].commands[0];if(k.type!==`SimpleCommand`)return pn(t,S);let j={...k,assignments:[...t.assignments,...k.assignments],redirections:[...k.redirections,...t.redirections],line:t.line};if(D&&t.args.length>0&&(j={...j,args:[...j.args,...t.args]},j.args.length>0)){let t=j.args[0];if(fn(t)){let g=dn(t);if(g&&hn(e,g)){let g={type:`SimpleCommand`,name:t,args:j.args.slice(1),assignments:[],redirections:[]},S=Ws(e,g,s);S!==g&&(j={...j,name:S.name,args:[...S.args]})}}}return j}catch(e){throw s.delete(g),e}}function pn(e,t){let s=t;for(let t of e.args){let e=mn(t);s+=` ${e}`}let g=new V;return{type:`SimpleCommand`,name:g.parseWordFromString(`eval`,!1,!1),args:[g.parseWordFromString(`'${s.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function mn(e){let t=``;for(let s of e.parts)switch(s.type){case`Literal`:t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${s.value}'`;break;case`DoubleQuoted`:t+=`"${s.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${s.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${s.expression}))`;break;case`Glob`:t+=s.pattern;break;default:break}return t}async function yn(e,t){let s=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),g=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!g||!s.endsWith(`)`))return null;let S=g[1],w=[],E=!1,D=``,O=!1;for(let s of t.parts)if(s.type===`Literal`){let e=s.value;if(!E){let t=e.indexOf(`=(`);t!==-1&&(E=!0,e=e.slice(t+2))}if(E){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(D||O)&&(w.push(D),D=``,O=!1):e&&(D+=e)}}else if(E)if(s.type===`BraceExpansion`)if(/^\[.+\]=/.test(D))D+=En$1({type:`Word`,parts:[s]});else{(D||O)&&(w.push(D),D=``,O=!1);let t=await wl(e,{type:`Word`,parts:[s]});w.push(...t.values)}else{(s.type===`SingleQuoted`||s.type===`DoubleQuoted`||s.type===`Escaped`)&&(O=!0);let t=await Pt$1(e,{type:`Word`,parts:[s]});D+=t}return(D||O)&&w.push(D),`${S}=(${w.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function gn(e,t){let s=-1,g=-1,S=!1;for(let e=0;e<t.parts.length;e++){let w=t.parts[e];if(w.type===`Literal`){let t=w.value.indexOf(`+=`);if(t!==-1){let E=w.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){s=e,g=t,S=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=e,g=t,S=!0;break}}let E=w.value.indexOf(`=`);if(E!==-1&&(E===0||w.value[E-1]!==`+`)){let t=w.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){s=e,g=E;break}}}}if(s===-1)return null;let w=t.parts.slice(0,s),E=t.parts[s];if(E.type!==`Literal`)return null;let D=S?2:1,O=E.value.slice(0,g),k=E.value.slice(g+D),j=t.parts.slice(s+1),F=``;for(let t of w)F+=await Pt$1(e,{type:`Word`,parts:[t]});F+=O;let L={type:`Word`,parts:k===``?j:[{type:`Literal`,value:k},...j]},B=L.parts.length>0?await Pt$1(e,L):``;return`${F}${S?`+=`:`=`}${B}`}var ao=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function wn(e){return ao.includes(e)}var W=Object.freeze({stdout:``,stderr:``,exitCode:0});function z(e=``){return{stdout:e,stderr:``,exitCode:0}}function A(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function Ne(e,t,s=``,g=``){throw new b(e,t,s,g)}function le(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new b(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function zs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new f;return W}if(t.length>1)throw new d(1,``,`bash: break: too many arguments
|
|
@@ -767,7 +767,7 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
767
767
|
`}){let g=e.split(/\r?\n/);for(let e=1;e<g.length;e+=1)g[e]=t+g[e];return g.join(s)}})),require_parse_factory_options=__commonJSMin(((e,t)=>{t.exports=D;let{LEVEL_NAMES:s}=require_constants(),g=require_colors(),S=require_handle_custom_levels_opts(),w=require_handle_custom_levels_names_opts(),E=require_get_level_label_data();function D(e){let t=e.crlf?`\r
|
|
768
768
|
`:`
|
|
769
769
|
`,D=` `,{customPrettifiers:O,errorLikeObjectKeys:k,hideObject:j,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,singleLine:J,timestampKey:Y,translateTime:te}=e,ne=e.errorProps.split(`,`),ae=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,oe=S(e.customLevels),se=w(e.customLevels),ce=E(ae,oe,se),ue;if(e.customColors)if(typeof e.customColors==`string`)ue=e.customColors.split(`,`).reduce((t,g)=>{let[S,w]=g.split(`:`),E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else if(typeof e.customColors==`object`)ue=Object.keys(e.customColors).reduce((t,g)=>{let[S,w]=[g,e.customColors[g]],E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let de={customLevels:oe,customLevelNames:se};ae===!0&&!e.customLevels&&(de.customLevels=void 0,de.customLevelNames=void 0);let fe=e.include===void 0?void 0:new Set(e.include.split(`,`)),me=!fe&&e.ignore?new Set(e.ignore.split(`,`)):void 0,ge=g(e.colorize,ue,ae),_e=e.colorizeObjects?ge:g(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:ge,customColors:ue,customLevelNames:se,customLevels:oe,customPrettifiers:O,customProperties:de,errorLikeObjectKeys:k,errorProps:ne,getLevelLabelData:ce,hideObject:j,ignoreKeys:me,includeKeys:fe,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,objectColorizer:_e,singleLine:J,timestampKey:Y,translateTime:te,useOnlyCustomProps:ae}}})),require_fast_safe_stringify=__commonJSMin(((e,t)=>{t.exports=D,D.default=D,D.stable=F,D.stableStringify=F;var s=`[...]`,g=`[Circular]`,S=[],w=[];function E(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function D(e,t,s,g){g===void 0&&(g=E()),k(e,``,0,[],void 0,0,g);var D;try{D=w.length===0?JSON.stringify(e,t,s):JSON.stringify(e,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var O=S.pop();O.length===4?Object.defineProperty(O[0],O[1],O[3]):O[0][O[1]]=O[2]}}return D}function O(e,t,s,g){var E=Object.getOwnPropertyDescriptor(g,s);E.get===void 0?(g[s]=e,S.push([g,s,t])):E.configurable?(Object.defineProperty(g,s,{value:e}),S.push([g,s,t,E])):w.push([t,s,e])}function k(e,t,S,w,E,D,j){D+=1;var F;if(typeof e==`object`&&e){for(F=0;F<w.length;F++)if(w[F]===e){O(g,e,t,E);return}if(j.depthLimit!==void 0&&D>j.depthLimit){O(s,e,t,E);return}if(j.edgesLimit!==void 0&&S+1>j.edgesLimit){O(s,e,t,E);return}if(w.push(e),Array.isArray(e))for(F=0;F<e.length;F++)k(e[F],F,F,w,e,D,j);else{var L=Object.keys(e);for(F=0;F<L.length;F++){var B=L[F];k(e[B],B,F,w,e,D,j)}}w.pop()}}function j(e,t){return e<t?-1:e>t?1:0}function F(e,t,s,g){g===void 0&&(g=E());var D=L(e,``,0,[],void 0,0,g)||e,O;try{O=w.length===0?JSON.stringify(D,t,s):JSON.stringify(D,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var k=S.pop();k.length===4?Object.defineProperty(k[0],k[1],k[3]):k[0][k[1]]=k[2]}}return O}function L(e,t,w,E,D,k,F){k+=1;var B;if(typeof e==`object`&&e){for(B=0;B<E.length;B++)if(E[B]===e){O(g,e,t,D);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(F.depthLimit!==void 0&&k>F.depthLimit){O(s,e,t,D);return}if(F.edgesLimit!==void 0&&w+1>F.edgesLimit){O(s,e,t,D);return}if(E.push(e),Array.isArray(e))for(B=0;B<e.length;B++)L(e[B],B,B,E,e,k,F);else{var H={},q=Object.keys(e).sort(j);for(B=0;B<q.length;B++){var ee=q[B];L(e[ee],ee,B,E,e,k,F),H[ee]=e[ee]}if(D!==void 0)S.push([D,t,e]),D[t]=H;else return H}E.pop()}}function B(e){return e=e===void 0?function(e,t){return t}:e,function(t,s){if(w.length>0)for(var g=0;g<w.length;g++){var S=w[g];if(S[1]===t&&S[0]===s){s=S[2],w.splice(g,1);break}}return e.call(this,t,s)}}})),require_prettify_error=__commonJSMin(((e,t)=>{t.exports=g;let s=require_join_lines_with_indentation();function g({keyName:e,lines:t,eol:g,ident:S}){let w=``,E=`${S}${e}: ${s({input:t,ident:S,eol:g})}${g}`.split(g);for(let e=0;e<E.length;e+=1){e!==0&&(w+=g);let t=E[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let s=/^\s*/.exec(t)[0].length+4,S=` `.repeat(s),E=e[2];w+=e[1]+g+S+JSON.parse(E).replace(/\n/g,g+S)}else w+=t}else w+=t}return w}})),require_prettify_object=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_fast_safe_stringify(),S=require_join_lines_with_indentation(),w=require_prettify_error();function E({log:e,excludeLoggerKeys:t=!0,skipKeys:E=[],context:D}){let{EOL:O,IDENT:k,customPrettifiers:j,errorLikeObjectKeys:F,objectColorizer:L,singleLine:B,colorizer:H}=D,q=[].concat(E);t===!0&&Array.prototype.push.apply(q,s);let ee=``,{plain:J,errors:Y}=Object.entries(e).reduce(({plain:t,errors:s},[g,S])=>{if(q.includes(g)===!1){let w=typeof j[g]==`function`?j[g](S,g,e,{colors:H.colors}):S;F.includes(g)?s[g]=w:t[g]=w}return{plain:t,errors:s}},{plain:{},errors:{}});return B?(Object.keys(J).length>0&&(ee+=L.greyMessage(g(J))),ee+=O,ee=ee.replace(/\\\\/gi,`\\`)):Object.entries(J).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);if(s===void 0)return;s=s.replace(/\\\\/gi,`\\`);let w=S({input:s,ident:k,eol:O});ee+=`${k}${L.property(e)}:${w.startsWith(O)?``:` `}${w}${O}`}),Object.entries(Y).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);s!==void 0&&(ee+=w({keyName:e,lines:s,eol:O,ident:k}))}),ee}})),require_prettify_error_log=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_is_object(),S=require_join_lines_with_indentation(),w=require_prettify_object();function E({log:e,context:t}){let{EOL:E,IDENT:D,errorProps:O,messageKey:k}=t,j=e.stack,F=`${D}${S({input:j,ident:D,eol:E})}${E}`;if(O.length>0){let S=s.concat(k,`type`,`stack`),j;j=O[0]===`*`?Object.keys(e).filter(e=>S.includes(e)===!1):O.filter(e=>S.includes(e)===!1);for(let s=0;s<j.length;s+=1){let S=j[s];if(S in e){if(g(e[S])){let s=w({log:e[S],excludeLoggerKeys:!1,context:{...t,IDENT:D+D}});F=`${F}${D}${S}: {${E}${s}${D}}${E}`;continue}F=`${F}${D}${S}: ${e[S]}${E}`}}}return F}})),require_prettify_level=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g({log:e,context:t}){let{colorizer:g,customLevels:S,customLevelNames:w,levelKey:E,getLevelLabelData:D}=t,O=t.customPrettifiers?.level,k=s(e,E);if(k===void 0)return;let j=g(k,{customLevels:S,customLevelNames:w});if(O){let[t]=D(k);return O(k,E,e,{label:t,labelColorized:j,colors:g.colors})}return j}})),require_prettify_message=__commonJSMin(((e,t)=>{t.exports=w;let{LEVELS:s}=require_constants(),g=require_get_property_value(),S=require_interpret_conditionals();function w({log:e,context:t}){let{colorizer:w,customLevels:E,levelKey:D,levelLabel:O,messageFormat:k,messageKey:j,useOnlyCustomProps:F}=t;if(k&&typeof k==`string`){let t=S(k,e),j=String(t).replace(/{([^{}]+)}/g,function(t,S){let w;if(S===O&&(w=g(e,D))!==void 0)return(F?E===void 0:E[w]===void 0)?s[w]:E[w];let k=g(e,S);return k===void 0?``:k});return w.message(j)}if(k&&typeof k==`function`){let t=k(e,j,O,{colors:w.colors});return w.message(t)}if(j in e&&!(typeof e[j]!=`string`&&typeof e[j]!=`number`&&typeof e[j]!=`boolean`))return w.message(e[j])}})),require_prettify_metadata=__commonJSMin(((e,t)=>{t.exports=s;function s({log:e,context:t}){let{customPrettifiers:s,colorizer:g}=t,S=``;if(e.name||e.pid||e.hostname){if(S+=`(`,e.name&&(S+=s.name?s.name(e.name,`name`,e,{colors:g.colors}):e.name),e.pid){let t=s.pid?s.pid(e.pid,`pid`,e,{colors:g.colors}):e.pid;e.name&&e.pid?S+=`/`+t:S+=t}if(e.hostname){let t=s.hostname?s.hostname(e.hostname,`hostname`,e,{colors:g.colors}):e.hostname;S+=`${S===`(`?`on`:` on`} ${t}`}S+=`)`}if(e.caller){let t=s.caller?s.caller(e.caller,`caller`,e,{colors:g.colors}):e.caller;S+=`${S===``?``:` `}<${t}>`}if(S!==``)return S}})),require_prettify_time=__commonJSMin(((e,t)=>{t.exports=g;let s=require_format_time();function g({log:e,context:t}){let{timestampKey:g,translateTime:S}=t,w=t.customPrettifiers?.time,E=null;if(g in e?E=e[g]:`timestamp`in e&&(E=e.timestamp),E===null)return;let D=S?s(E,S):E;return w?w(D):`[${D}]`}})),require_utils=__commonJSMin(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin(((e,t)=>{let s=typeof Buffer<`u`,g=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,S=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function w(e,t,w){w==null&&typeof t==`object`&&t&&(w=t,t=void 0),s&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let D=JSON.parse(e,t);if(typeof D!=`object`||!D)return D;let O=w&&w.protoAction||`error`,k=w&&w.constructorAction||`error`;if(O===`ignore`&&k===`ignore`)return D;if(O!==`ignore`&&k!==`ignore`){if(g.test(e)===!1&&S.test(e)===!1)return D}else if(O!==`ignore`&&k===`ignore`){if(g.test(e)===!1)return D}else if(S.test(e)===!1)return D;return E(D,{protoAction:O,constructorAction:k,safe:w&&w.safe})}function E(e,{protoAction:t=`error`,constructorAction:s=`error`,safe:g}={}){let S=[e];for(;S.length;){let e=S;S=[];for(let w of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`__proto__`)){if(g===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.__proto__}if(s!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`constructor`)&&w.constructor!==null&&typeof w.constructor==`object`&&Object.prototype.hasOwnProperty.call(w.constructor,`prototype`)){if(g===!0)return null;if(s===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.constructor}for(let e in w){let t=w[e];t&&typeof t==`object`&&S.push(t)}}}return e}function D(e,t,s){let{stackTraceLimit:g}=Error;Error.stackTraceLimit=0;try{return w(e,t,s)}finally{Error.stackTraceLimit=g}}function O(e,t){let{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return w(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=s}}t.exports=D,t.exports.default=D,t.exports.parse=D,t.exports.safeParse=O,t.exports.scan=E})),require_pretty=__commonJSMin(((e,t)=>{t.exports=q;let s=require_secure_json_parse(),g=require_is_object(),S=require_prettify_error_log(),w=require_prettify_level(),E=require_prettify_message(),D=require_prettify_metadata(),O=require_prettify_object(),k=require_prettify_time(),j=require_filter_log(),{LEVELS:F,LEVEL_KEY:L,LEVEL_NAMES:B}=require_constants(),H=e=>{try{return{value:s.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function q(e){let t;if(g(e))t=e;else{let s=H(e);if(s.err||!g(s.value))return e+this.EOL;t=s.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let s;if(s=e?this.customLevelNames[this.minimumLevel]:B[this.minimumLevel],s||=typeof this.minimumLevel==`string`?B[this.minimumLevel]:B[F[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?L:this.levelKey]<s)return}let s=E({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=j({log:t,context:this.context}));let q=w({log:t,context:{...this.context,...this.context.customProperties}}),ee=D({log:t,context:this.context}),J=k({log:t,context:this.context}),Y=``;if(this.levelFirst&&q&&(Y=`${q}`),J&&Y===``?Y=`${J}`:J&&(Y=`${Y} ${J}`),!this.levelFirst&&q&&(Y=Y.length>0?`${Y} ${q}`:q),ee&&(Y=Y.length>0?`${Y} ${ee}:`:ee),Y.endsWith(`:`)===!1&&Y!==``&&(Y+=`:`),s!==void 0&&(Y=Y.length>0?`${Y} ${s}`:s),Y.length>0&&!this.singleLine&&(Y+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=S({log:t,context:this.context});this.singleLine&&(Y+=this.EOL),Y+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),s=O({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(s)&&(Y+=` `),Y+=s}return Y}})),require_pino_pretty=__commonJSMin(((e,t)=>{let{isColorSupported:s}=require_colorette(),g=require_pump(),{Transform:S}=__require(`node:stream`),w=require_pino_abstract_transport(),E=require_colors(),{ERROR_LIKE_KEYS:D,LEVEL_KEY:O,LEVEL_LABEL:k,MESSAGE_KEY:j,TIMESTAMP_KEY:F}=require_constants(),{buildSafeSonicBoom:L,parseFactoryOptions:B}=require_utils(),H=require_pretty(),q={colorize:s,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:D,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:O,levelLabel:k,messageFormat:null,messageKey:j,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:F,translateTime:!0,useOnlyCustomProps:!0};function ee(e){let t=B(Object.assign({},q,e));return H.bind({...t,context:t})}function J(e={}){let t=ee(e),s;return w(function(w){w.on(`message`,function s(g){!g||g.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:g.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||D,g.config.errorKey])),customLevels:g.config.levels.values}),t=ee(e),w.off(`message`,s))});let E=new S({objectMode:!0,autoDestroy:!0,transform(e,s,g){g(null,t(e))}});return s=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:L({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),w.on(`unknown`,function(e){s.write(e+`
|
|
770
|
-
`)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementReconcileOwnFlushSkips(){counters$1.reconcileOwnFlushSkips++}function incrementReconcileInFlightFallthroughs(){counters$1.reconcileInFlightFallthroughs++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.reconcileOwnFlushSkips=0,counters$1.reconcileInFlightFallthroughs=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}function isManagedArtifactDoc(e){return isManagedArtifactDocName(e)}function isReservedForUserTree(e){return isSystemDoc(e)||isConfigDoc(e)||isManagedArtifactDoc(e)}function isLinkIndexExcludedDoc(e){return isSystemDoc(e)||isConfigDoc(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$18=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID$1()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$18().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$18().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$18()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$18().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID$1()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$18().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$18()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$18().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$18().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function classifyParseError(e){return e===`top-level value is not a mapping`?`non-mapping-top-level`:e.startsWith(`value at "`)||e.startsWith(`schema validation failed:`)?`schema-rejection`:e.startsWith(`parse threw:`)||e.startsWith(`toJS threw:`)||e.length>0&&e!==`unknown YAML parse error`?`yaml-parse-error`:`unknown`}function respondFrontmatterMalformed(e,t,s){let g=classifyParseError(t.parseError);console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,class:g,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$17=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,s,g){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});return withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":s,"agent.markdown.bytes":t.length}},()=>{let S=applyAgentMarkdownWriteInner(e,t,s,g);return S!==void 0&&setActiveSpanAttributes({"agent.content_divergent":!0,"agent.intended_bytes":S.intendedBytes,"agent.actual_bytes":S.actualBytes,"agent.byte_delta":S.byteDelta,"agent.divergence_type":S.divergenceType}),S})}function applyAgentMarkdownWriteInner(e,t,s,g){try{let{frontmatter:S,body:w}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:E,body:D}=stripFrontmatter(t);if((s===`append`||s===`prepend`)&&D===``)return;let O,k;switch(s){case`replace`:O=E||S,k=D;break;case`patch`:O=E||S,k=D;break;case`prepend`:O=S,k=w.length>0?`${D.replace(/\n+$/,``)}\n\n${w.replace(/^\n+/,``)}`:D;break;case`append`:O=S,k=w.length>0?`${w.replace(/\n+$/,``)}\n\n${D.replace(/^\n+/,``)}`:D;break}if(O!==S){let t=parseFrontmatterYaml(unwrapFrontmatterFences(O));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}let j=prependFrontmatter(O,k);return s===`replace`?replaceRawBody(e,j,g):composeAndWriteRawBody(e,j,`agent`,g),evaluateContentDivergence(e.getText(`source`).toString(),j,s)}catch(g){throw g instanceof FrontmatterMalformedError||log$17.error({err:g,docName:e.name,position:s,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),g}}function applyAgentUndo(e,t,s){let g=e.dc.document;if(isDocInConflict(g))throw new DocInConflictError({file:docNameToFile(g.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let g=applyAgentUndoInner(e,t,s);return setActiveSpanAttributes({"agent.undo_effective":g}),g})}function applyAgentUndoInner(e,t,s){let{dc:g,um:S,undoOrigin:w}=e,E=g.document,D=!1;return E.transact(()=>{if(t===`last`){if(S.undoStack.length===0)return;S.undo(),D=!0}else for(;S.undoStack.length>0;)S.undo(),D=!0;deriveFragmentFromYtext(E,s)},w),D}function createSessionOrigin(e,t,s,g,S){let w={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(w.agent_type=t),s!==void 0&&(w.principal=s),g!==void 0&&(w.display_name=g),S!==void 0&&(w.color_seed=S),Object.freeze(w);let E={source:`local`,skipStoreHooks:!1,context:w};return Object.freeze(E),E}function createUndoOrigin(e,t){let s={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(s.agent_type=t),Object.freeze(s);let g={source:`local`,skipStoreHooks:!1,context:s};return Object.freeze(g),g}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,s]of this.sessions)e.endsWith(t)&&(yield s)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,s){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let g=this.sessionKey(e,t),S=this.sessions.get(g);if(S)return S;let w=this.pendingSessions.get(g);if(w)return w;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let E=this._createSession(e,t,s);this.pendingSessions.set(g,E);try{let e=await E;return this.sessions.set(g,e),e}finally{this.pendingSessions.delete(g)}}async _createSession(e,t,s){let g=s?.clientName,S=t.startsWith(`agent-`)?t.slice(6):t,w=createSessionOrigin(S,g,s?.principalId,s?.displayName,s?.colorSeed),E=createUndoOrigin(S,g),D={session_id:S,...g===void 0?{}:{agent_type:g},...s?.clientName===void 0?{}:{client_name:s.clientName},...s?.principalId===void 0?{}:{principalId:s.principalId}},O=await this.hocuspocus.openDirectConnection(e,D),k=new UndoManager([O.document.getText(`source`),O.document.getMap(`agent-flash`)],{trackedOrigins:new Set([w]),captureTimeout:500,captureTransaction:e=>e.origin!==E,ignoreRemoteMapChanges:!0}),j=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return k.on(`stack-item-added`,j),k.on(`stack-item-updated`,j),log$17.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:O,origin:w,undoOrigin:E,um:k,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,s){try{try{t.um.destroy()}catch(e){log$17.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$17.error({err:e,...s},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let s=this.sessionKey(e,t),g=this.sessions.get(s);g&&(await this.cleanupSession(s,g,{docName:e,agentId:t}),log$17.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];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 g=e.slice(t+1);return{kind:s,payload:g.length>0?g: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 counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t),S=g.filter(e=>shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs));g.length>0&&emitToleranceFire(g,e,t,s.docName);for(let e of S)incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e}))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedSymlinkSync(e,t,s){withSpanSync(`fs.symlinkSync`,{attributes:buildAttrs(`symlinkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{symlinkSync(e,t,s)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}const tracedAtomicFs={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
770
|
+
`)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementReconcileOwnFlushSkips(){counters$1.reconcileOwnFlushSkips++}function incrementReconcileInFlightFallthroughs(){counters$1.reconcileInFlightFallthroughs++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.reconcileOwnFlushSkips=0,counters$1.reconcileInFlightFallthroughs=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}function isManagedArtifactDoc(e){return isManagedArtifactDocName(e)}function isReservedForUserTree(e){return isSystemDoc(e)||isConfigDoc(e)||isManagedArtifactDoc(e)}function isLinkIndexExcludedDoc(e){return isSystemDoc(e)||isConfigDoc(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$18=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$18().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$18().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$18()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$18().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$18().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$18()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$18().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$18().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function classifyParseError(e){return e===`top-level value is not a mapping`?`non-mapping-top-level`:e.startsWith(`value at "`)||e.startsWith(`schema validation failed:`)?`schema-rejection`:e.startsWith(`parse threw:`)||e.startsWith(`toJS threw:`)||e.length>0&&e!==`unknown YAML parse error`?`yaml-parse-error`:`unknown`}function respondFrontmatterMalformed(e,t,s){let g=classifyParseError(t.parseError);console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,class:g,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$17=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,s,g){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});return withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":s,"agent.markdown.bytes":t.length}},()=>{let S=applyAgentMarkdownWriteInner(e,t,s,g);return S!==void 0&&setActiveSpanAttributes({"agent.content_divergent":!0,"agent.intended_bytes":S.intendedBytes,"agent.actual_bytes":S.actualBytes,"agent.byte_delta":S.byteDelta,"agent.divergence_type":S.divergenceType}),S})}function applyAgentMarkdownWriteInner(e,t,s,g){try{let{frontmatter:S,body:w}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:E,body:D}=stripFrontmatter(t);if((s===`append`||s===`prepend`)&&D===``)return;let O,k;switch(s){case`replace`:O=E||S,k=D;break;case`patch`:O=E||S,k=D;break;case`prepend`:O=S,k=w.length>0?`${D.replace(/\n+$/,``)}\n\n${w.replace(/^\n+/,``)}`:D;break;case`append`:O=S,k=w.length>0?`${w.replace(/\n+$/,``)}\n\n${D.replace(/^\n+/,``)}`:D;break}if(O!==S){let t=parseFrontmatterYaml(unwrapFrontmatterFences(O));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}let j=prependFrontmatter(O,k);return s===`replace`?replaceRawBody(e,j,g):composeAndWriteRawBody(e,j,`agent`,g),evaluateContentDivergence(e.getText(`source`).toString(),j,s)}catch(g){throw g instanceof FrontmatterMalformedError||log$17.error({err:g,docName:e.name,position:s,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),g}}function applyAgentUndo(e,t,s){let g=e.dc.document;if(isDocInConflict(g))throw new DocInConflictError({file:docNameToFile(g.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let g=applyAgentUndoInner(e,t,s);return setActiveSpanAttributes({"agent.undo_effective":g}),g})}function applyAgentUndoInner(e,t,s){let{dc:g,um:S,undoOrigin:w}=e,E=g.document,D=!1;return E.transact(()=>{if(t===`last`){if(S.undoStack.length===0)return;S.undo(),D=!0}else for(;S.undoStack.length>0;)S.undo(),D=!0;deriveFragmentFromYtext(E,s)},w),D}function createSessionOrigin(e,t,s,g,S){let w={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(w.agent_type=t),s!==void 0&&(w.principal=s),g!==void 0&&(w.display_name=g),S!==void 0&&(w.color_seed=S),Object.freeze(w);let E={source:`local`,skipStoreHooks:!1,context:w};return Object.freeze(E),E}function createUndoOrigin(e,t){let s={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(s.agent_type=t),Object.freeze(s);let g={source:`local`,skipStoreHooks:!1,context:s};return Object.freeze(g),g}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,s]of this.sessions)e.endsWith(t)&&(yield s)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,s){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let g=this.sessionKey(e,t),S=this.sessions.get(g);if(S)return S;let w=this.pendingSessions.get(g);if(w)return w;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let E=this._createSession(e,t,s);this.pendingSessions.set(g,E);try{let e=await E;return this.sessions.set(g,e),e}finally{this.pendingSessions.delete(g)}}async _createSession(e,t,s){let g=s?.clientName,S=t.startsWith(`agent-`)?t.slice(6):t,w=createSessionOrigin(S,g,s?.principalId,s?.displayName,s?.colorSeed),E=createUndoOrigin(S,g),D={session_id:S,...g===void 0?{}:{agent_type:g},...s?.clientName===void 0?{}:{client_name:s.clientName},...s?.principalId===void 0?{}:{principalId:s.principalId}},O=await this.hocuspocus.openDirectConnection(e,D),k=new UndoManager([O.document.getText(`source`),O.document.getMap(`agent-flash`)],{trackedOrigins:new Set([w]),captureTimeout:500,captureTransaction:e=>e.origin!==E,ignoreRemoteMapChanges:!0}),j=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return k.on(`stack-item-added`,j),k.on(`stack-item-updated`,j),log$17.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:O,origin:w,undoOrigin:E,um:k,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,s){try{try{t.um.destroy()}catch(e){log$17.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$17.error({err:e,...s},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let s=this.sessionKey(e,t),g=this.sessions.get(s);g&&(await this.cleanupSession(s,g,{docName:e,agentId:t}),log$17.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];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 g=e.slice(t+1);return{kind:s,payload:g.length>0?g: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 counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function createDocCanonicalizer(e,t){let s=t.resolveEmbed&&t.docName?{resolveEmbed:t.resolveEmbed,resolveSize:t.resolveSize,sourcePath:t.docName}:void 0;return t=>e.serialize(e.parseWithFallback(t,s))}function assertBridgeInvariant(e,t,s){let g=g=>{let S=g.filter(e=>shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs));g.length>0&&emitToleranceFire(g,e,t,s.docName);for(let e of S)incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e}))},S=normalizeBridge(e),w=normalizeBridge(t);if(S===w)return e!==t&&g(detectAppliedToleranceClasses(e,t)),!0;if(s.canonicalizeBody&&isParseEquivalentBridge(e,t,s.canonicalizeBody))return g([...detectAppliedToleranceClasses(e,t),PARSE_EQUIVALENCE_TOLERANCE]),!0;let E={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${S.slice(0,300)}\n frag: ${w.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(E);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let D=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(E,{verbose:D}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedSymlinkSync(e,t,s){withSpanSync(`fs.symlinkSync`,{attributes:buildAttrs(`symlinkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{symlinkSync(e,t,s)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}const tracedAtomicFs={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
771
771
|
`);for(let e=0;e<t.length;e++){let s=t[e]??``;if(s.length!==0&&/^\s+$/.test(s))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function validateConfigContent(e,t){return e===`__config__/okignore`?validateOkignore(t):validateConfigYaml(t)}function defaultLkgFor(e){return e===`__config__/okignore`?``:serializedDefaults()}function validateConfigYaml(e){let t=(0,import_dist$1.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let s=t.toJSON()??{},g=ConfigSchema$1.safeParse(s);return g.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:g.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function loadConfigDoc(e,t,s){let g=e.getText(`source`);if(g.length>0)return;let S=configDocAbsPath(t,s),w=``;if(existsSync(S))try{w=readFileSync(S,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[config] Could not read ${S}: ${t}. Seeding with empty content.`),w=``}let E=validateConfigContent(t,w);!E.ok&&w.length>0&&getLogger(`config-persistence`).warn({docName:t,path:S},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{w.length>0&&g.insert(0,w)},CONFIG_VALIDATION_REVERT_ORIGIN),E.ok&&w.length>0?s.lkgCache.set(t,w):s.lkgCache.set(t,defaultLkgFor(t))}async function atomicWriteConfig(e,t){await tracedMkdir(dirname(e),{recursive:!0});let s=`${e}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(s,t,`utf-8`),await tracedRename(s,e)}catch(e){try{tracedUnlinkSync(s)}catch{}throw e}}async function storeConfigDoc(e,t,s,g){return withConfigSpan(`config.persist`,{"config.scope":configScopeAttr(t),"config.transport":`fs`},async S=>{let w=await storeConfigDocInner(e,t,s,g);return S.setAttribute(`config.outcome`,persistOutcomeAttr(w)),w})}function persistOutcomeAttr(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function storeConfigDocInner(e,t,s,g){if(g.ephemeral&&t===`__config__/okignore`||s===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let S=e.getText(`source`),w=S.toString(),E=g.lkgCache.get(t);if(w.length===0&&(t!==`__config__/okignore`||E===void 0||E===``)||E!==void 0&&w===E)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let s=validateConfigContent(t,w);return e.setAttribute(`config.outcome`,s.ok?`success`:`rejected`),s.ok||emitSchemaInvalidIssueEvents(s.error),s});if(!O.ok)return await withConfigSpan(`config.revert`,{"config.scope":D,"config.outcome":`reverted`},async()=>{let s=E??defaultLkgFor(t);e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_VALIDATION_REVERT_ORIGIN),E===void 0&&g.lkgCache.set(t,s),t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),g.onConfigRejected?.(t,O.error)}),`reverted`;let k=configDocAbsPath(t,g);try{await tracedMkdir(dirname(k),{recursive:!0})}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not create parent dir for ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${k}: ${s}`}),`write-failed`}try{return await withFileLock(`${k}.lock`,async()=>{let s=null;try{s=readFileSync(k,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not read config for reconciliation: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${k}: ${s}`}),`write-failed`}}if(s!==null&&E!==void 0&&s!==E){if(validateConfigContent(t,s).ok)return e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),getLogger(`config-persistence`).info({docName:t,path:k},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:k},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(k,w)}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] write-failed at ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${k}: ${s}`}),`write-failed`}return g.lkgCache.set(t,w),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] lock timeout at ${k}: ${e.message}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);if(S!==void 0&&S===s)return`no-op`;let w=configScopeAttr(t),E=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L3`},e=>{let g=validateConfigContent(t,s);return e.setAttribute(`config.outcome`,g.ok?`success`:`rejected`),g.ok||emitSchemaInvalidIssueEvents(g.error),g});if(!E.ok)return t===`__config__/okignore`&&isKnownConfigError(E.error)&&okignoreRejectionCounter().add(1,{"error.code":E.error.code}),g.onConfigRejected?.(t,E.error),`rejected`;let D=e.getText(`source`);return e.transact(()=>{D.length>0&&D.delete(0,D.length),D.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),`applied`}let pendingContributors=new Map;function recordContributor(e,t,s,g,S,w,E,D){let O=pendingContributors.get(t);if(O||(O={writerId:t,displayName:s,colorSeed:g??s,docs:new Set,subjectOverride:S,actor:w,summaries:[],previousPaths:[]},pendingContributors.set(t,O)),O.docs.add(e),S!==void 0&&(O.subjectOverride=S),w!==void 0){let e=O.actor??{};w.principalId!==void 0&&(e.principalId=w.principalId),w.agentType!==void 0&&(e.agentType=w.agentType),w.clientName!==void 0&&(e.clientName=w.clientName),w.clientVersion!==void 0&&(e.clientVersion=w.clientVersion),w.label!==void 0&&(e.label=w.label),O.actor=e}if(typeof E==`string`&&E.length>0&&O.summaries.push(E),D&&D.length>0)for(let e of D)O.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,s]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:s.displayName,colorSeed:s.colorSeed,docs:new Set,actor:s.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of s.docs)e.docs.add(t);s.summaries.length>0&&(e.summaries=[...s.summaries,...e.summaries]),s.previousPaths.length>0&&(e.previousPaths=[...s.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let s of e.values()){let e={v:1,id:s.writerId,name:s.displayName,colorSeed:s.colorSeed,docs:[...s.docs]};s.summaries.length>0&&(e.summaries=[...s.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
772
772
|
`)}function formatContributors(){return formatContributorsFrom(pendingContributors)}function restoreContributorEntry(e,t){let s=pendingContributors.get(e);s||(s={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},pendingContributors.set(e,s));for(let e of t.docs)s.docs.add(e);t.summaries.length>0&&(s.summaries=[...t.summaries,...s.summaries]),t.previousPaths.length>0&&(s.previousPaths=[...t.previousPaths,...s.previousPaths])}function clearContributors(){pendingContributors.clear()}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let s=t.split(`
|
|
773
773
|
`),g=[],S=[],w=null;for(let e of s){let t=e.match(/^(`{3,}|~{3,})/);if(t){let e=t[1][0];w?e===w&&(w=null):w=e}w===null&&e.trim()===``&&S.length>0?(g.push(S.join(`
|
|
@@ -776,10 +776,10 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
776
776
|
|
|
777
777
|
`)}\n`:``;return E.length>0?{kind:`conflicts`,newContent:k,conflicts:E}:{kind:`merged`,newContent:k,mergedBlocks:w.length}}function computeEditOps(e,t){let s=new Map,g=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)s.set(t,{action:`keep`,insertsBefore:[]});let S=new Set,w=new Set;for(let[e,t]of g)S.add(e),w.add(t);let E=-1;for(let D=0;D<e.length;D++)if(S.has(D)){let e=g.find(e=>e[0]===D)?.[1]??-1,S=[];for(let s=E+1;s<e;s++)w.has(s)||S.push(t[s]);let O=s.get(D);O&&(O.insertsBefore=S),E=e}else{let e=g.find(e=>e[0]>D),S=e?e[1]:t.length,O=[];for(let e=E+1;e<S;e++)w.has(e)||O.push(e);if(O.length>0){let e=O[0];w.add(e);let g=s.get(D);g&&(g.action=`modify`,g.newContent=t[e])}else{let e=s.get(D);e&&(e.action=`delete`)}}let D=[];for(let e=E+1;e<t.length;e++)w.has(e)||D.push(t[e]);let O=s.get(e.length);return O&&(O.insertsBefore=D),s}function longestCommonSubsequence(e,t){let s=e.length,g=t.length,S=g+1,w=new Uint32Array((s+1)*S);for(let E=1;E<=s;E++){let s=E*S,D=(E-1)*S;for(let S=1;S<=g;S++)if(e[E-1]===t[S-1])w[s+S]=w[D+(S-1)]+1;else{let e=w[D+S],t=w[s+(S-1)];w[s+S]=e>t?e:t}}let E=[],D=s,O=g;for(;D>0&&O>0;)e[D-1]===t[O-1]?(E.push([D-1,O-1]),D--,O--):w[(D-1)*S+O]>=w[D*S+(O-1)]?D--:O--;return E.reverse()}function acquireLock(e,t){let s=resolve(e,`lock`);if(existsSync(s)){let t=null;try{t=JSON.parse(readFileSync(s,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${s} — replacing`)}if(t&&!isValidLockPid(t.pid)&&(console.warn(`[shadow-lock] Invalid lock pid (${String(t.pid)}) at ${s} — replacing`),t=null),t){let s=t.hostname===hostname();if(!(s&&t.pid===process.pid)){if(s&&isProcessAlive(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let g={pid:process.pid,hostname:hostname(),startedAt:new Date().toISOString(),worktreeRoot:t};return writeFileSync(s,JSON.stringify(g,null,2),`utf-8`),s}function releaseLock(e){let t=resolve(e,`lock`);try{unlinkSync(t)}catch{}}const GIT_TIMEOUT_MS$3=(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),MAINTENANCE_GIT_TIMEOUT_MS=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),SHADOW_GC_AUTO=512;function shadowGit(e,t){return esm_default({baseDir:e.workTree,timeout:{block:t?.timeoutMs??GIT_TIMEOUT_MS$3}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function configureShadowGc(e){let t=shadowGit(e);await t.raw(`config`,`gc.auto`,String(SHADOW_GC_AUTO)),await t.raw(`config`,`gc.autoDetach`,`false`),await t.raw(`config`,`gc.writeCommitGraph`,`true`),await t.raw(`config`,`commitGraph.changedPaths`,`true`)}async function enumerateWipChains(e,t){let s=shadowGit(e),g;try{g=(await s.raw(`for-each-ref`,`--format=%(refname)%00%(objectname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/${t}/`)).trim().split(`
|
|
778
778
|
`).filter(Boolean)}catch{return[]}let S=[];for(let e of g){let[t=``,s=``,g=``,w=``]=e.split(`\0`),E=t.split(`/`).slice(3).join(`/`);if(!E)continue;let D=Number.parseInt(g,10);S.push({writerId:E,tipSha:s,classification:parseWriterId(E).classification,isPark:w.startsWith(`park:`),committedAtMs:Number.isFinite(D)?D*1e3:0})}return S}async function initShadowRepo(e){let t=resolveShadowDir(e),s=resolve(e,`.git/openknowledge`),g=existsSync(s),S=existsSync(t);if(g&&!S?tracedRenameSync(s,t):g&&S&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!existsSync(resolve(t,`HEAD`))){tracedMkdirSync(t,{recursive:!0}),await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$3}}).raw(`init`,`--bare`,t);let s=esm_default({timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:t});await s.raw(`config`,`--unset`,`core.bare`),await s.raw(`config`,`core.worktree`,e),await s.raw(`config`,`user.name`,`openknowledge`),await s.raw(`config`,`user.email`,`noreply@openknowledge.local`)}let w={gitDir:t,workTree:e};try{await configureShadowGc(w)}catch(e){console.warn(`[shadow-repo] failed to write gc config (non-fatal):`,e)}return await sweepLegacyShadowRefs(w),sweepOrphanedTmpIndexFiles(w),acquireLock(t,e),w}function destroyShadowRepo(e){releaseLock(e.gitDir)}async function sweepLegacyShadowRefs(e){let t=shadowGit(e),s;try{s=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
|
|
779
|
-
`).filter(e=>e.length>0)}catch{return 0}let g=[],S={server:0,"human-":0,upstream:0};for(let e of s){let t=e.split(`/`);if(t.length<4)continue;let s=t.slice(3).join(`/`);parseWriterId(s).classification===`unknown`&&(s===`server`?(g.push(e),S.server++):s.startsWith(`human-`)?(g.push(e),S[`human-`]++):s===`upstream`&&(g.push(e),S.upstream++))}if(g.length===0)return 0;for(let e of g)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let w=g.length;return incrementShadowMigrationLegacyRefsDeleted(w),console.warn(`[shadow-migration] deleted ${w} legacy refs: server=${S.server} human-=${S[`human-`]} upstream=${S.upstream}`),w}async function commitWip(e,t,s,g,S=`main`,w){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":S}},async()=>commitWipInner(e,t,s,g,S,w?.date))}async function commitWipInner(e,t,s,g,S=`main`,w){let E=resolve(e.gitDir,`index-wip-${t.id}`),D=`refs/wip/${S}/${t.id}`,O=shadowGit(e),k=s||`.`;try{try{let t=(await O.raw(`rev-parse`,`${D}^{tree}`)).trim();await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${D}:`,e),e}await O.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:E}).raw(`add`,k);let s=(await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),S=null;try{S=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,s,`-m`,g];S&&j.push(`-p`,S);let F={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w&&(F.GIT_AUTHOR_DATE=w,F.GIT_COMMITTER_DATE=w);let L=(await O.env(F).raw(...j)).trim();return await O.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let s of readdirSync(e.gitDir))if(s.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,s)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let s=resolve(e.gitDir,`index-wip-fanout-${randomUUID
|
|
779
|
+
`).filter(e=>e.length>0)}catch{return 0}let g=[],S={server:0,"human-":0,upstream:0};for(let e of s){let t=e.split(`/`);if(t.length<4)continue;let s=t.slice(3).join(`/`);parseWriterId(s).classification===`unknown`&&(s===`server`?(g.push(e),S.server++):s.startsWith(`human-`)?(g.push(e),S[`human-`]++):s===`upstream`&&(g.push(e),S.upstream++))}if(g.length===0)return 0;for(let e of g)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let w=g.length;return incrementShadowMigrationLegacyRefsDeleted(w),console.warn(`[shadow-migration] deleted ${w} legacy refs: server=${S.server} human-=${S[`human-`]} upstream=${S.upstream}`),w}async function commitWip(e,t,s,g,S=`main`,w){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":S}},async()=>commitWipInner(e,t,s,g,S,w?.date))}async function commitWipInner(e,t,s,g,S=`main`,w){let E=resolve(e.gitDir,`index-wip-${t.id}`),D=`refs/wip/${S}/${t.id}`,O=shadowGit(e),k=s||`.`;try{try{let t=(await O.raw(`rev-parse`,`${D}^{tree}`)).trim();await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${D}:`,e),e}await O.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:E}).raw(`add`,k);let s=(await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),S=null;try{S=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,s,`-m`,g];S&&j.push(`-p`,S);let F={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w&&(F.GIT_AUTHOR_DATE=w,F.GIT_COMMITTER_DATE=w);let L=(await O.env(F).raw(...j)).trim();return await O.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let s of readdirSync(e.gitDir))if(s.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,s)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let s=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),g=shadowGit(e),S=t||`.`;try{return await g.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:s}).raw(`add`,S),(await g.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:s}).raw(`write-tree`)).trim()}finally{try{rmSync(s)}catch{}}}async function commitWipFromTree(e,t,s,g,S=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":S,"shadow.tree":s.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,s,g,S))}async function commitWipFromTreeInner(e,t,s,g,S=`main`){let w=`refs/wip/${S}/${t.id}`,E=shadowGit(e),D=null;try{D=(await E.raw(`rev-parse`,w)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${w}:`,e),e}let O=[`commit-tree`,s,`-m`,g];D&&O.push(`-p`,D);let k=(await E.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...O)).trim();return await E.raw(`update-ref`,w,k),k}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`OpenKnowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,s,g,S=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":S,"shadow.new_head":g.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,s,g,S))}async function commitUpstreamImportInner(e,t,s,g,S=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(s,g)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,S)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,s,g=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${s.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,g)}async function saveInMemoryCheckpoint(e,t,s){let g=s.branch??`main`,S=shadowGit(e),w=randomUUID(),E=resolve(e.gitDir,`index-checkpoint-${w}`),D=resolve(e.gitDir,`tmp-checkpoint-blob-${w}`),O=t?`${t.replace(/\/$/,``)}/${s.docName}`:s.docName,k=Buffer.byteLength(s.contents,`utf-8`),j=formatCheckpointBodyLine(s.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:s.docName,size:k,metadata:s.metadata}:{kind:`external-change-rescue`,docName:s.docName,size:k,metadata:s.metadata}),F=`checkpoint: ${s.label}\n\n${j}`;try{tracedWriteFileSync(D,s.contents,`utf-8`);let t=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,D)).trim();await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${O}`);let w=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=(await S.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,w,`-m`,F)).trim();return await S.raw(`update-ref`,`refs/checkpoints/${g}/${k}`,k),k}finally{try{rmSync(E)}catch{}try{rmSync(D)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let s=shadowGit(e),g;try{g=await s.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let S=g.trim().split(`
|
|
780
780
|
`).filter(e=>e.length===40);if(S.length===0)return[];let w;try{w=await s.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...S)}catch{return[]}let E=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[g=``,S=``,w=``,D=``]=t.split(`\0`),O=parseCheckpoint(D);if(O?.kind!==`external-change-rescue`)continue;let k=O.docName??``,j=O.size??0;if(!k)try{let e=(await s.raw(`ls-tree`,`-r`,`--long`,g)).trim().split(`
|
|
781
781
|
`)[0];if(e){let t=e.split(/\s+/),s=4,g=3;j===0&&(j=Number(t[3]??`0`)),k=(t[4]??``).replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``}}catch{}k&&E.push({docName:k,timestamp:S,size:j,sha:g,label:w.replace(/^checkpoint:\s*/,``),incomingDiskSha:O.metadata.incomingDiskSha})}return E}const DEFAULT_CHECKPOINT_RETENTION={maxBridgeMergeLoss:50,maxExternalChangeRescue:50,maxAutoConsolidation:2,ttlMs:720*60*60*1e3};async function gcCheckpointRefs(e,t=`main`,s=DEFAULT_CHECKPOINT_RETENTION){let g={scanned:0,deletedBridgeMergeLoss:0,deletedExternalChangeRescue:0,deletedAutoConsolidation:0,retained:0},S=shadowGit(e),w;try{w=await S.raw(`for-each-ref`,`--format=%(objectname) %(refname)`,`refs/checkpoints/${t}/`)}catch{return g}let E=w.trim().split(`
|
|
782
|
-
`).map(e=>e.trim()).filter(Boolean);if(E.length===0)return g;let D=new Map,O=[];for(let e of E){let t=e.indexOf(` `);if(t<0)continue;let s=e.slice(0,t),g=e.slice(t+1);s.length===40&&(D.set(s,g),O.push(s))}if(g.scanned=O.length,O.length===0)return g;let k;try{k=await S.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%B%x1e`,...O)}catch{return g}let j=[];for(let e of k.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,g=``,S=``]=t.split(`\0`);if(!s)continue;let w=parseCheckpoint(S)?.kind??null,E=Date.parse(g);j.push({sha:s,timestamp:Number.isFinite(E)?E:0,kind:w})}let F={"bridge-merge-loss":[],"external-change-rescue":[],"auto-consolidation":[]},L=0;for(let e of j){if(e.kind===null){L++;continue}F[e.kind].push(e)}let B=Date.now(),H=[],q=(e,t,S,w=!0)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let E=0;E<e.length;E++){let O=e[E];if(!O)continue;let k=E>=t,j=w&&s.ttlMs>0&&O.timestamp>0&&B-O.timestamp>s.ttlMs;if(k||j){let e=D.get(O.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`),q(F[`auto-consolidation`],s.maxAutoConsolidation,`deletedAutoConsolidation`,!1);for(let e of H)try{await S.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[checkpoint-gc] failed to delete`,e,t)}return g.retained=L+(g.scanned-H.length-L),g}async function parkBranch(e,t,s,g,S){return g.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":S??``,"shadow.doc_count":g.length}},async()=>parkBranchInner(e,t,s,g,S))}async function parkBranchInner(e,t,s,g,S){let w=shadowGit(e),E=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),D=`refs/wip/${t}/${s}`,O=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of g){tracedWriteFileSync(O,t.markdown,`utf-8`);let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${s},${t.docName}`),tracedWriteFileSync(O,t.diskSnapshot,`utf-8`);let g=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${g},.park-base/${t.docName}`)}let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=null;try{k=(await w.raw(`rev-parse`,D)).trim()}catch{}let j={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:g.map(e=>e.docName)},F=[`commit-tree`,s,`-m`,`${formatParkSubject(t,S??t)}\n\n${formatOkActor(j)}`];k&&F.push(`-p`,k);let L=(await w.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await w.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}try{rmSync(O)}catch{}}}async function readParkedState(e,t,s,g){let S=shadowGit(e),w=`refs/wip/${t}/${s}`,E;try{E=(await S.raw(`rev-parse`,w)).trim()}catch{return null}try{return(await S.raw(`log`,`-1`,`--format=%s`,E)).trim().startsWith(`park:`)?{markdown:(await S.raw(`show`,`${E}:${g}`)).trim(),diskSnapshot:(await S.raw(`show`,`${E}:.park-base/${g}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${g} from ${w}:`,e),e}}async function saveVersion(e,t,s,g=`main`,S,w){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length,"shadow.checkpoint_kind":w?.checkpointKind?`auto-consolidation`:`user`}},async()=>saveVersionInner(e,t,s,g,S,w))}async function saveVersionInner(e,t,s,g=`main`,S,w){let E=shadowGit(e,w?.timeoutMs?{timeoutMs:w.timeoutMs}:void 0),D=t||`.`,O=resolve(e.gitDir,`index-checkpoint-${randomUUID$1()}`);try{await E.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:O}).raw(`add`,D);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),k=w?.includeUpstream===!1?s:[...s,GIT_UPSTREAM_WRITER],j=[],F=new Map;for(let e of k)try{let t=(await E.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();j.push(t),F.set(e.id,t)}catch{}let L=[...new Set(j)];try{let e=(await E.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim();e&&!L.includes(e)&&L.push(e)}catch{}let B={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},H=`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(B)}`;w?.checkpointKind&&(H+=`\n${formatCheckpointBodyLine({kind:`auto-consolidation`,docName:null,size:null,metadata:{foldedRefs:w.checkpointKind.foldedRefs,trigger:w.checkpointKind.trigger}})}`);let q=[`commit-tree`,t,`-m`,H];for(let e of L)q.push(`-p`,e);let ee={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w?.date&&(ee.GIT_AUTHOR_DATE=w.date,ee.GIT_COMMITTER_DATE=w.date);let J=(await E.env(ee).raw(...q)).trim(),Y=`refs/checkpoints/${g}/${J}`;return await E.raw(`update-ref`,Y,J),await resetFoldedWipRefs(E,g,k,F),{checkpointRef:Y}}finally{try{rmSync(O)}catch{}}}async function resetFoldedWipRefs(e,t,s,g){for(let S of s){let s=`refs/wip/${t}/${S.id}`,w=g.get(S.id);if(w!==void 0)try{await e.raw(`update-ref`,`-d`,s,w)}catch{}}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyDiskContentToDoc(e,t,s,g,S){composeAndWriteRawBody(e,t,`file-watcher`,s&&g?{resolveEmbed:s,resolveSize:S,sourcePath:g}:void 0)}function applyExternalChange(e,t,s,g,S){if(isSystemDoc(t)||isConfigDoc(t))return;let w=e.documents.get(t);if(!w)return;let E=stripFrontmatter(w.getText(`source`).toString()).frontmatter,{frontmatter:D}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}E!==D&&recordFrontmatterEditSurface(`file-watcher`),recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,s)}function createExternalChangeHandler(e,t,s){return async(g,S)=>{try{applyExternalChange(e,g,S,t,s),getLogger(`file-watcher`).info({docName:g},`applied external change`)}catch(e){if(e instanceof BridgeInvariantViolationError||e instanceof BridgeMergeContentLossError)throw e;incrementExternalChangeHandlerErrors(),console.error(`[file-watcher] Failed to apply external change for ${g}:`,e)}}}const NOT_RECONCILED={reconciled:!1,baseBytes:0,diskBytes:0};function serializeYDocSource(e){let{frontmatter:t,body:s}=stripFrontmatter(e.getText(`source`).toString());return prependFrontmatter(t,s)}function reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(t))return NOT_RECONCILED;let S=e.documents.get(t);if(S&&isDocInConflict(S))return NOT_RECONCILED;let w=getReconciledBase(t);if(w===void 0)return NOT_RECONCILED;let E;try{let e=safeContentPath(t,s);if(!existsSync(e))return NOT_RECONCILED;E=realpathSync(e)}catch{return NOT_RECONCILED}if(!isWithinContentDir(E,s))return getLogger(`reconcile`).warn({docName:t,canonical:E,contentDir:s},`[reconcile] symlink-escape on disk read for ${t}; skipping reconcile`),NOT_RECONCILED;let D;try{D=readFileSync(E,`utf-8`)}catch(e){let s=e?.code;return s!==`ENOENT`&&getLogger(`reconcile`).warn({docName:t,canonical:E,code:s},`[reconcile] disk read failed for ${t} (${s??`unknown`}); skipping reconcile`),NOT_RECONCILED}if(normalizeBridge(D)===normalizeBridge(w))return NOT_RECONCILED;let O=peekInFlightFlush(t);if(O!==void 0){if(normalizeBridge(D)===O)return incrementReconcileOwnFlushSkips(),getLogger(`reconcile`).debug({docName:t,diskBytes:D.length},`[reconcile] disk matches own in-flight flush for ${t}; skipping reconcile`),NOT_RECONCILED;incrementReconcileInFlightFallthroughs(),getLogger(`reconcile`).warn({docName:t,diskBytes:D.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${t}; falling through to merge`)}if(!S)return NOT_RECONCILED;let k=reconcile({docName:t,base:w,ours:serializeYDocSource(S),theirs:D});switch(getLogger(`reconcile`).info({docName:t,result:k.kind,baseBytes:w.length,diskBytes:D.length},`[reconcile] before-agent-write ${t} result=${k.kind}`),k.kind){case`noop`:return NOT_RECONCILED;case`conflicts`:case`refused`:{let e=S.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,k.kind===`refused`?k.reason:`reconcile-conflicts`),NOT_RECONCILED}case`clean`:case`merged`:return applyExternalChange(e,t,k.kind===`clean`?D:k.newContent,g),k.kind===`merged`&&setReconciledBase(t,D),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`),mergeOutcome:k.kind}}}function splitFrontmatterLines(e){return e?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}function toPosix(e){return e.replace(/\\/g,`/`)}function isWithinDir(e,t){let s=toPosix(e),g=toPosix(t);return s===g||s.startsWith(`${g}/`)}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function derivePageMeta(e,t){return{title:extractPageTitle(e,t),icon:extractPageIcon(e)}}function markdownIndexView(e){let t=new Map;for(let[s,g]of e)g.kind===`markdown`&&t.set(s,g);return t}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(toPosix(relative(t,e)))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=toPosix(relative(t,g.path));if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E,D){let O=D??new Set;try{let D=await readdir(e,{withFileTypes:!0});for(let k of D){let D=join(e,k.name),j;try{j=await lstat(D)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${D}, skipping:`,e);continue}if(j.isSymbolicLink()){let e;try{e=await realpath(D)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${D}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${D}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${D} → ${e}, skipping`);continue}try{let j=await stat$1(e);if(O.has(j.ino)){if(j.isFile()&&isSupportedDocFile(k.name)){let s=pathToDocName(D,t),S=pathToDocName(e,t);w.set(s,S);let E=g.get(S);E&&!E.aliases.includes(s)&&E.aliases.push(s)}else if(j.isDirectory()){let g=contentRelativePath(t,D);(!s||g&&!s.isDirExcluded(g))&&E.set(pathToDocName(D,t),pathToDocName(e,t))}continue}if(O.add(j.ino),j.isDirectory()){let k=contentRelativePath(t,D);if(s&&(!k||s.isDirExcluded(k)))continue;E.set(pathToDocName(D,t),pathToDocName(e,t)),await seedLastKnownHashes(e,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(s){let g=toPosix(relative(t,e));if(s.isExcluded(g))continue}let S=pathToDocName(D,t),E=pathToDocName(e,t);w.set(S,E);try{let t=await readFile$1(e,`utf-8`),s=contentHash(t);lastKnownHash.set(e,s);let w=extractDocExtension(e);if(w){let e=registerDocExtension(E,w);if(e.shadowed&&(console.warn(`[file-watcher] docName "${E}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(E,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[S],kind:`markdown`,...derivePageMeta(t,E)})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}else if(j.isFile()){if(s){let g=toPosix(relative(t,e));if(s.isPathIgnored(g))continue}let S=pathToDocName(D,t);if(isSystemDoc(S)||isConfigDoc(S))continue;g.set(S,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[],kind:`file`})}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(j.isDirectory()){let e=contentRelativePath(t,D);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,D,j),await seedLastKnownHashes(D,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isExcluded(e))continue}try{let e=await readFile$1(D,`utf-8`);lastKnownHash.set(D,contentHash(e));let s=pathToDocName(D,t),S=extractDocExtension(D);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`markdown`,...derivePageMeta(e,s)})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${D}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${D}:`,e)}}else if(j.isFile()){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isPathIgnored(e))continue}let e=pathToDocName(D,t);if(isSystemDoc(e)||isConfigDoc(e))continue;g.set(e,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`file`})}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let s=e.relativePath;if(isSystemDoc(s)||isConfigDoc(s))return;if(e.kind===`file-delete`){let e=t.get(s);e&&e.kind===`file`&&t.delete(s);return}let g=t.get(s);if(g&&g.kind===`markdown`)return;t.set(s,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:e.inode||g?.inode||0,aliases:g?.aliases??[],kind:`file`});return}if(!isReservedForUserTree(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&®isterDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,s)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&®isterDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,e.newDocName)});break}default:assertNeverDiskEvent(e)}}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[];for(let w of e){let e=contentRelativePath(t,w.path);if(!e)continue;if(w.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:w.path,relativePath:e});continue}let E;try{E=lstatSync(w.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${w.path} (${t})`);continue}let D=null,O=w.path;if(E.isDirectory())D=E;else if(E.isSymbolicLink())try{if(O=realpathSync(w.path),!isWithinContentDir(O,t))continue;let e=statSync(O);e.isDirectory()&&(D=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${w.path} (${t})`),D=null}if(!D||s?.isDirExcluded(e))continue;let k=g.has(e);upsertFolderIndexEntry(g,t,w.path,D,O),k||(S.push({kind:`folder-create`,path:w.path,relativePath:e}),scanForUntrackedSubfolders(O,t,s,g,S))}return S}function scanForUntrackedSubfolders(e,t,s,g,S){let w=[e];for(;w.length>0;){let e=w.shift();if(e===void 0)continue;let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let D of E){if(!D.isDirectory())continue;let E=join(e,D.name),O=contentRelativePath(t,E);if(!O||s?.isDirExcluded(O))continue;let k;try{k=lstatSync(E)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${E} (${t})`);continue}k.isDirectory()&&(g.has(O)||(upsertFolderIndexEntry(g,t,E,k),S.push({kind:`folder-create`,path:E,relativePath:O})),w.push(E))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),O=D.filter(e=>isSupportedDocFile(e.path)),k=D.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),j=D.filter(e=>!isSupportedDocFile(e.path)),F=updateFolderIndexFromRawEvents(D,t,s,S);if(O.length===0&&k.length===0&&F.length===0&&j.length===0)return;let L=O.length>0?await classifyEvents(O,t,s,E):[];for(let e of L){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of F)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of k){if(s){let g=toPosix(relative(t,e.path));if(s.isExcluded(g))continue}let g=toPosix(relative(t,e.path));await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}for(let e of j){let S=toPosix(relative(t,e.path));if(s?.isPathIgnored(S)||isSystemDoc(S)||isConfigDoc(S))continue;if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:S};updateFileIndex(t,g),await w(t);continue}let E;try{E=lstatSync(e.path),E.isSymbolicLink()&&(E=statSync(e.path))}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] file-event lstat failed for ${e.path} (${s})`);continue}if(!E.isFile())continue;let D=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)}:{kind:`file-update`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)};updateFileIndex(D,g),await w(D)}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w,E){let D;try{D=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let O=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await D.subscribe(e,async(D,O)=>{if(D){console.error(`[file-watcher]`,D);return}try{await handleRawEvents(O.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w),E()}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},O)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w,E){let{watch:D}=await import(`./chokidar-D1eNAlbX.mjs`),O=D(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=toPosix(relative(e,s));return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});O.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let k=50,j=[],F=null;function L(D,O){j.push({type:D,path:O}),F||=setTimeout(()=>{let D=j;j=[],F=null,handleRawEvents(D,e,t,s,g,S,w).then(E).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return O.on(`add`,e=>L(`create`,e)),O.on(`change`,e=>L(`update`,e)),O.on(`unlink`,e=>L(`delete`,e)),O.on(`addDir`,e=>L(`create`,e)),O.on(`unlinkDir`,e=>L(`delete`,e)),{unsubscribe:()=>(F&&(clearTimeout(F),F=null,j=[]),O.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map,D=new Map,O=0,k=null,j=-1,F=()=>{O++};await seedLastKnownHashes(g,g,s,S,w,E,D),F();let L=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),B,H;try{let e=await startParcelWatcher(g,s,S,w,t,E,F);e?(B=e,H=`parcel`):(B=await startChokidarWatcher(g,s,S,w,t,E,F),H=`chokidar`)}catch(e){throw clearInterval(L),e}let q=B.unsubscribe.bind(B);return getLogger(`file-watcher`).info({contentDir:g,backend:H},`watching for external .md changes`),{async unsubscribe(){return clearInterval(L),writeTracker.clear(),lastKnownHash.clear(),q()},getFileIndex(){return k&&j===O?k:(k=markdownIndexView(S),j=O,k)},getAllFilesIndex(){return S},getFileIndexGeneration(){return O},getFolderIndex(){return w},getAliasMap(){return E},getFolderAliasIndex(){return D},mutateFileIndex(e){updateFileIndex(e,S),F()},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=toPosix(relative(g,w.canonicalPath));(w.kind===`file`?s.isPathIgnored(E):s.isExcluded(E))&&(S.delete(t),e++)}return e>0&&F(),e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},async rescanFromDisk(){await seedLastKnownHashes(g,g,s,S,w,E,D),F()}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}const log$16=getLogger(`managed-artifact-persistence`);function homeFor(e){return e.homedirOverride??homedir()}function managedArtifactContributorAttribution(e){let t=parseManagedArtifactName(e);if(t===null)return null;if(t.kind===`skill`)return t.scope===`project`?{docKey:`${SKILL_CONTENT_ROOT}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}:null;let s=t.folder.replace(/\/$/,``),g=`${s?`${s}/`:``}.ok/templates/${t.name}`;return{docKey:g,subject:`template-edit: ${g}.md`}}function managedArtifactTimelinePaths(e){let t=parseManagedArtifactName(e);if(!t)return{managed:!1};let s=managedArtifactContributorAttribution(e);if(!s)return{managed:!0,versioned:!1};let g=t.kind===`skill`?`${s.docKey}/SKILL.md`:`${s.docKey}.md`;return{managed:!0,versioned:!0,docKey:s.docKey,filePath:g}}function managedArtifactSkillsRoots(e){return[resolve(homeFor(e),`.ok`,`skills`)]}function managedArtifactAbsPath(e,t){let s=parseManagedArtifactName(e);if(s===null)throw Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${e}`);if(s.kind===`template`)return templateAbsPath(s.folder,s.name,t,e);if(!SKILL_NAME_REGEX.test(s.name)||s.name.length>64)throw Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(s.name)}`);let g=resolve(s.scope===`global`?homeFor(t):t.projectDir,`.ok`,`skills`),S=resolve(g,s.name,`SKILL.md`);if(!S.startsWith(g+sep))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return S}function normalizeTemplateFolder(e){return e.replace(/^\/+/,``).replace(/\/+$/,``)}function templateAbsPath(e,t,s,g){if(!TEMPLATE_NAME_REGEX.test(t)||t.length>64)throw Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(t)}`);let S=normalizeTemplateFolder(e);if(S.split(`/`).includes(`..`))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let w=resolve(s.projectDir),E=S?resolve(w,S):w;if(E!==w&&!E.startsWith(w+sep))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let D=resolve(E,`.ok`,`templates`),O=resolve(D,`${t}.md`);if(!O.startsWith(D+sep))throw Error(`managedArtifactAbsPath: path escape for ${g}`);return O}function managedArtifactDocNameForPath(e,t){let s=resolve(e);if(s.endsWith(`${sep}SKILL.md`)){let e=[[resolve(homeFor(t),`.ok`,`skills`),`global`]];for(let[t,g]of e){if(!s.startsWith(t+sep))continue;let e=s.slice(t.length+1).split(sep);if(e.length!==2||e[1]!==`SKILL.md`)continue;let S=e[0];if(!(!SKILL_NAME_REGEX.test(S)||S.length>64))return`${MANAGED_ARTIFACT_PREFIX_SKILL}${g}/${S}`}return null}if(s.endsWith(`.md`)){let e=resolve(t.projectDir);if(s!==e&&!s.startsWith(e+sep))return null;let g=s===e?``:s.slice(e.length+1),S=`.ok${sep}templates${sep}`,w=g.indexOf(S);if(w<0||w>0&&g[w-1]!==sep)return null;let E=g.slice(w+S.length);if(E.includes(sep)||!E.endsWith(`.md`))return null;let D=E.slice(0,-3);if(!TEMPLATE_NAME_REGEX.test(D)||D.length>64)return null;let O=w===0?``:g.slice(0,w-1),k=O?O.split(sep).map(e=>encodeURIComponent(e)).join(`/`):``;return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${k?`${k}/`:``}${encodeURIComponent(D)}`}return null}function loadManagedArtifactDoc(e,t,s){let g=parseManagedArtifactName(t);if(g?.kind===`skill`&&g.scope===`project`||e.getXmlFragment(`default`).length>0)return;let S=managedArtifactAbsPath(t,s);if(!existsSync(S))return;let w;try{w=readFileSync(S,`utf-8`)}catch(e){log$16.warn({documentName:t,err:e.message},`load: could not read; seeding empty`);return}e.transact(()=>{applyDiskContentToDoc(e,w,void 0,t),e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),s.setReconciledBase(t,w),s.lkgCache.set(t,w)}async function storeManagedArtifactDoc(e,t,s,g){let S=parseManagedArtifactName(t);if(S?.kind===`skill`&&S.scope===`project`||s===FILE_WATCHER_ORIGIN)return`no-op`;let w=e.getText(`source`).toString(),E=g.lkgCache.get(t);if(w===E)return`no-op`;let D=managedArtifactAbsPath(t,g);try{return await tracedMkdir(resolve(D,`..`),{recursive:!0}),await withFileLock(`${D}.lock`,async()=>{if(existsSync(D)){let s=null;try{s=readFileSync(D,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$16.warn({documentName:t,err:e.message},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==E&&s!==w)return e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(D,w,{fs:tracedAtomicFs}),g.lkgCache.set(t,w),g.setReconciledBase(t,w),`persisted`})}catch(e){return e instanceof FileLockTimeoutError?(log$16.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(log$16.warn({documentName:t,err:e.message},`store: write failed`),`write-failed`)}}function applyExternalManagedArtifactChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);return S!==void 0&&S===s?`no-op`:(e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`applied`)}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
782
|
+
`).map(e=>e.trim()).filter(Boolean);if(E.length===0)return g;let D=new Map,O=[];for(let e of E){let t=e.indexOf(` `);if(t<0)continue;let s=e.slice(0,t),g=e.slice(t+1);s.length===40&&(D.set(s,g),O.push(s))}if(g.scanned=O.length,O.length===0)return g;let k;try{k=await S.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%B%x1e`,...O)}catch{return g}let j=[];for(let e of k.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,g=``,S=``]=t.split(`\0`);if(!s)continue;let w=parseCheckpoint(S)?.kind??null,E=Date.parse(g);j.push({sha:s,timestamp:Number.isFinite(E)?E:0,kind:w})}let F={"bridge-merge-loss":[],"external-change-rescue":[],"auto-consolidation":[]},L=0;for(let e of j){if(e.kind===null){L++;continue}F[e.kind].push(e)}let B=Date.now(),H=[],q=(e,t,S,w=!0)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let E=0;E<e.length;E++){let O=e[E];if(!O)continue;let k=E>=t,j=w&&s.ttlMs>0&&O.timestamp>0&&B-O.timestamp>s.ttlMs;if(k||j){let e=D.get(O.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`),q(F[`auto-consolidation`],s.maxAutoConsolidation,`deletedAutoConsolidation`,!1);for(let e of H)try{await S.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[checkpoint-gc] failed to delete`,e,t)}return g.retained=L+(g.scanned-H.length-L),g}async function parkBranch(e,t,s,g,S){return g.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":S??``,"shadow.doc_count":g.length}},async()=>parkBranchInner(e,t,s,g,S))}async function parkBranchInner(e,t,s,g,S){let w=shadowGit(e),E=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),D=`refs/wip/${t}/${s}`,O=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of g){tracedWriteFileSync(O,t.markdown,`utf-8`);let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${s},${t.docName}`),tracedWriteFileSync(O,t.diskSnapshot,`utf-8`);let g=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${g},.park-base/${t.docName}`)}let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=null;try{k=(await w.raw(`rev-parse`,D)).trim()}catch{}let j={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:g.map(e=>e.docName)},F=[`commit-tree`,s,`-m`,`${formatParkSubject(t,S??t)}\n\n${formatOkActor(j)}`];k&&F.push(`-p`,k);let L=(await w.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await w.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}try{rmSync(O)}catch{}}}async function readParkedState(e,t,s,g){let S=shadowGit(e),w=`refs/wip/${t}/${s}`,E;try{E=(await S.raw(`rev-parse`,w)).trim()}catch{return null}try{return(await S.raw(`log`,`-1`,`--format=%s`,E)).trim().startsWith(`park:`)?{markdown:(await S.raw(`show`,`${E}:${g}`)).trim(),diskSnapshot:(await S.raw(`show`,`${E}:.park-base/${g}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${g} from ${w}:`,e),e}}async function saveVersion(e,t,s,g=`main`,S,w){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length,"shadow.checkpoint_kind":w?.checkpointKind?`auto-consolidation`:`user`}},async()=>saveVersionInner(e,t,s,g,S,w))}async function saveVersionInner(e,t,s,g=`main`,S,w){let E=shadowGit(e,w?.timeoutMs?{timeoutMs:w.timeoutMs}:void 0),D=t||`.`,O=resolve(e.gitDir,`index-checkpoint-${randomUUID()}`);try{await E.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:O}).raw(`add`,D);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),k=w?.includeUpstream===!1?s:[...s,GIT_UPSTREAM_WRITER],j=[],F=new Map;for(let e of k)try{let t=(await E.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();j.push(t),F.set(e.id,t)}catch{}let L=[...new Set(j)];try{let e=(await E.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim();e&&!L.includes(e)&&L.push(e)}catch{}let B={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},H=`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(B)}`;w?.checkpointKind&&(H+=`\n${formatCheckpointBodyLine({kind:`auto-consolidation`,docName:null,size:null,metadata:{foldedRefs:w.checkpointKind.foldedRefs,trigger:w.checkpointKind.trigger}})}`);let q=[`commit-tree`,t,`-m`,H];for(let e of L)q.push(`-p`,e);let ee={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w?.date&&(ee.GIT_AUTHOR_DATE=w.date,ee.GIT_COMMITTER_DATE=w.date);let J=(await E.env(ee).raw(...q)).trim(),Y=`refs/checkpoints/${g}/${J}`;return await E.raw(`update-ref`,Y,J),await resetFoldedWipRefs(E,g,k,F),{checkpointRef:Y}}finally{try{rmSync(O)}catch{}}}async function resetFoldedWipRefs(e,t,s,g){for(let S of s){let s=`refs/wip/${t}/${S.id}`,w=g.get(S.id);if(w!==void 0)try{await e.raw(`update-ref`,`-d`,s,w)}catch{}}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyDiskContentToDoc(e,t,s,g,S){composeAndWriteRawBody(e,t,`file-watcher`,s&&g?{resolveEmbed:s,resolveSize:S,sourcePath:g}:void 0)}function applyExternalChange(e,t,s,g,S){if(isSystemDoc(t)||isConfigDoc(t))return;let w=e.documents.get(t);if(!w)return;let E=stripFrontmatter(w.getText(`source`).toString()).frontmatter,{frontmatter:D}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}E!==D&&recordFrontmatterEditSurface(`file-watcher`),recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,s)}function createExternalChangeHandler(e,t,s){return async(g,S)=>{try{applyExternalChange(e,g,S,t,s),getLogger(`file-watcher`).info({docName:g},`applied external change`)}catch(e){if(e instanceof BridgeInvariantViolationError||e instanceof BridgeMergeContentLossError)throw e;incrementExternalChangeHandlerErrors(),console.error(`[file-watcher] Failed to apply external change for ${g}:`,e)}}}const NOT_RECONCILED={reconciled:!1,baseBytes:0,diskBytes:0};function serializeYDocSource(e){let{frontmatter:t,body:s}=stripFrontmatter(e.getText(`source`).toString());return prependFrontmatter(t,s)}function reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(t))return NOT_RECONCILED;let S=e.documents.get(t);if(S&&isDocInConflict(S))return NOT_RECONCILED;let w=getReconciledBase(t);if(w===void 0)return NOT_RECONCILED;let E;try{let e=safeContentPath(t,s);if(!existsSync(e))return NOT_RECONCILED;E=realpathSync(e)}catch{return NOT_RECONCILED}if(!isWithinContentDir(E,s))return getLogger(`reconcile`).warn({docName:t,canonical:E,contentDir:s},`[reconcile] symlink-escape on disk read for ${t}; skipping reconcile`),NOT_RECONCILED;let D;try{D=readFileSync(E,`utf-8`)}catch(e){let s=e?.code;return s!==`ENOENT`&&getLogger(`reconcile`).warn({docName:t,canonical:E,code:s},`[reconcile] disk read failed for ${t} (${s??`unknown`}); skipping reconcile`),NOT_RECONCILED}if(normalizeBridge(D)===normalizeBridge(w))return NOT_RECONCILED;let O=peekInFlightFlush(t);if(O!==void 0){if(normalizeBridge(D)===O)return incrementReconcileOwnFlushSkips(),getLogger(`reconcile`).debug({docName:t,diskBytes:D.length},`[reconcile] disk matches own in-flight flush for ${t}; skipping reconcile`),NOT_RECONCILED;incrementReconcileInFlightFallthroughs(),getLogger(`reconcile`).warn({docName:t,diskBytes:D.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${t}; falling through to merge`)}if(!S)return NOT_RECONCILED;let k=reconcile({docName:t,base:w,ours:serializeYDocSource(S),theirs:D});switch(getLogger(`reconcile`).info({docName:t,result:k.kind,baseBytes:w.length,diskBytes:D.length},`[reconcile] before-agent-write ${t} result=${k.kind}`),k.kind){case`noop`:return NOT_RECONCILED;case`conflicts`:case`refused`:{let e=S.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,k.kind===`refused`?k.reason:`reconcile-conflicts`),NOT_RECONCILED}case`clean`:case`merged`:return applyExternalChange(e,t,k.kind===`clean`?D:k.newContent,g),k.kind===`merged`&&setReconciledBase(t,D),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`),mergeOutcome:k.kind}}}function splitFrontmatterLines(e){return e?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}function toPosix(e){return e.replace(/\\/g,`/`)}function isWithinDir(e,t){let s=toPosix(e),g=toPosix(t);return s===g||s.startsWith(`${g}/`)}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function derivePageMeta(e,t){return{title:extractPageTitle(e,t),icon:extractPageIcon(e)}}function markdownIndexView(e){let t=new Map;for(let[s,g]of e)g.kind===`markdown`&&t.set(s,g);return t}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(toPosix(relative(t,e)))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=toPosix(relative(t,g.path));if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E,D){let O=D??new Set;try{let D=await readdir(e,{withFileTypes:!0});for(let k of D){let D=join(e,k.name),j;try{j=await lstat(D)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${D}, skipping:`,e);continue}if(j.isSymbolicLink()){let e;try{e=await realpath(D)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${D}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${D}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${D} → ${e}, skipping`);continue}try{let j=await stat$1(e);if(O.has(j.ino)){if(j.isFile()&&isSupportedDocFile(k.name)){let s=pathToDocName(D,t),S=pathToDocName(e,t);w.set(s,S);let E=g.get(S);E&&!E.aliases.includes(s)&&E.aliases.push(s)}else if(j.isDirectory()){let g=contentRelativePath(t,D);(!s||g&&!s.isDirExcluded(g))&&E.set(pathToDocName(D,t),pathToDocName(e,t))}continue}if(O.add(j.ino),j.isDirectory()){let k=contentRelativePath(t,D);if(s&&(!k||s.isDirExcluded(k)))continue;E.set(pathToDocName(D,t),pathToDocName(e,t)),await seedLastKnownHashes(e,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(s){let g=toPosix(relative(t,e));if(s.isExcluded(g))continue}let S=pathToDocName(D,t),E=pathToDocName(e,t);w.set(S,E);try{let t=await readFile$1(e,`utf-8`),s=contentHash(t);lastKnownHash.set(e,s);let w=extractDocExtension(e);if(w){let e=registerDocExtension(E,w);if(e.shadowed&&(console.warn(`[file-watcher] docName "${E}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(E,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[S],kind:`markdown`,...derivePageMeta(t,E)})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}else if(j.isFile()){if(s){let g=toPosix(relative(t,e));if(s.isPathIgnored(g))continue}let S=pathToDocName(D,t);if(isSystemDoc(S)||isConfigDoc(S))continue;g.set(S,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[],kind:`file`})}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(j.isDirectory()){let e=contentRelativePath(t,D);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,D,j),await seedLastKnownHashes(D,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isExcluded(e))continue}try{let e=await readFile$1(D,`utf-8`);lastKnownHash.set(D,contentHash(e));let s=pathToDocName(D,t),S=extractDocExtension(D);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`markdown`,...derivePageMeta(e,s)})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${D}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${D}:`,e)}}else if(j.isFile()){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isPathIgnored(e))continue}let e=pathToDocName(D,t);if(isSystemDoc(e)||isConfigDoc(e))continue;g.set(e,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`file`})}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let s=e.relativePath;if(isSystemDoc(s)||isConfigDoc(s))return;if(e.kind===`file-delete`){let e=t.get(s);e&&e.kind===`file`&&t.delete(s);return}let g=t.get(s);if(g&&g.kind===`markdown`)return;t.set(s,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:e.inode||g?.inode||0,aliases:g?.aliases??[],kind:`file`});return}if(!isReservedForUserTree(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&®isterDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,s)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&®isterDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,e.newDocName)});break}default:assertNeverDiskEvent(e)}}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[];for(let w of e){let e=contentRelativePath(t,w.path);if(!e)continue;if(w.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:w.path,relativePath:e});continue}let E;try{E=lstatSync(w.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${w.path} (${t})`);continue}let D=null,O=w.path;if(E.isDirectory())D=E;else if(E.isSymbolicLink())try{if(O=realpathSync(w.path),!isWithinContentDir(O,t))continue;let e=statSync(O);e.isDirectory()&&(D=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${w.path} (${t})`),D=null}if(!D||s?.isDirExcluded(e))continue;let k=g.has(e);upsertFolderIndexEntry(g,t,w.path,D,O),k||(S.push({kind:`folder-create`,path:w.path,relativePath:e}),scanForUntrackedSubfolders(O,t,s,g,S))}return S}function scanForUntrackedSubfolders(e,t,s,g,S){let w=[e];for(;w.length>0;){let e=w.shift();if(e===void 0)continue;let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let D of E){if(!D.isDirectory())continue;let E=join(e,D.name),O=contentRelativePath(t,E);if(!O||s?.isDirExcluded(O))continue;let k;try{k=lstatSync(E)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${E} (${t})`);continue}k.isDirectory()&&(g.has(O)||(upsertFolderIndexEntry(g,t,E,k),S.push({kind:`folder-create`,path:E,relativePath:O})),w.push(E))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),O=D.filter(e=>isSupportedDocFile(e.path)),k=D.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),j=D.filter(e=>!isSupportedDocFile(e.path)),F=updateFolderIndexFromRawEvents(D,t,s,S);if(O.length===0&&k.length===0&&F.length===0&&j.length===0)return;let L=O.length>0?await classifyEvents(O,t,s,E):[];for(let e of L){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of F)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of k){if(s){let g=toPosix(relative(t,e.path));if(s.isExcluded(g))continue}let g=toPosix(relative(t,e.path));await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}for(let e of j){let S=toPosix(relative(t,e.path));if(s?.isPathIgnored(S)||isSystemDoc(S)||isConfigDoc(S))continue;if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:S};updateFileIndex(t,g),await w(t);continue}let E;try{E=lstatSync(e.path),E.isSymbolicLink()&&(E=statSync(e.path))}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] file-event lstat failed for ${e.path} (${s})`);continue}if(!E.isFile())continue;let D=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)}:{kind:`file-update`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)};updateFileIndex(D,g),await w(D)}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w,E){let D;try{D=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let O=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await D.subscribe(e,async(D,O)=>{if(D){console.error(`[file-watcher]`,D);return}try{await handleRawEvents(O.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w),E()}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},O)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w,E){let{watch:D}=await import(`./chokidar-D1eNAlbX.mjs`),O=D(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=toPosix(relative(e,s));return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});O.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let k=50,j=[],F=null;function L(D,O){j.push({type:D,path:O}),F||=setTimeout(()=>{let D=j;j=[],F=null,handleRawEvents(D,e,t,s,g,S,w).then(E).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return O.on(`add`,e=>L(`create`,e)),O.on(`change`,e=>L(`update`,e)),O.on(`unlink`,e=>L(`delete`,e)),O.on(`addDir`,e=>L(`create`,e)),O.on(`unlinkDir`,e=>L(`delete`,e)),{unsubscribe:()=>(F&&(clearTimeout(F),F=null,j=[]),O.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map,D=new Map,O=0,k=null,j=-1,F=()=>{O++};await seedLastKnownHashes(g,g,s,S,w,E,D),F();let L=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),B,H;try{let e=await startParcelWatcher(g,s,S,w,t,E,F);e?(B=e,H=`parcel`):(B=await startChokidarWatcher(g,s,S,w,t,E,F),H=`chokidar`)}catch(e){throw clearInterval(L),e}let q=B.unsubscribe.bind(B);return getLogger(`file-watcher`).info({contentDir:g,backend:H},`watching for external .md changes`),{async unsubscribe(){return clearInterval(L),writeTracker.clear(),lastKnownHash.clear(),q()},getFileIndex(){return k&&j===O?k:(k=markdownIndexView(S),j=O,k)},getAllFilesIndex(){return S},getFileIndexGeneration(){return O},getFolderIndex(){return w},getAliasMap(){return E},getFolderAliasIndex(){return D},mutateFileIndex(e){updateFileIndex(e,S),F()},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=toPosix(relative(g,w.canonicalPath));(w.kind===`file`?s.isPathIgnored(E):s.isExcluded(E))&&(S.delete(t),e++)}return e>0&&F(),e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},async rescanFromDisk(){await seedLastKnownHashes(g,g,s,S,w,E,D),F()}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}const log$16=getLogger(`managed-artifact-persistence`);function homeFor(e){return e.homedirOverride??homedir()}function managedArtifactContributorAttribution(e){let t=parseManagedArtifactName(e);if(t===null)return null;if(t.kind===`skill`)return t.scope===`project`?{docKey:`${SKILL_CONTENT_ROOT}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}:null;let s=t.folder.replace(/\/$/,``),g=`${s?`${s}/`:``}.ok/templates/${t.name}`;return{docKey:g,subject:`template-edit: ${g}.md`}}function managedArtifactTimelinePaths(e){let t=parseManagedArtifactName(e);if(!t)return{managed:!1};let s=managedArtifactContributorAttribution(e);if(!s)return{managed:!0,versioned:!1};let g=t.kind===`skill`?`${s.docKey}/SKILL.md`:`${s.docKey}.md`;return{managed:!0,versioned:!0,docKey:s.docKey,filePath:g}}function managedArtifactSkillsRoots(e){return[resolve(homeFor(e),`.ok`,`skills`)]}function managedArtifactAbsPath(e,t){let s=parseManagedArtifactName(e);if(s===null)throw Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${e}`);if(s.kind===`template`)return templateAbsPath(s.folder,s.name,t,e);if(!SKILL_NAME_REGEX.test(s.name)||s.name.length>64)throw Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(s.name)}`);let g=resolve(s.scope===`global`?homeFor(t):t.projectDir,`.ok`,`skills`),S=resolve(g,s.name,`SKILL.md`);if(!S.startsWith(g+sep))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return S}function normalizeTemplateFolder(e){return e.replace(/^\/+/,``).replace(/\/+$/,``)}function templateAbsPath(e,t,s,g){if(!TEMPLATE_NAME_REGEX.test(t)||t.length>64)throw Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(t)}`);let S=normalizeTemplateFolder(e);if(S.split(`/`).includes(`..`))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let w=resolve(s.projectDir),E=S?resolve(w,S):w;if(E!==w&&!E.startsWith(w+sep))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let D=resolve(E,`.ok`,`templates`),O=resolve(D,`${t}.md`);if(!O.startsWith(D+sep))throw Error(`managedArtifactAbsPath: path escape for ${g}`);return O}function managedArtifactDocNameForPath(e,t){let s=resolve(e);if(s.endsWith(`${sep}SKILL.md`)){let e=[[resolve(homeFor(t),`.ok`,`skills`),`global`]];for(let[t,g]of e){if(!s.startsWith(t+sep))continue;let e=s.slice(t.length+1).split(sep);if(e.length!==2||e[1]!==`SKILL.md`)continue;let S=e[0];if(!(!SKILL_NAME_REGEX.test(S)||S.length>64))return`${MANAGED_ARTIFACT_PREFIX_SKILL}${g}/${S}`}return null}if(s.endsWith(`.md`)){let e=resolve(t.projectDir);if(s!==e&&!s.startsWith(e+sep))return null;let g=s===e?``:s.slice(e.length+1),S=`.ok${sep}templates${sep}`,w=g.indexOf(S);if(w<0||w>0&&g[w-1]!==sep)return null;let E=g.slice(w+S.length);if(E.includes(sep)||!E.endsWith(`.md`))return null;let D=E.slice(0,-3);if(!TEMPLATE_NAME_REGEX.test(D)||D.length>64)return null;let O=w===0?``:g.slice(0,w-1),k=O?O.split(sep).map(e=>encodeURIComponent(e)).join(`/`):``;return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${k?`${k}/`:``}${encodeURIComponent(D)}`}return null}function loadManagedArtifactDoc(e,t,s){let g=parseManagedArtifactName(t);if(g?.kind===`skill`&&g.scope===`project`||e.getXmlFragment(`default`).length>0)return;let S=managedArtifactAbsPath(t,s);if(!existsSync(S))return;let w;try{w=readFileSync(S,`utf-8`)}catch(e){log$16.warn({documentName:t,err:e.message},`load: could not read; seeding empty`);return}e.transact(()=>{applyDiskContentToDoc(e,w,void 0,t),e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),s.setReconciledBase(t,w),s.lkgCache.set(t,w)}async function storeManagedArtifactDoc(e,t,s,g){let S=parseManagedArtifactName(t);if(S?.kind===`skill`&&S.scope===`project`||s===FILE_WATCHER_ORIGIN)return`no-op`;let w=e.getText(`source`).toString(),E=g.lkgCache.get(t);if(w===E)return`no-op`;let D=managedArtifactAbsPath(t,g);try{return await tracedMkdir(resolve(D,`..`),{recursive:!0}),await withFileLock(`${D}.lock`,async()=>{if(existsSync(D)){let s=null;try{s=readFileSync(D,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$16.warn({documentName:t,err:e.message},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==E&&s!==w)return e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(D,w,{fs:tracedAtomicFs}),g.lkgCache.set(t,w),g.setReconciledBase(t,w),`persisted`})}catch(e){return e instanceof FileLockTimeoutError?(log$16.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(log$16.warn({documentName:t,err:e.message},`store: write failed`),`write-failed`)}}function applyExternalManagedArtifactChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);return S!==void 0&&S===s?`no-op`:(e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`applied`)}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
783
783
|
`||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let s=t.actor;return typeof s.writerId!=`string`||s.writerId.length===0||typeof s.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:s.writerId,displayName:s.displayName}}}function removeFromByFrom(e,t){let s=e.byFrom.get(t.from);if(!s)return;let g=s.filter(e=>e!==t);g.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,g)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let s=e.byTo.get(t.to);s&&removeFromByFrom(e,s),e.byTo.set(t.to,t);let g=e.byFrom.get(t.from);g?g.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),s=renameLogPath(e);if(!existsSync(s))return t;let g;try{g=readFileSync(s,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${s}, treating as empty:`,e),t}if(g.length===0)return t;let S=g.split(`
|
|
784
784
|
`),w=S[S.length-1];w!==``&&console.warn(`[rename-log] WARN: trailing line missing newline (${w.length} bytes); dropped`);let E=S.slice(0,-1);for(let e=0;e<E.length;e++){let s=E[e];if(s.length===0)continue;let g;try{g=JSON.parse(s)}catch(t){let g=s.slice(0,80),S=t.message;console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped (${S}): ${g}${s.length>80?`…`:``}`);continue}let S=validateEntry(g);if(!S){console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped`);continue}indexInsert(t,S)}return t.byTo.size>0&&liveEntriesGauge().add(t.byTo.size),t}function appendRenameLogEntry(e,t,s,g){let S=validateEntry(t);if(!S)throw Error(`[rename-log] refusing to append malformed entry`);let w=`${JSON.stringify(S)}\n`;if(Buffer.byteLength(w,`utf-8`)>RENAME_LOG_MAX_LINE_BYTES)throw Error(`[rename-log] entry exceeds max line size (${RENAME_LOG_MAX_LINE_BYTES} bytes)`);let E=renameLogPath(e),D=!1;if(existsSync(E))try{let e=statSync(E).size;e>5242880&&(D=!0,console.warn(`[rename-log] WARN: file size ${e} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`))}catch{}tracedAppendFileSync(E,w,{flag:`a`}),indexInsert(s,S),liveEntriesGauge().add(1),D&&g&&scheduleHardCapGc(g,s)}const gcPending=new Set;function scheduleHardCapGc(e,t){queueMicrotask(()=>{gcRenameLog(e,t).catch(e=>{console.warn(`[rename-log] WARN: hard-cap forced GC failed:`,e)})})}let _moduleIndex=null;function setRenameLogIndex(e,t){_moduleIndex={shadowDir:e,index:t}}function getOrLoadRenameLogIndex(e){if(_moduleIndex&&_moduleIndex.shadowDir===e)return _moduleIndex.index;let t=loadRenameLogIndex(e);return _moduleIndex={shadowDir:e,index:t},t}function serializeIndexToString(e){let t=[];for(let s of e.byTo.values())t.push(JSON.stringify(s));return t.length>0?`${t.join(`
|
|
785
785
|
`)}\n`:``}function parseGitTimeoutMs(){let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4}function expandPredecessors(e,t,s){let g=[],S=new Set,w=e,E=0;for(;;){if(g.length>=100){console.warn(`[rename-log] WARN: predecessor chain depth exceeded 100 while expanding "${e}"; truncating`);break}if(S.has(w)){console.warn(`[rename-log] WARN: cycle detected at "${w}" while expanding predecessors of "${e}"; truncating`);break}S.add(w);let D=s.byTo.get(w);if(!D||D.branch!==t)break;if(D.commitSha===``){E+=1;break}g.push({path:D.from,renameCommit:D.commitSha}),w=D.from}return g.reverse(),g.push({path:e,renameCommit:null}),{chain:g,skipped:E}}function createAncestorShaSetCache(){return new Map}function createSeedsCache(){return new Map}async function buildSeeds(e,t,s,g){return withSpan(`rename.buildSeeds`,void 0,async S=>{if(g){let e=g.get(`${s}:${t}`);if(e)return S.setAttribute(`rename.seeds_count`,e.length),S.setAttribute(`rename.cache_hit`,!0),e}let w=shadowGit(e),E;try{E=(await w.raw(`show`,`-s`,`--format=%aI`,t)).trim()}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: git show failed for rename commit ${t}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}if(!E)return S.setAttribute(`rename.seeds_count`,1),[t];let D;try{D=await w.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(creatordate:iso8601-strict) %(objectname)`,`refs/checkpoints/${s}/`)}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${s}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}let O=[t];for(let e of D.split(`
|
|
@@ -793,14 +793,14 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
793
793
|
`)){let t=e.trim();t.length===40&&D.add(t)}}g.scanned=t.byTo.size;let O=[];for(let{entry:e,observedSha:s}of w)D.has(s)||t.byTo.get(e.to)===e&&e.commitSha===s&&O.push(e);for(let e of O)t.byTo.get(e.to)===e&&indexRemove(t,e);if(g.dropped=O.length,g.retained=t.byTo.size,s?.rebuild){let s;try{s=await S.raw(`log`,`--all`,`--grep=^rename: `,`--format=%H%x00%cI%x00%B%x1e`)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction:`,e),s=``}let w=await buildBranchReachabilityMap(e,E);for(let e of s.split(``)){let s=e.trimStart();if(!s)continue;let S=s.split(`\0`),E=(S[0]??``).trim(),O=(S[1]??``).trim(),k=S[2]??``;if(E.length!==40||!D.has(E))continue;let j=parseOkActors(k),F=0;for(let e of j)F+=e.previous_paths?.length??0;if(F===0)continue;let L=F>1?`folder`:`file`,B=lookupBranchInMap(w,E),H=deriveGroupId(E,``,``);for(let e of j)if(!(!e.previous_paths||e.previous_paths.length===0))for(let s of e.previous_paths)t.byTo.has(s.to)||(indexInsert(t,{v:1,from:s.from,to:s.to,at:O||new Date(0).toISOString(),commitSha:E,branch:B,groupId:H,kind:L,actor:{writerId:e.writer_id,displayName:e.display_name}}),g.rebuilt+=1,g.retained+=1)}}return(g.dropped>0||g.rebuilt>0)&&rewriteJsonlAtomically(e.gitDir,t),g.dropped>0&&(console.warn(`[rename-log] gc swept ${g.dropped} dead entries (${g.retained} live remain)`),gcDroppedCounter().add(g.dropped),liveEntriesGauge().add(-g.dropped)),g.rebuilt>0&&liveEntriesGauge().add(g.rebuilt),g}function deriveGroupId(e,t,s){let g=createHash(`sha256`);g.update(`${e}\0${t}\0${s}`);let S=g.digest(`hex`);return`${S.slice(0,8)}-${S.slice(8,12)}-${S.slice(12,16)}-${S.slice(16,20)}-${S.slice(20,32)}`}async function buildBranchReachabilityMap(e,t){let s=new Map;for(let e of[...t].sort()){let t=/^refs\/(?:wip|checkpoints)\/([^/]+)\//.exec(e);if(!t?.[1])continue;let g=s.get(t[1])??[];g.push(e),s.set(t[1],g)}let g=new Map;for(let[t,S]of s){let s;try{s=await revListReachable(e,S)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${t}; reconstructed entries on this branch will fall back to 'main':`,e);continue}let w=new Set;for(let e of s.split(`
|
|
794
794
|
`)){let t=e.trim();t.length===40&&w.add(t)}g.set(t,w)}return g}function lookupBranchInMap(e,t){for(let[s,g]of e)if(g.has(t))return s;return`main`}async function resolveDocPathAtCommit(e,t,s,g,S,w,E,D){let{chain:O}=expandPredecessors(t,g,S),k=await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,g,D);return s.length===0?new Set:buildAncestorShaSet(e,s,g,E)})),j=[];for(let e=O.length-1;e>=0;e--){let t=O[e],g=k[e];g!==null&&!g.has(s)||j.push({sha:s,path:w(t.path)})}if(j.length===0)return null;let F=await batchCheckExistence(e,j);for(let e=0;e<j.length;e++)if(F[e])return j[e].path;return null}function computeMapDrivenBodySplice(e,t,s,g){let S,w,E;try{S=s.parseToMdast(e).children,w=s.serialize(t),E=s.parseToMdast(w).children}catch(e){return g?.(`parse-error`,e),null}if(!allBlocksCarryPositions(S)||!allBlocksCarryPositions(E))return g?.(`missing-position`),null;let D=0;for(;D<S.length&&D<E.length&&structurallyEqual(S[D],E[D]);)D++;let O=0;for(;O<S.length-D&&O<E.length-D&&structurallyEqual(S[S.length-1-O],E[E.length-1-O]);)O++;let k=D>0?blockEndOffset(S[D-1]):S.length>0?blockStartOffset(S[0]):0,j=O>0?blockStartOffset(S[S.length-O]):e.length,F=D>0?blockEndOffset(E[D-1]):E.length>0?blockStartOffset(E[0]):0,L=O>0?blockStartOffset(E[E.length-O]):w.length;return{spliceStart:k,spliceEnd:j,newSlice:w.slice(F,L)}}function allBlocksCarryPositions(e){for(let t of e){let e=t.position?.start?.offset,s=t.position?.end?.offset;if(typeof e!=`number`||typeof s!=`number`)return!1}return!0}function blockStartOffset(e){let t=e.position?.start?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.start.offset`);return t}function blockEndOffset(e){let t=e.position?.end?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.end.offset`);return t}function structurallyEqual(e,t){return stringifyIgnorePosition(e)===stringifyIgnorePosition(t)}function stringifyIgnorePosition(e){return JSON.stringify(e,(e,t)=>e===`position`?void 0:t)}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}let mapDrivenParseErrorWarned=!1;function warnOnceMapDrivenParseError(e,t){mapDrivenParseErrorWarned||(mapDrivenParseErrorWarned=!0,console.warn(`[Server Observer A] Map-driven splice parse/serialize threw (doc: ${e??`unknown`}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only):`,t instanceof Error?t.message:String(t)))}function tryComputeMapDrivenSplice(e){let{currentText:t,lastSyncedXmlMd:s,json:g,mdManager:S,docName:w}=e;if(t!==s)return incrementMapDrivenSpliceFallback(`text-mismatch`),null;if(w!==void 0&&(isSystemDoc(w)||isConfigDoc(w)))return incrementMapDrivenSpliceFallback(`synthetic-doc`),null;let{body:E}=stripFrontmatter(t),D=t.length-E.length,O=computeMapDrivenBodySplice(E,g,S,(e,t)=>{incrementMapDrivenSpliceFallback(e),e===`parse-error`&&warnOnceMapDrivenParseError(w,t)});return O?{spliceStart:D+O.spliceStart,spliceEnd:D+O.spliceEnd,newSlice:O.newSlice}:null}function applyMapDrivenSplice(e,t){let s=t.spliceEnd-t.spliceStart;s>0&&e.delete(t.spliceStart,s),t.newSlice.length>0&&e.insert(t.spliceStart,t.newSlice)}function settlesSplitBrain(e,t,s){return e!==t&&normalizeBridge(e)!==(s??normalizeBridge(t))}function setupServerObservers(e){let{doc:t,xmlFragment:s,ytext:g,mdManager:S,schema:w}=e,E=(t,s)=>{let g=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:g}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let S=e.shadow?.();if(!S||!e.docName)return;let w=e.getBranch?.()??`main`,E=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(S,E,{kind:`bridge-merge-loss`,docName:e.docName,contents:s,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:w,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
|
|
795
795
|
`).slice(0,4).join(`
|
|
796
|
-
`)})})})},D=t=>{try{emitBridgeSplitBrainRederive(t,e.docName)&&(incrementBridgeSplitBrainRederives(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){console.warn(`[Server Observer A] Split-brain telemetry failed:`,e)}},O=``,k=``,j=!1,F=!1,L=!1,B=()=>{k=g.toString(),j=!1},H=e=>{O=e,B(),j=e!==``},q=e=>{O=e,k=e,j=!1},ee=e=>{O=e,j=!1},J=e=>{O=e,k=g.toString(),j=!0},Y=()=>stripFrontmatter(g.toString()).frontmatter;try{let t=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(t),D=prependFrontmatter(Y(),E),O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,k=S.serialize(S.parseWithFallback(stripFrontmatter(g.toString()).body,O)),j=e=>e.replace(/^\n+/,``).replace(/\n+$/,``);j(k)===j(E)?H(D):q(D)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),H(``)}let te=()=>{try{let F=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),B=S.serialize(F),ee=prependFrontmatter(Y(),B);if(j&&O===ee){settlesSplitBrain(g.toString(),ee)?(q(ee),L=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let J=g.toString(),te=normalizeBridge(J),ne=normalizeBridge(ee);if(te===ne){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),H(ee);return}let ae=k,oe=J===k,se=oe&&j&&k!==O&&te!==normalizeBridge(O);setActiveSpanAttributes({"observer.a.path":oe?se?`residual-merge`:`path-a`:`path-b`});let ce={mergedText:null},ue=performance.now(),de=oe&&se?null:tryComputeMapDrivenSplice({currentText:J,lastSyncedXmlMd:k,json:F,mdManager:S,docName:e.docName});de&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-ue)}),t.transact(()=>{if(de)applyMapDrivenSplice(g,de);else if(oe&&!se)applyIncrementalDiff(g,J,ee);else{let t=oe?O:ae,{boundary:s}=splitLeadingDocBoundary(J),S=e=>reattachLeadingDocBoundary(splitLeadingDocBoundary(e).text,s),w=e.mergeThreeWay??mergeThreeWay;try{let e=S(w(projectMergeBoundarySpace(t),projectMergeBoundarySpace(ee),projectMergeBoundarySpace(J)));applyFastDiff(g,J,e),ce.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,ae),shouldRethrowBridgeMergeLoss()))throw e;let t=S(e.info.result);applyFastDiff(g,J,t),ce.mergedText=t}}},OBSERVER_SYNC_ORIGIN),de&&incrementMapDrivenSpliceApplied(),ce.mergedText!==null&&!oe&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!oe,mergeBytesChanged:Math.abs(ce.mergedText.length-J.length)}))),ce.mergedText!==null&&oe&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),H(ee),settlesSplitBrain(g.toString(),ee,ne)&&(L=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(Y(),t);settlesSplitBrain(g.toString(),E)?(J(E),L=!0,D(`error-recovery`)):H(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),O=``,k=``,j=!1}}},ne=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},te)},ae=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(Y(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),H(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),H(``)}let oe=Y(),se=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(k)===normalizeBridge(w)){oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E);return}let O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,j=S.parseWithFallback(D,O),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),H(t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),H(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);ee(prependFrontmatter(Y(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ce=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},se)},ue=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}},de=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!F&&!L){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){F=!1,L=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=F;F&&(F=!1,e.onDispatch?.(`a`),ne());let S=L;L&&(L=!1,e.onDispatch?.(`b`),ce()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(ae),g.observe(ue),t.on(`afterAllTransactions`,de);let fe=attachQuiescenceTracker(t);return()=>{fe(),t.off(`afterAllTransactions`,de),s.unobserveDeep(ae),g.unobserve(ue)}}const log$15=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; OpenKnowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,`${e}${getDocExtension(e)}`);if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return isWithinDir(e,t)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}const inFlightFlushByDoc=new Map;function peekInFlightFlush(e){return inFlightFlushByDoc.get(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(toPosix(relative(g,s))||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onFlushCommit,j=e?.onDiskFlush,F=e?.mdManager??mdManager,L=e?.ephemeral??!1,B={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:L},H=new Map,q={projectDir:g,homedirOverride:e?.configHomedirOverride,lkgCache:H,setReconciledBase,getReconciledBase},ee=new Set,J=e?.applyDiskContentToDoc??applyDiskContentToDoc,Y=null,te=8,ne=new Map,ae=new Map,oe=new Set,se=new Set,ce=e?.gitEnabled??!0,ue=e?.commitDebounceMs??15e3,de=e?.wipRef??`refs/wip/main`,fe=e?.getCurrentBranch,me=null,ge=0,_e=null,ve=!1,ye=null,Ce=new Map;async function we(){Ve();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await Te()).finally(()=>{Be?.record((Date.now()-e)/1e3)})}async function Te(){let e=S?.current;if(e){let t=swapContributors(),s=fe?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);ge=0,log$15.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$15.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){ge++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:ge},`[persistence] Shadow commit failed (attempt ${ge})`),ge>=3&&log$15.error({attempt:ge},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),ge++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:ge},`[persistence] Shadow WIP tree build failed (attempt ${ge})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],j=E.actor,F=[...E.summaries],L=[...E.previousPaths],B={v:1,writer_id:w,principal:j?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:j?.agentType??null,client_name:j?.clientName??null,client_version:j?.clientVersion??null,label:j?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...F.length>0?{summaries:F}:{},...L.length>0?{previous_paths:L}:{}},H=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),F)}\n\n${formatOkActor(B)}`;try{let E=await commitWipFromTree(e,t,g,H,s);S=!0;try{k?.()}catch(e){log$15.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}log$15.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$15.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$15.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?ge=0:(ge++,incrementGitAutoSaveFailure(),ge>=3&&log$15.error({attempt:ge},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$15.info({},`[persistence] Empty repo — starting with empty index`):log$15.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,de)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,de,S),ge=0,log$15.info({sha:S.slice(0,8),wipRef:de},`[persistence] Git commit: ${S.slice(0,8)} on ${de}`)}catch(e){ge++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:ge},`[persistence] Git commit failed (attempt ${ge})`),ge>=3&&log$15.error({attempt:ge},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function De(e){if(e<=0)return ue;let t=2**Math.min(e,5),s=Math.random()*.25*ue;return ue*t+s}function je(){ce&&(isBatchInProgress()||(me&&clearTimeout(me),me=setTimeout(()=>{if(me=null,_e){ve=!0;return}_e=we().finally(()=>{_e=null,ve&&(ve=!1,je())})},De(ge))))}async function Me(){me&&(clearTimeout(me),me=null,_e||=we().finally(()=>{_e=null,ve&&(ve=!1,je())})),_e&&await _e}function Pe(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=F.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,F.serialize(E)))}catch(e){return log$15.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function Ie(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$15.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let Re=null,ze=null,Be=null;function Ve(){if(Re)return;let e=getMeter();Re=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),ze=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Be=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Ue({document:e,documentName:t,lastTransactionOrigin:g}){Ve();let S=Date.now(),w;return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let S=se.delete(t),O=e.getMap(`lifecycle`).get(`status`);if(O===`deleted-upstream`||O===`renamed`||O===`conflict`){log$15.info({documentName:t,lifecycleStatus:O},`[persistence] Skipped store for ${t}: lifecycle=${O}`),ne.delete(t),ee.delete(t);return}if(!isDocQuiescent(e)){let s=ne.get(t)??0;if(s<8){let g=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:g??null,deferCount:s})),incrementPersistenceSkipNonQuiescent(),ne.set(t,s+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:s})),incrementPersistenceForceFlushDuringBurst()}let{sv:k,json:B}=captureDocSnapshotForPersistence(e),{frontmatter:H,body:q}=stripFrontmatter(e.getText(`source`).toString()),Y=prependFrontmatter(H,q),te;try{te=assertBridgeInvariant(Y,prependFrontmatter(H,F.serialize(B)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$15.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),te=!1}te||Ie(e,q,t);let ce=getReconciledBase(t),ue=normalizeBridge(Y),de=ce!==void 0&&ue===normalizeBridge(ce);if(!de&&L&&ce!==void 0){let e=Pe(ce,t);e!==null&&ue===e&&(de=!0)}if(de){contributorCount()>0&&je(),ne.delete(t);return}if(ce===void 0&&normalizeBridge(Y)===``){log$15.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),ne.delete(t);return}let fe=resolveWriterFromOrigin(g,D);if(fe&&fe.id!==SERVICE_WRITER.id&&(hasContributor(fe.id)||recordContributor(t,fe.id,fe.name,fe.id)),ce!==void 0){let g=classifyDuplication(Y,ce);if(g.kind===`block`){if(ee.has(t)){log$15.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let S=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:Y.length,baseBytes:ce.length,fragmentChildren:S,copies:g.copies,reason:g.reason}));try{let g=safeContentPath(t,s),S;if(existsSync(g)){let e=null;try{e=realpathSync(g)}catch(e){log$15.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,s))try{S=readFileSync(e,`utf-8`)}catch(s){log$15.warn({err:s,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),S=ce}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${g} → ${e}, using currentBase`,{docName:t,originalPath:g,canonical:e,contentDir:s}),S=ce}else S=ce;e.transact(()=>{J(e,S)},FILE_WATCHER_ORIGIN),ee.delete(t)}catch(e){ee.add(t),log$15.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}ne.delete(t);return}}w=normalizeBridge(Y),inFlightFlushByDoc.set(t,w);let me=safeContentPath(t,s);await tracedMkdir(dirname(me),{recursive:!0});let ge;try{ge=await realpath(me)}catch(e){let s=e.code;if(s===`ENOENT`){let e=!1;try{e=lstatSync(me).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$15.warn({err:e,path:me},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),ge=me}else if(s===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${me}`),Error(`Symlink cycle detected at ${me}`);else throw e}if(!isWithinContentDir(ge,s)){let e=`symlink-escape: ${me} resolves to ${ge} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:me,canonical:ge,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===t&&await tracedWriteFile(ge,`# NATIVE
|
|
796
|
+
`)})})})},D=t=>{try{emitBridgeSplitBrainRederive(t,e.docName)&&(incrementBridgeSplitBrainRederives(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){console.warn(`[Server Observer A] Split-brain telemetry failed:`,e)}},O=``,k=``,j=!1,F=!1,L=!1,B=()=>{k=g.toString(),j=!1},H=e=>{O=e,B(),j=e!==``},q=e=>{O=e,k=e,j=!1},ee=e=>{O=e,j=!1},J=e=>{O=e,k=g.toString(),j=!0},Y=()=>stripFrontmatter(g.toString()).frontmatter,te=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,ne=createDocCanonicalizer(S,{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,docName:e.docName}),ae=``,oe=``,se=!1,ce=(e,t)=>{if(se&&e===ae&&t===oe)return!0;let s=isParseEquivalentBridge(e,t,ne);return s&&(ae=e,oe=t,se=!0),s},ue=(e,t,s)=>settlesSplitBrain(e,t,s)&&!ce(e,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(Y(),t);ce(g.toString(),E)?H(E):q(E)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),H(``)}let de=()=>{try{let F=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),B=S.serialize(F),ee=prependFrontmatter(Y(),B);if(j&&O===ee){ue(g.toString(),ee)?(q(ee),L=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let J=g.toString(),te=normalizeBridge(J),ne=normalizeBridge(ee);if(te===ne){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),H(ee);return}let ae=k,oe=J===k,se=oe&&j&&k!==O&&te!==normalizeBridge(O);setActiveSpanAttributes({"observer.a.path":oe?se?`residual-merge`:`path-a`:`path-b`});let ce={mergedText:null},de=performance.now(),fe=oe&&se?null:tryComputeMapDrivenSplice({currentText:J,lastSyncedXmlMd:k,json:F,mdManager:S,docName:e.docName});fe&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-de)}),t.transact(()=>{if(fe)applyMapDrivenSplice(g,fe);else if(oe&&!se)applyIncrementalDiff(g,J,ee);else{let t=oe?O:ae,{boundary:s}=splitLeadingDocBoundary(J),S=e=>reattachLeadingDocBoundary(splitLeadingDocBoundary(e).text,s),w=e.mergeThreeWay??mergeThreeWay;try{let e=S(w(projectMergeBoundarySpace(t),projectMergeBoundarySpace(ee),projectMergeBoundarySpace(J)));applyFastDiff(g,J,e),ce.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,ae),shouldRethrowBridgeMergeLoss()))throw e;let t=S(e.info.result);applyFastDiff(g,J,t),ce.mergedText=t}}},OBSERVER_SYNC_ORIGIN),fe&&incrementMapDrivenSpliceApplied(),ce.mergedText!==null&&!oe&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!oe,mergeBytesChanged:Math.abs(ce.mergedText.length-J.length)}))),ce.mergedText!==null&&oe&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),H(ee),ue(g.toString(),ee,ne)&&(L=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(Y(),t);ue(g.toString(),E)?(J(E),L=!0,D(`error-recovery`)):H(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),O=``,k=``,j=!1}}},fe=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},de)},me=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),ge=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(Y(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),H(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),H(``)}let ge=Y(),_e=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(k)===normalizeBridge(w)){ge!==E&&(recordFrontmatterEditSurface(`source-mode`),ge=E);return}let O=S.parseWithFallback(D,te),j=e.schema.nodeFromJSON(O);t.transact(()=>{updateYFragment(t,s,j,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),ge!==E&&(recordFrontmatterEditSurface(`source-mode`),ge=E),incrementServerObserverFire(`b`);try{let t=S.serialize(O),s=prependFrontmatter(E,t);assertBridgeInvariant(g.toString(),s,{site:`observer-b`,docName:e.docName,canonicalizeBody:e=>e===D?t:ne(e)}),H(s)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),H(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);ee(prependFrontmatter(Y(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ve=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},_e)},ye=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),ge=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}},Ce=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!F&&!L){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){F=!1,L=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=F;F&&(F=!1,e.onDispatch?.(`a`),fe());let S=L;L&&(L=!1,e.onDispatch?.(`b`),ve()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(me),g.observe(ye),t.on(`afterAllTransactions`,Ce);let we=attachQuiescenceTracker(t);return()=>{we(),t.off(`afterAllTransactions`,Ce),s.unobserveDeep(me),g.unobserve(ye)}}const log$15=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; OpenKnowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,`${e}${getDocExtension(e)}`);if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return isWithinDir(e,t)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}const inFlightFlushByDoc=new Map;function peekInFlightFlush(e){return inFlightFlushByDoc.get(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(toPosix(relative(g,s))||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onFlushCommit,j=e?.onDiskFlush,F=e?.onConfigPersisted,L=e?.mdManager??mdManager,B=e?.ephemeral??!1,H={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:B},q=new Map,ee={projectDir:g,homedirOverride:e?.configHomedirOverride,lkgCache:q,setReconciledBase,getReconciledBase},J=new Set,Y=e?.applyDiskContentToDoc??applyDiskContentToDoc,te=null,ne=8,ae=new Map,oe=new Map,se=new Set,ce=new Set,ue=e?.gitEnabled??!0,de=e?.commitDebounceMs??15e3,fe=e?.wipRef??`refs/wip/main`,me=e?.getCurrentBranch,ge=null,_e=0,ve=null,ye=!1,Ce=null,we=new Map;async function Te(){Ue();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await De()).finally(()=>{Ve?.record((Date.now()-e)/1e3)})}async function De(){let e=S?.current;if(e){let t=swapContributors(),s=me?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);_e=0,log$15.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$15.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){_e++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:_e},`[persistence] Shadow commit failed (attempt ${_e})`),_e>=3&&log$15.error({attempt:_e},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),_e++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:_e},`[persistence] Shadow WIP tree build failed (attempt ${_e})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],j=E.actor,F=[...E.summaries],L=[...E.previousPaths],B={v:1,writer_id:w,principal:j?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:j?.agentType??null,client_name:j?.clientName??null,client_version:j?.clientVersion??null,label:j?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...F.length>0?{summaries:F}:{},...L.length>0?{previous_paths:L}:{}},H=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),F)}\n\n${formatOkActor(B)}`;try{let E=await commitWipFromTree(e,t,g,H,s);S=!0;try{k?.()}catch(e){log$15.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}log$15.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$15.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$15.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?_e=0:(_e++,incrementGitAutoSaveFailure(),_e>=3&&log$15.error({attempt:_e},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$15.info({},`[persistence] Empty repo — starting with empty index`):log$15.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,fe)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,fe,S),_e=0,log$15.info({sha:S.slice(0,8),wipRef:fe},`[persistence] Git commit: ${S.slice(0,8)} on ${fe}`)}catch(e){_e++,incrementGitAutoSaveFailure(),log$15.error({err:e,attempt:_e},`[persistence] Git commit failed (attempt ${_e})`),_e>=3&&log$15.error({attempt:_e},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function je(e){if(e<=0)return de;let t=2**Math.min(e,5),s=Math.random()*.25*de;return de*t+s}function Me(){ue&&(isBatchInProgress()||(ge&&clearTimeout(ge),ge=setTimeout(()=>{if(ge=null,ve){ye=!0;return}ve=Te().finally(()=>{ve=null,ye&&(ye=!1,Me())})},je(_e))))}async function Pe(){ge&&(clearTimeout(ge),ge=null,ve||=Te().finally(()=>{ve=null,ye&&(ye=!1,Me())})),ve&&await ve}function Ie(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=L.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,L.serialize(E)))}catch(e){return log$15.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function Re(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$15.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let ze=null,Be=null,Ve=null;function Ue(){if(ze)return;let e=getMeter();ze=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Be=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ve=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function We({document:t,documentName:g,lastTransactionOrigin:S}){Ue();let w=Date.now(),O;return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":g}},async()=>{let w=ce.delete(g),k=t.getMap(`lifecycle`).get(`status`);if(k===`deleted-upstream`||k===`renamed`||k===`conflict`){log$15.info({documentName:g,lifecycleStatus:k},`[persistence] Skipped store for ${g}: lifecycle=${k}`),ae.delete(g),J.delete(g);return}if(!isDocQuiescent(t)){let e=ae.get(g)??0;if(e<8){let s=getMsSinceLastUserTx(t);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":g,wallClockMsSinceLastTransaction:s??null,deferCount:e})),incrementPersistenceSkipNonQuiescent(),ae.set(g,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":g,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(t)??null,deferCount:e})),incrementPersistenceForceFlushDuringBurst()}let{sv:F,json:H}=captureDocSnapshotForPersistence(t),{frontmatter:q,body:ee}=stripFrontmatter(t.getText(`source`).toString()),te=prependFrontmatter(q,ee),ne;try{ne=assertBridgeInvariant(te,prependFrontmatter(q,L.serialize(H)),{site:`persistence`,docName:g,suppressDevThrow:!0,canonicalizeBody:createDocCanonicalizer(L,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:g})})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":g,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$15.warn({err:e,documentName:g},`[persistence] Sanity-check serialize failed for ${g}; proceeding with ytext bytes`),ne=!1}ne||Re(t,ee,g);let ue=getReconciledBase(g),de=normalizeBridge(te),fe=ue!==void 0&&de===normalizeBridge(ue);if(!fe&&B&&ue!==void 0){let e=Ie(ue,g);e!==null&&de===e&&(fe=!0)}if(fe){contributorCount()>0&&Me(),ae.delete(g);return}if(ue===void 0&&normalizeBridge(te)===``){log$15.warn({documentName:g},`[persistence] Skipped phantom write for ${g}: empty Y.Doc with no reconciled base`),ae.delete(g);return}let me=resolveWriterFromOrigin(S,D);if(me&&me.id!==SERVICE_WRITER.id&&(hasContributor(me.id)||recordContributor(g,me.id,me.name,me.id)),ue!==void 0){let e=classifyDuplication(te,ue);if(e.kind===`block`){if(J.has(g)){log$15.warn({documentName:g},`[persistence] Tripwire breaker active — skipping duplicate store for ${g}`);return}let S=t.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":g,candidateBytes:te.length,baseBytes:ue.length,fragmentChildren:S,copies:e.copies,reason:e.reason}));try{let e=safeContentPath(g,s),S;if(existsSync(e)){let t=null;try{t=realpathSync(e)}catch(e){log$15.warn({err:e,documentName:g},`[persistence] Tripwire reset realpath failed for ${g}; using currentBase`)}if(t&&isWithinContentDir(t,s))try{S=readFileSync(t,`utf-8`)}catch(e){log$15.warn({err:e,documentName:g,canonical:t},`[persistence] Tripwire reset readFileSync failed for ${g}; using currentBase`),S=ue}else t&&console.warn(`[persistence] symlink-escape on tripwire reset: ${e} → ${t}, using currentBase`,{docName:g,originalPath:e,canonical:t,contentDir:s}),S=ue}else S=ue;t.transact(()=>{Y(t,S)},FILE_WATCHER_ORIGIN),J.delete(g)}catch(e){J.add(g),log$15.error({err:e,documentName:g},`[persistence] Tripwire reset failed for ${g}`)}ae.delete(g);return}}O=normalizeBridge(te),inFlightFlushByDoc.set(g,O);let ge=safeContentPath(g,s);await tracedMkdir(dirname(ge),{recursive:!0});let _e;try{_e=await realpath(ge)}catch(e){let t=e.code;if(t===`ENOENT`){let e=!1;try{e=lstatSync(ge).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$15.warn({err:e,path:ge},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:g,reason:`broken-symlink`}),_e=ge}else if(t===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${ge}`),Error(`Symlink cycle detected at ${ge}`);else throw e}if(!isWithinContentDir(_e,s)){let e=`symlink-escape: ${ge} resolves to ${_e} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:g,originalPath:ge,canonical:_e,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===g&&await tracedWriteFile(_e,`# NATIVE
|
|
797
797
|
|
|
798
798
|
native-divergence-injected
|
|
799
|
-
`,`utf-8`),
|
|
799
|
+
`,`utf-8`),w&&ue!==void 0){let e=null;try{existsSync(_e)&&(e=readFileSync(_e,`utf-8`))}catch(t){e=null,log$15.warn({err:t,documentName:g},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(e!==null&&normalizeBridge(e)!==normalizeBridge(ue)){let s=e;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":g,outcome:`reverted`,diskBytes:s.length,baseBytes:ue.length,candidateBytes:te.length}));try{t.transact(()=>{Y(t,s)},FILE_WATCHER_ORIGIN)}catch(e){throw oe.set(g,toStoreFailure(e)),ae.delete(g),e}setReconciledBase(g,s),se.add(g),ae.delete(g);return}}let ve=`${_e}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===g){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${g}`);throw e.code=`ENOSPC`,e}await tracedWriteFile(ve,te,`utf-8`),await tracedRename(ve,_e),registerWrite(_e,contentHash(te)),oe.delete(g),incrementPersistenceDiskWrite();try{j?.(g,F,te,ue??null)}catch(e){log$15.warn({err:e,documentName:g},`[persistence] onDiskFlush callback failed for ${g}`)}}catch(e){try{tracedUnlinkSync(ve)}catch{}throw ae.delete(g),oe.set(g,toStoreFailure(e)),log$15.error({err:e,documentName:g},`[persistence] Failed to save ${g}`),e}log$15.info({filePath:_e,bytes:te.length},`[persistence] Wrote ${_e} (${te.length} bytes)`),setReconciledBase(g,te),J.delete(g),ae.delete(g),E&&(E.updateDocumentFromMarkdown(g,te),E.saveToDisk().catch(e=>{log$15.warn({err:e,documentName:g},`[backlinks] Failed to persist cache for ${g}`)})),setActiveSpanAttributes({"persistence.bytes":te.length}),Me()}).finally(()=>{O!==void 0&&inFlightFlushByDoc.get(g)===O&&inFlightFlushByDoc.delete(g),Be?.record((Date.now()-w)/1e3)})}function Ge({document:e,documentName:t,lastTransactionOrigin:s}){we.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:s})}async function Ke(e=`within-branch`){return Ce?(te=te===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,Ce):(Ce=(async()=>{let t=e;for(;;){let e=[...we.entries()];if(we.clear(),t!==`discard-stale`){for(let[t,s]of e)if(s.branch===getActiveBranch())try{await We({document:s.document,documentName:t,lastTransactionOrigin:s.lastTransactionOrigin})}catch(e){let s=process.env.OK_TELEMETRY_VERBOSE===`1`,g=``;try{g=String(e?.message??``)}catch{g=``}let S=fnv1aDigest(g),w;try{w=classifyDeferredStoreError(e)}catch(e){let g=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(g),errorMessageHash:S,...s?{classifyErrorMessage:g}:{},timestamp:new Date().toISOString()})),w=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:w,errorMessageHash:S,...s?{errorMessage:g}:{},timestamp:new Date().toISOString()})),log$15.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let s=te;if(te=null,we.size===0&&s===null)break;t=s??`within-branch`}})().finally(()=>{Ce=null}),Ce)}let Xe={async onLoadDocument({document:t,documentName:g,context:S}){if(isSystemDoc(g))return;if(isConfigDoc(g)){loadConfigDoc(t,g,H);return}if(isManagedArtifactDoc(g)){loadManagedArtifactDoc(t,g,ee);return}Ue();let w=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":g}},async()=>{log$15.info({documentName:g,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${g} (connections: ${t.getConnectionsCount?.()??`?`})`);let S=safeContentPath(g,s);if(!existsSync(S))return;let w=S;try{let e=realpathSync(S);if(!isWithinContentDir(e,s)){console.warn(`[persistence] symlink-escape on load: ${S} → ${e}, refusing`);return}w=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${S}, refusing`);return}}let E=statSync(w).size;if(E>524288)throw log$15.warn({documentName:g,fileSize:E,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(g,E);let D=readFileSync(S,`utf-8`),O=t.getXmlFragment(`default`);log$15.info({documentName:g,fragmentLength:O.length},`[persistence] onLoadDocument ${g}: fragment.length=${O.length} before update`),O.length===0?(t.transact(()=>{applyDiskContentToDoc(t,D,e?.resolveEmbed,g,e?.resolveSize),t.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),log$15.info({filePath:S,children:O.length},`[persistence] Loaded ${S} into Y.Doc (${O.length} children)`),O.observeDeep(()=>{log$15.info({documentName:g,fragmentLength:O.length},`[persistence] MUTATION on ${g}: fragment.length=${O.length}`)})):log$15.info({documentName:g,children:O.length},`[persistence] Skipped load for ${g} — fragment already has ${O.length} children`),setReconciledBase(g,D)}).finally(()=>{ze?.record((Date.now()-w)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:s,lastContext:g}){if(!isSystemDoc(t)){if(isConfigDoc(t)){let g=await storeConfigDoc(e,t,s,H);if(g===`persisted`||g===`reconciled`)try{F?.(t)}catch(e){log$15.warn({err:e,documentName:t},`[persistence] onConfigPersisted callback failed`)}return}if(isManagedArtifactDoc(t)){if(await storeManagedArtifactDoc(e,t,s,ee)===`persisted`){let e=resolveWriterFromOrigin(s,D);if(e&&e.id!==SERVICE_WRITER.id&&!e.id.startsWith(`agent-`)){let s=managedArtifactContributorAttribution(t);s&&(recordContributor(s.docKey,e.id,e.name,e.id,s.subject),Me())}}return}if(isBatchInProgress()){Ge({document:e,documentName:t,lastTransactionOrigin:s});return}return We({document:e,documentName:t,lastTransactionOrigin:s})}}};async function $e(){ve&&await ve}async function nt(){if(ve){await ve;return}contributorCount()!==0&&(ve=Te().finally(()=>{ve=null,ye&&(ye=!1,Me())}),await ve)}function rt(e){let t=oe.get(e);return t&&oe.delete(e),t??null}function it(e){return se.has(e)?(se.delete(e),!0):!1}function at(e){ce.add(e)}return{extension:Xe,flushDeferredStores:Ke,flushPendingGitCommit:Pe,flushContributors:nt,waitForPendingCommits:$e,takeStoreFailure:rt,takeStoreDivergence:it,markAgentWriteStore:at,configPersistenceCtx:H,managedArtifactCtx:ee}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),s=t.indexOf(`#`),g=s>=0?t.slice(0,s):t,S=g.indexOf(`?`);return S>=0?g.slice(0,S):g}function isLocalAssetReferenceHref(e){let t=stripHrefDecorations(e);return!t||isRemoteOrOpaqueHref(t)?!1:LINKABLE_ASSET_EXTENSIONS.has(extname(t).slice(1).toLowerCase())}function assetReferenceSignature(e){return e?[...new Set(extractLocalAssetHrefs(e).filter(isLocalAssetReferenceHref))].sort().join(`\0`):``}function assetReferencesChanged(e,t){return assetReferenceSignature(e)!==assetReferenceSignature(t)}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let s of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=s[1]??s[2];e&&t.add(e)}for(let s of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=s[1];e&&t.add(e)}for(let s of e.matchAll(HTML_LINK_ATTR_RE)){let e=s[1]??s[2]??s[3]??s[4];e&&t.add(e)}}function stripHtmlComments(e,t){let s=e,g=``;for(;s.length>0;){if(t.inComment){let e=s.indexOf(`-->`);if(e===-1)return g;s=s.slice(e+3),t.inComment=!1;continue}let e=s.indexOf(`<!--`);if(e===-1)return g+s;g+=s.slice(0,e),s=s.slice(e+4),t.inComment=!0}return g}function extractLocalAssetHrefs(e){let t=new Set,s=createCodeFenceTracker(),g={inComment:!1};for(let S of e.replaceAll(`\r
|
|
800
800
|
`,`
|
|
801
801
|
`).replaceAll(`\r`,`
|
|
802
802
|
`).split(`
|
|
803
|
-
`))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!LINKABLE_ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`);let F=SANDBOXED_HTML_EXTENSIONS.has(k);j||(g.has(k)||F?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`?E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`):F&&(E.setHeader(`Content-Security-Policy`,SANDBOXED_HTML_CSP),E.setHeader(`Cache-Control`,`no-store`)),s(e,E,()=>{if(E.headersSent)return;let e=SANDBOXED_HTML_EXTENSIONS.has(k);if(!e&&(S.has(k)||w.has(k))){E.statusCode=404,E.end();return}e&&(E.removeHeader(`Content-Security-Policy`),E.removeHeader(`Content-Disposition`),E.removeHeader(`X-Content-Type-Options`),E.removeHeader(`Cache-Control`)),D()})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}function agentIdentityFields(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),VERSION_FIELD_DESCRIBE="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",versionInputSchema=string().length(40).regex(/^[0-9a-f]+$/i).describe(VERSION_FIELD_DESCRIBE),previewUrlOutputField=string().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),previewUrlSourceField=string().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),previousPreviewUrlField=string().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),summaryOutputSchema=object$1({value:string(),truncatedFrom:number().optional(),hint:string().optional()}).describe(`Normalized change-note summary, when one was recorded.`),looseObjectArray=array(record(string(),unknown())),previewAttachWarningField=record(string(),unknown()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),brokenLinksOutputField=array(BrokenLinkSchema).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.');function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}}const documentResultBaseShape={summary:summaryOutputSchema.optional(),warnings:array(AdvisoryWarningSchema).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),brokenLinks:brokenLinksOutputField};function nestDocResult(e,t,s){let g={};return e&&(g.previewUrl=e.url,g.previewUrlSource=e.source),t&&(g.warning=t),Object.keys(s).length>0&&(g.document=s),g}function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,s){let g={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
|
|
803
|
+
`))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!LINKABLE_ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`);let F=SANDBOXED_HTML_EXTENSIONS.has(k);j||(g.has(k)||F?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`?E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`):F&&(E.setHeader(`Content-Security-Policy`,SANDBOXED_HTML_CSP),E.setHeader(`Cache-Control`,`no-store`)),s(e,E,()=>{if(E.headersSent)return;let e=SANDBOXED_HTML_EXTENSIONS.has(k);if(!e&&(S.has(k)||w.has(k))){E.statusCode=404,E.end();return}e&&(E.removeHeader(`Content-Security-Policy`),E.removeHeader(`Content-Disposition`),E.removeHeader(`X-Content-Type-Options`),E.removeHeader(`Cache-Control`)),D()})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}function agentIdentityFields(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),VERSION_FIELD_DESCRIBE="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",versionInputSchema=string().length(40).regex(/^[0-9a-f]+$/i).describe(VERSION_FIELD_DESCRIBE),previewUrlOutputField=string().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),previewUrlSourceField=string().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),previousPreviewUrlField=string().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),summaryOutputSchema=object$1({value:string(),truncatedFrom:number().optional(),hint:string().optional()}).describe(`Normalized change-note summary, when one was recorded.`),looseObjectArray=array(record(string(),unknown())),previewAttachWarningField=record(string(),unknown()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),brokenLinksOutputField=array(BrokenLinkSchema).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.');function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}}const documentResultBaseShape={summary:summaryOutputSchema.optional(),warnings:array(AdvisoryWarningSchema).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),brokenLinks:brokenLinksOutputField,templateHint:array(object$1({name:string(),description:string().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function nestDocResult(e,t,s){let g={};return e&&(g.previewUrl=e.url,g.previewUrlSource=e.source),t&&(g.warning=t),Object.keys(s).length>0&&(g.document=s),g}function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,s){let g={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
|
|
804
804
|
|
|
805
805
|
OpenKnowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
|
|
806
806
|
|
|
@@ -825,11 +825,12 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
825
825
|
`),g=e=>e.endsWith(`\r`)?e.slice(0,-1):e,S=0;for(;S<s.length;){let e=g(s[S]??``),w=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!w){S++;continue}let E=w[1]??``,D=E[0]??"`";if(D==="`"&&e.slice(e.indexOf(E)+E.length).includes("`")){S++;continue}let O=w[2]??``,k=RegExp(`^ {0,3}\\${D}{${E.length},}[ \t]*$`),j=[],F=S+1;for(;F<s.length&&!k.test(g(s[F]??``));)j.push(s[F]??``),F++;if(O===`mermaid`){let e=j.join(`
|
|
826
826
|
`),s=(j.find(e=>e.trim().length>0)?.trim()??``).slice(0,MAX_FIRST_LINE_CHARS);t.push({firstLine:s,body:e})}S=F+1}return t}async function initMermaid(){let{Window:e}=await import(`./lib-CCQO9uWA.mjs`),t=new e({url:`http://localhost/`}),s={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},g=new Map;try{for(let[e,t]of Object.entries(s))g.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-LrO0u_wA.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
|
|
827
827
|
A-->B`),e}finally{for(let[e,t]of g)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function getMermaid(e){return initPromise??=initMermaid().catch(t=>(log$10.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),initPromise}function extractLineNumber(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:void 0}async function validateMermaidFences(e,t){try{if(!e.includes(`mermaid`))return;let{body:s}=detectFmRegion(e),g=extractMermaidFences(s);if(g.length===0)return;let S=performance.now(),w=await getMermaid(t);if(w===null)return;let E=performance.now(),D=[],O=0;for(let e=0;e<g.length&&D.length<MAX_WARNINGS&&!(O>=MAX_FENCES_PARSED);e++){if(performance.now()-E>TOTAL_PARSE_BUDGET_MS){log$10.debug({"doc.name":t,skippedFrom:e+1,fences:g.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let s=g[e];if(s!==void 0){if(s.body.length>MAX_FENCE_BYTES||s.body.split(`
|
|
828
|
-
`).length>MAX_FENCE_LINES){log$10.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$10.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$10.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$10.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$10.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g}},`share action`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
829
|
-
`).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,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}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,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{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){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const
|
|
830
|
-
`).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,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(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({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)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.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:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.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 g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})}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,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=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 quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,{env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}})}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}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)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:`discovery`,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},O;try{O=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 D(`failed`,void 0,`version-read-failed`),`failed`}let k=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(k!==null&&k===O){if(await centralSkillExists(t))return s.info?.({event:`skill-install.skip-current`,version:O},`OpenKnowledge skill already installed at current version; skipping.`),await D(`skip-current`,O),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:O,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let j;try{j=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await D(`failed`,O,`bundled-asset-missing`),`failed`}let F={...process.env,HOME:t};await removeLegacyUserSkill(t,g,F,S,s,E);let L=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,j,`--agent`,`*`,`-g`,`-y`,`--copy`],F,S,E);if(L.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,O,w,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 D(`failed`,O,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:O},`OpenKnowledge skill installed to detected agent hosts.`),await D(`installed`,O),`installed`}return L.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:L.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`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 ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`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 ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`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 g={detached:!0,stdio:`ignore`};try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).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)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.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,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.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 E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
|
|
828
|
+
`).length>MAX_FENCE_LINES){log$10.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$10.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$10.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$10.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$10.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind,S=t?.freshness;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g},...S===void 0?{}:{freshness:S}},`share action`)}function truncateError(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}const FRESHNESS_PROBE_TIMEOUT_MS=5e3;async function computeShareFreshness(e,t,s,g){try{let{git:g}=createGitInstance(e,{timeoutMs:FRESHNESS_PROBE_TIMEOUT_MS}),S=`refs/remotes/origin/${t}`;await g.raw([`rev-parse`,`--verify`,S]);let w=s===``?`.`:s,[E,D,O]=await Promise.all([g.raw([`cat-file`,`-e`,`${S}:${s}`]).then(()=>!0).catch(()=>!1),g.raw([`diff`,`--name-only`,S,`--`,w]),g.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,w])]);return E?D.trim()!==``||O.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=truncateError(e);getLogger(`share`).warn({action:`freshness-probe-failed`,kind:g,error:t},`[share] freshness probe failed; omitting freshness`);return}}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
829
|
+
`).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,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}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,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{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){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const SHARE_TARGET_STATUS_HANDLER_TAG=`share-target-status`,DEFAULT_FETCH_TIMEOUT_MS=15e3;function parseNameStatus(e){let t=[];for(let s of e.split(`
|
|
830
|
+
`)){if(s.trim()===``)continue;let e=s.split(` `),g=e[0]??``;(g.startsWith(`R`)||g.startsWith(`C`))&&e.length>=3?t.push({status:g,from:e[1]??``,to:e[2]??``}):t.push({status:g,from:e[1]??``,to:e[1]??``})}return t}function classifyDoc(e,t){for(let s of e)if(s.from===t){if(s.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:s.to};if(s.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function classifyFolder(e,t){let s=t.endsWith(`/`)?t:`${t}/`,g=new Set;for(let t of e){if(!t.from.startsWith(s)||!t.status.startsWith(`R`))continue;let e=t.from.slice(s.length);t.to.endsWith(`/${e}`)?g.add(t.to.slice(0,t.to.length-e.length-1)):g.add(`\0ambiguous`)}let S=g.size===1?[...g][0]:void 0;return S!==void 0&&S!==`\0ambiguous`?{verdict:`renamed`,renamedTo:S}:{verdict:`deleted`}}async function computeShareTargetStatus(e,t,s,g,S={}){let w=getLogger(`share`),E=e=>(w.info({action:`target-status`,verdict:e.verdict,kind:g},`target-status verdict`),e),{git:D}=createGitInstance(e,S.skipFetch?{}:{timeoutMs:S.fetchTimeoutMs??DEFAULT_FETCH_TIMEOUT_MS});if(!S.skipFetch)try{await D.raw([`fetch`,`origin`,t])}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status fetch failed`),E({verdict:`unknown`})}let O=`origin/${t}`;try{if(await D.raw([`cat-file`,`-e`,`${O}:${s}`]).then(()=>!0).catch(()=>!1)){let t=await D.raw([`cat-file`,`-e`,`HEAD:${s}`]).then(()=>!0).catch(()=>!1),g=existsSync(join(e,s));return E(t&&!g?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await D.raw([`log`,`-1`,`--format=%H`,O,`--`,s])).trim();if(t===``)return E({verdict:`never-on-branch`});let S=parseNameStatus(await D.raw([`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t])),w=g===`folder`?classifyFolder(S,s):classifyDoc(S,s);return w.verdict===`renamed`&&!await D.raw([`cat-file`,`-e`,`${O}:${w.renamedTo}`]).then(()=>!0).catch(()=>!1)?E({verdict:`deleted`}):E(w)}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status detection failed`),E({verdict:`unknown`})}}const BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},BUNDLE_IDS=Object.keys(BUNDLE_SKILL_NAME),BUNDLE_SCOPE={discovery:`user`,project:`project`,"write-skill":`user`},USER_GLOBAL_BUNDLE_IDS=BUNDLE_IDS.filter(e=>BUNDLE_SCOPE[e]===`user`);function bundleSkillMdPath(e){return`packages/server/assets/skills/${e}/SKILL.md`}const MAX_ZIP_BYTES=102400,DESKTOP_SKILLS_REL=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let s=t.platform??process.platform,g=t.checkDesktop??!1,S=t.home??homedir(),w=[];g&&s===`darwin`&&(w.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),w.push(join(S,`Applications`,DESKTOP_SKILLS_REL,e))),w.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of w)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${w.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 g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.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,s=computeWrapperFolderName(e)){let g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
|
|
831
|
+
`).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,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(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({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)}async function withSkillStateWriteLock(e,t){let s=skillStateYamlPath(e);await tracedMkdir(dirname(s),{recursive:!0});try{return await withFileLock(`${s}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.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:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.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 g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);await withSkillStateWriteLock(e,async()=>{let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})})}async function readBundleDecision(e,t,s){let g=(await readSkillStateFile(e,s).catch(()=>null))?.bundles?.[t];return typeof g?.enabled==`boolean`?g.enabled:null}async function writeBundleDecision(e,t,s,g){await withSkillStateWriteLock(e,async()=>{let S=await readSkillStateFile(e,g)??emptySkillState();await writeSkillStateFile(e,{...S,bundles:{...S.bundles,[t]:{enabled:s,decidedAt:new Date().toISOString()}}})})}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,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=6e4;function centralSkillDir(e,t){return join(e,`.agents`,`skills`,t)}async function centralSkillExists(e,t){try{return(await stat$1(centralSkillDir(e,t))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,{env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}})}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}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)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=e.bundleId??`discovery`,O=BUNDLE_SKILL_NAME[D],k=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:D,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},j;try{j=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 k(`failed`,void 0,`version-read-failed`),`failed`}let F=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(!e.force&&F!==null&&F===j){if(await centralSkillExists(t,O))return s.info?.({event:`skill-install.skip-current`,version:j},`OpenKnowledge skill already installed at current version; skipping.`),await k(`skip-current`,j),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:j,path:centralSkillDir(t,O)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let L;try{L=resolveBundledSkillDir(D,{checkDesktop:!1})}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 k(`failed`,j,`bundled-asset-missing`),`failed`}let B={...process.env,HOME:t};await removeLegacyUserSkill(t,g,B,S,s,E);let H=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,L,`--agent`,`*`,`-g`,`-y`,`--copy`],B,S,E);if(H.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,j,w,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 k(`failed`,j,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:j},`OpenKnowledge skill installed to detected agent hosts.`),await k(`installed`,j),`installed`}return H.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:H.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`timeout`),`failed`):H.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(H.error),stderr:H.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:H.exitCode,stderr:H.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`nonzero-exit:${H.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 g={detached:!0,stdio:`ignore`};try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).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)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.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,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.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 E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
|
|
831
832
|
`)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`OpenKnowledge requires ${g.product} ${t} or newer (detected ${e} at ${s}).`),S.push(``),g.options.length>0){S.push(`Update ${g.product}:`);for(let e of g.options){let t=e.requiresAdmin?` (admin required)`:``;S.push(` • ${e.label}${t}`),S.push(` ${e.command}`)}S.push(``)}return S.push(`Or download from: ${g.url}`),S.push(``),S.push(`After updating, re-run OpenKnowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
|
|
832
|
-
`)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$2=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$2.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$2.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$2.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$2.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$2.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$2.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$1=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$1.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$1.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}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$9=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$1()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);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),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$9.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$9.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$9.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,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 g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return 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 g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,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 g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,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 g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}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,t=`${e} does not exist`){super(t),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,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},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:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID$1().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}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 parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}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 g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
833
|
+
`)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$2=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$2.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$2.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$2.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$2.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$2.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$2.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$1=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$1.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$1.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}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,t){releaseProcessLock({lockName:`ui`,lockDir:e,...t})}function markUiLockDraining(e){markProcessLockDraining({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$9=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 g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);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),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$9.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$9.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$9.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,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 g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return 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 g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,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 g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,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 g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}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,t=`${e} does not exist`){super(t),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,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},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:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}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 parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}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 g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
833
834
|
`,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
|
|
834
835
|
`,s)].filter(e=>e>=0),w=g>=0?g+1:Math.max(0,t-60),E=S.length>0?Math.min(...S)+1:Math.min(e.length,s+60),D=w>0?`…`:``,O=E<e.length?`…`:``,k=normalizeSnippet$1(e.slice(w,E));return k?`${D}${k}${O}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,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 g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{text:e.slice(g,S),nextIndex:S+s};S+=t}return{text:e.slice(t,g),nextIndex:g}}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let s=WIKI_LINK_RE$1.exec(e);if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function extractWikiLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let w=readWikiLink$1(e,S);if(w){let e=getWikiLinkText(w),E=s.length;s+=e;let D=classifyWikiLinkTarget(w.target,w.anchor);if(D?.kind===`doc`){let s=resolveSkillBundleWikiTarget(w.target,t)??D.docName;g.push({target:s,anchor:D.anchor,start:E,end:E+e.length})}S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractExternalWikiLinksFromLine(e){let t=``,s=[],g=leadingMarkdownPrefixLength$1(e);for(;g<e.length;){if(e[g]===`\\`&&g+1<e.length){t+=e[g+1],g+=2;continue}if(e[g]==="`"){let s=readInlineCode$1(e,g);if(s){t+=s.text,g=s.nextIndex;continue}}if(e[g]===`[`&&e[g+1]===`[`){let S=readWikiLink$1(e,g);if(S){let e=getWikiLinkText(S),w=t.length;t+=e;let E=classifyWikiLinkTarget(S.target,S.anchor);E?.kind===`external`&&s.push({url:E.url,label:e,start:w,end:w+e.length}),g=S.nextIndex;continue}}t+=e[g],g++}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=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(e?.kind===`doc`){let t=s.length;s+=w.text,g.push({target:e.docName,anchor:e.anchor,start:t,end:t+w.text.length})}else s+=w.text;S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractExternalMarkdownLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(s+=w.text,e?.kind===`external`){let t=s.length-w.text.length;g.push({url:e.url,label:w.text||null,start:t,end:t+w.text.length})}S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractMarkdownLinksFromMarkdown(e,t){let s=e.replaceAll(`\r
|
|
835
836
|
`,`
|
|
@@ -851,9 +852,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
851
852
|
`,`
|
|
852
853
|
`).replaceAll(`\r`,`
|
|
853
854
|
`).split(`
|
|
854
|
-
`),D=[],O=new Set,k=null,j=(e,t,s)=>{O.has(e)||(O.add(e),D.push({href:e,resolvedTo:t,reason:s}))},F=e=>{let s=e.trim();if(s.startsWith(`#`))return;let w=classifyMarkdownHref(s,t);if(!w){j(s,null,`unresolvable`);return}if(w.kind===`doc`){S.has(w.docName)||j(s,w.docName,`no-such-doc`);return}if(w.kind===`asset`){if(!g)return;let e=resolveAssetProjectPath(w.url,t);if(e===null){j(s,null,`unresolvable`);return}g(e)||j(s,e,`no-such-file`);return}},L=(e,t)=>{let s=classifyWikiLinkTarget(e,t);!s||s.kind!==`doc`||S.has(s.docName)||j(`[[${e}${t?`#${t}`:``}]]`,s.docName,`no-such-doc`)};for(let e of E){if(k){isFenceClose$1(e,k)&&(k=null);continue}let t=matchFence$1(e);if(t){k=t;continue}let s=leadingMarkdownPrefixLength$1(e);for(;s<e.length;){if(e[s]===`\\`&&s+1<e.length){s+=2;continue}if(e[s]==="`"){let t=readInlineCode$1(e,s);if(t){s=t.nextIndex;continue}}if(e[s]===`[`&&e[s+1]===`[`){let t=readWikiLink$1(e,s);if(t){L(t.target,t.anchor),s=t.nextIndex;continue}}if(e[s]===`[`&&e[s-1]!==`!`){let t=readMarkdownLink$1(e,s);if(t){F(t.href),s=t.nextIndex;continue}}s++}}return D}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let s=parseSkillBundleDocAnyScope(e),g=new Set;if(!s)return g;let S=this.getState(t);if(!S.forward.has(e))return g;if(s.kind===`skill`)for(let t of S.forward.keys()){let s=parseSkillBundleDocAnyScope(t);s?.kind===`reference`&&s.skillDocName===e&&g.add(t)}else S.forward.has(s.skillDocName)&&g.add(s.skillDocName);return g}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.set(e,new Set),s.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){parseGlobalSkillBundleDoc(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,s=[],g=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;if(parseGlobalSkillBundleDoc(e)){this.registerNodeOnly(e,g);return}let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;let t=managedArtifactDocNameFromContentTarget(s.target)??s.target;D.add(t);let g=S.backward.get(t);g||(g=new Map,S.backward.set(t,g)),g.set(e,mergeLinkMeta(g.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g,e),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=new Map;if(s)for(let[e,t]of s)g.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let s of this.structuralBundleNeighbors(e,t))g.has(s)||g.set(s,{source:s,anchor:null,snippet:null});return[...g.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=this.structuralBundleNeighbors(e,t);if(g.size===0)return s?.size??0;let S=new Set(s?.keys()??[]);for(let e of g)S.add(e);return S.size}getForwardLinks(e,t=this.activeBranch){let s=this.getState(t),g=new Set(s.forward.get(e)??new Set);for(let s of this.structuralBundleNeighbors(e,t))g.add(s);return[...g].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s),S=new Set;for(let e of g.forward.keys()){let t=parseSkillBundleDocAnyScope(e);t?.kind===`reference`&&S.add(t.skillDocName)}let w=e=>{let t=parseSkillBundleDocAnyScope(e);return!t||!g.forward.has(e)?!1:t.kind===`skill`?S.has(e):g.forward.has(t.skillDocName)};return[...e].filter(e=>{let s=w(e),S=s||(g.backward.get(e)?.size??0)>0,E=s||(g.forward.get(e)?.size??0)>0;return t===`incoming`?!S:(t===`outgoing`||!S)&&!E}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e)||g.forward.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}for(let S of t.forward.keys())if(parseSkillBundleDocAnyScope(S)?.kind===`skill`)for(let w of this.structuralBundleNeighbors(S,e))t.forward.get(S)?.has(w)||t.forward.get(w)?.has(S)||(s.set(S,{kind:`doc`,id:S,docName:S,anchor:getRepresentativeAnchor(t.backward.get(S))}),s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:S,target:w}));return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let S=externalUrlFromNodeId(e.nodeId),O=new Set;if(S)for(let e of g.externalBackward.get(S)?.keys()??[])O.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)O.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])O.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])O.add(t);for(let t of this.structuralBundleNeighbors(e.nodeId,s))O.add(t)}for(let t of O)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}for(let e of w)if(parseSkillBundleDocAnyScope(e)?.kind===`skill`)for(let t of this.structuralBundleNeighbors(e,s))w.has(t)&&(g.forward.get(e)?.has(t)||g.forward.get(t)?.has(e)||O.push({source:e,target:t}));return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E,g),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;let s=managedArtifactDocNameFromContentTarget(e.target)??e.target;q.add(s);let S=t.backward.get(s);S||(S=new Map,t.backward.set(s,S)),S.set(g,mergeLinkMeta(S.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of B)parseGlobalSkillBundleDoc(t)||w.has(t)||(this.deleteDocument(t,e),L++);return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let s=new Set;for(let g of e){if(!existsSync(g))continue;let e;try{e=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[backlinks] Failed to read global skills root ${g}:`,e);continue}for(let S of e){if(!S.isDirectory())continue;let e=S.name,w=join(g,e),E=skillLiveDocName(`global`,e);existsSync(join(w,`SKILL.md`))&&parseGlobalSkillBundleDoc(E)&&(this.registerNodeOnly(E,t),s.add(E));let D=[];await this.walkGlobalSkillReferences(join(w,`references`),e,``,D);for(let{docName:e}of D)this.registerNodeOnly(e,t),s.add(e)}}let g=[];for(let e of this.getState(t).forward.keys())parseGlobalSkillBundleDoc(e)&&!s.has(e)&&g.push(e);for(let e of g)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,s,g){let S;try{S=await readdir(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&console.warn(`[backlinks] Failed to read skill references dir ${e}:`,t);return}for(let w of S){let S=s?`${s}/${w.name}`:w.name;if(w.isDirectory())await this.walkGlobalSkillReferences(join(e,w.name),t,S,g);else if(w.isFile()&&isSupportedDocFile(w.name)){let e=stripDocExtension(S);g.push({docName:`${MANAGED_ARTIFACT_PREFIX_SKILL}global/${t}/references/${e}`})}}}};let current,bootStartMono;function startBootTimings(e=new Date().toISOString()){current={startedAt:e},bootStartMono=performance.now()}function bootElapsedMs(){if(bootStartMono!==void 0)return Math.round(performance.now()-bootStartMono)}function recordBootPhase(e,t){current&&(current[e]=t)}function setBootField(e,t){current&&(current[e]=t)}function getBootTimings(){return current}function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}function parsePorcelainPaths(e){let t=[];for(let s of e.split(`
|
|
855
|
-
`)){if(s.length<4)continue;let e=s.slice(3),g=e.indexOf(` -> `),S=g>=0?e.slice(g+4):e;S.length>0&&t.push(S)}return t}function parseDiffPaths(e){return e.split(`
|
|
856
|
-
`).map(e=>e.trim()).filter(e=>e.length>0)}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([s.raw([`status`,`--porcelain`]),s.raw([`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(parsePorcelainPaths(g));if(w.size===0)return{conflicts:!1,files:[]};let E=parseDiffPaths(S);if(E.length===0)return{conflicts:!1,files:[]};let D=new Set;for(let e of E)w.has(e)&&D.add(e);return D.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(D).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=e instanceof Error?e.message:String(e),g=s.length>500?`${s.slice(0,500)}…`:s;return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${g}`),{conflicts:!1,files:[]}}),[k,j,F,L]=await Promise.all([w,E,D,O]);return k.detached?{detached:!0,currentBranch:null,currentHeadSha:k.currentHeadSha,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}:{detached:!1,currentBranch:k.currentBranch,currentHeadSha:null,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t){let{git:s}=createGitInstance(e),g=await s.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!g)try{await s.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let S=await dirtyFilesOverlapWith(e,g?t:`origin/${t}`);if(S.conflicts)return{ok:!1,reason:`dirty-conflict`,files:S.files};try{return await s.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=e instanceof Error?e.message:String(e),S=g.length>500?`${g.slice(0,500)}…`:g;return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${S}`),{ok:!1,reason:`checkout-failed`}}}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
|
|
855
|
+
`),D=[],O=new Set,k=null,j=(e,t,s)=>{O.has(e)||(O.add(e),D.push({href:e,resolvedTo:t,reason:s}))},F=e=>{let s=e.trim();if(s.startsWith(`#`))return;let w=classifyMarkdownHref(s,t);if(!w){j(s,null,`unresolvable`);return}if(w.kind===`doc`){S.has(w.docName)||j(s,w.docName,`no-such-doc`);return}if(w.kind===`asset`){if(!g)return;let e=resolveAssetProjectPath(w.url,t);if(e===null){j(s,null,`unresolvable`);return}g(e)||j(s,e,`no-such-file`);return}},L=(e,t)=>{let s=classifyWikiLinkTarget(e,t);!s||s.kind!==`doc`||S.has(s.docName)||j(`[[${e}${t?`#${t}`:``}]]`,s.docName,`no-such-doc`)};for(let e of E){if(k){isFenceClose$1(e,k)&&(k=null);continue}let t=matchFence$1(e);if(t){k=t;continue}let s=leadingMarkdownPrefixLength$1(e);for(;s<e.length;){if(e[s]===`\\`&&s+1<e.length){s+=2;continue}if(e[s]==="`"){let t=readInlineCode$1(e,s);if(t){s=t.nextIndex;continue}}if(e[s]===`[`&&e[s+1]===`[`){let t=readWikiLink$1(e,s);if(t){L(t.target,t.anchor),s=t.nextIndex;continue}}if(e[s]===`[`&&e[s-1]!==`!`){let t=readMarkdownLink$1(e,s);if(t){F(t.href),s=t.nextIndex;continue}}s++}}return D}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let s=parseSkillBundleDocAnyScope(e),g=new Set;if(!s)return g;let S=this.getState(t);if(!S.forward.has(e))return g;if(s.kind===`skill`)for(let t of S.forward.keys()){let s=parseSkillBundleDocAnyScope(t);s?.kind===`reference`&&s.skillDocName===e&&g.add(t)}else S.forward.has(s.skillDocName)&&g.add(s.skillDocName);return g}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.set(e,new Set),s.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){parseGlobalSkillBundleDoc(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,s=[],g=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;if(parseGlobalSkillBundleDoc(e)){this.registerNodeOnly(e,g);return}let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;let t=managedArtifactDocNameFromContentTarget(s.target)??s.target;D.add(t);let g=S.backward.get(t);g||(g=new Map,S.backward.set(t,g)),g.set(e,mergeLinkMeta(g.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g,e),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=new Map;if(s)for(let[e,t]of s)g.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let s of this.structuralBundleNeighbors(e,t))g.has(s)||g.set(s,{source:s,anchor:null,snippet:null});return[...g.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=this.structuralBundleNeighbors(e,t);if(g.size===0)return s?.size??0;let S=new Set(s?.keys()??[]);for(let e of g)S.add(e);return S.size}getForwardLinks(e,t=this.activeBranch){let s=this.getState(t),g=new Set(s.forward.get(e)??new Set);for(let s of this.structuralBundleNeighbors(e,t))g.add(s);return[...g].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s),S=new Set;for(let e of g.forward.keys()){let t=parseSkillBundleDocAnyScope(e);t?.kind===`reference`&&S.add(t.skillDocName)}let w=e=>{let t=parseSkillBundleDocAnyScope(e);return!t||!g.forward.has(e)?!1:t.kind===`skill`?S.has(e):g.forward.has(t.skillDocName)};return[...e].filter(e=>{let s=w(e),S=s||(g.backward.get(e)?.size??0)>0,E=s||(g.forward.get(e)?.size??0)>0;return t===`incoming`?!S:(t===`outgoing`||!S)&&!E}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e)||g.forward.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}for(let S of t.forward.keys())if(parseSkillBundleDocAnyScope(S)?.kind===`skill`)for(let w of this.structuralBundleNeighbors(S,e))t.forward.get(S)?.has(w)||t.forward.get(w)?.has(S)||(s.set(S,{kind:`doc`,id:S,docName:S,anchor:getRepresentativeAnchor(t.backward.get(S))}),s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:S,target:w}));return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let S=externalUrlFromNodeId(e.nodeId),O=new Set;if(S)for(let e of g.externalBackward.get(S)?.keys()??[])O.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)O.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])O.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])O.add(t);for(let t of this.structuralBundleNeighbors(e.nodeId,s))O.add(t)}for(let t of O)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}for(let e of w)if(parseSkillBundleDocAnyScope(e)?.kind===`skill`)for(let t of this.structuralBundleNeighbors(e,s))w.has(t)&&(g.forward.get(e)?.has(t)||g.forward.get(t)?.has(e)||O.push({source:e,target:t}));return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E,g),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;let s=managedArtifactDocNameFromContentTarget(e.target)??e.target;q.add(s);let S=t.backward.get(s);S||(S=new Map,t.backward.set(s,S)),S.set(g,mergeLinkMeta(S.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of B)parseGlobalSkillBundleDoc(t)||w.has(t)||(this.deleteDocument(t,e),L++);return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let s=new Set;for(let g of e){if(!existsSync(g))continue;let e;try{e=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[backlinks] Failed to read global skills root ${g}:`,e);continue}for(let S of e){if(!S.isDirectory())continue;let e=S.name,w=join(g,e),E=skillLiveDocName(`global`,e);existsSync(join(w,`SKILL.md`))&&parseGlobalSkillBundleDoc(E)&&(this.registerNodeOnly(E,t),s.add(E));let D=[];await this.walkGlobalSkillReferences(join(w,`references`),e,``,D);for(let{docName:e}of D)this.registerNodeOnly(e,t),s.add(e)}}let g=[];for(let e of this.getState(t).forward.keys())parseGlobalSkillBundleDoc(e)&&!s.has(e)&&g.push(e);for(let e of g)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,s,g){let S;try{S=await readdir(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&console.warn(`[backlinks] Failed to read skill references dir ${e}:`,t);return}for(let w of S){let S=s?`${s}/${w.name}`:w.name;if(w.isDirectory())await this.walkGlobalSkillReferences(join(e,w.name),t,S,g);else if(w.isFile()&&isSupportedDocFile(w.name)){let e=stripDocExtension(S);g.push({docName:`${MANAGED_ARTIFACT_PREFIX_SKILL}global/${t}/references/${e}`})}}}};let current,bootStartMono;function startBootTimings(e=new Date().toISOString()){current={startedAt:e},bootStartMono=performance.now()}function bootElapsedMs(){if(bootStartMono!==void 0)return Math.round(performance.now()-bootStartMono)}function recordBootPhase(e,t){current&&(current[e]=t)}function setBootField(e,t){current&&(current[e]=t)}function getBootTimings(){return current}function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}function parsePorcelainPaths(e){let t=[],s=e.split(`\0`);for(let e=0;e<s.length;e++){let g=s[e]??``;g.length<4||(t.push(g.slice(3)),(g[0]===`R`||g[0]===`C`)&&e++)}return t}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([s.raw([`status`,`--porcelain`,`-z`]),s.raw([`diff`,`--name-only`,`-z`,`HEAD..${t}`])]),w=new Set(parsePorcelainPaths(g));if(w.size===0)return{conflicts:!1,files:[]};let E=splitNulSeparatedPaths(S);if(E.length===0)return{conflicts:!1,files:[]};let D=new Set;for(let e of E)w.has(e)&&D.add(e);return D.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(D).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=(async()=>{let e=`origin/${t}`;if(await S.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return g===`folder`&&s===``?!0:S.raw([`cat-file`,`-e`,`${e}:${s}`]).then(()=>!0).catch(()=>!1)})(),k=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=truncateError(e);return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${s}`),{conflicts:!1,files:[]}}),[j,F,L,B,H]=await Promise.all([w,E,D,k,O]);return j.detached?{detached:!0,currentBranch:null,currentHeadSha:j.currentHeadSha,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}:{detached:!1,currentBranch:j.currentBranch,currentHeadSha:null,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const FF_FETCH_TIMEOUT_MS=15e3,BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t,s){if(s?.fastForward&&await fastForwardBranchToOrigin(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:g}=createGitInstance(e),S=await g.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!S)try{await g.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let w=await dirtyFilesOverlapWith(e,S?t:`origin/${t}`);if(w.conflicts)return{ok:!1,reason:`dirty-conflict`,files:w.files};try{return await g.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=truncateError(e);return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${g}`),{ok:!1,reason:`checkout-failed`}}}async function fastForwardBranchToOrigin(e,t){let{git:s}=createGitInstance(e,{timeoutMs:FF_FETCH_TIMEOUT_MS}),g=e=>s.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await s.raw([`fetch`,`origin`,t])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-fetch-failed branch=${t} error=${s}`),`unavailable`}let S=await g(`refs/remotes/origin/${t}`);if(!S)return`unavailable`;let w=await g(`refs/heads/${t}`);if(!w||w===S)return`up-to-date`;let E=await s.raw([`merge-base`,w,S]).then(e=>e.trim()).catch(()=>``);if(E===w){try{await s.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-advance-failed branch=${t} error=${s}`),`unavailable`}return await g(`refs/heads/${t}`)===S?`advanced`:`unavailable`}return E===S?`up-to-date`:`diverged`}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
|
|
857
856
|
# OpenKnowledge — project configuration
|
|
858
857
|
#
|
|
859
858
|
# This file overrides built-in defaults for this project. Every key below
|
|
@@ -954,7 +953,7 @@ last-spawn-error.log
|
|
|
954
953
|
`,ROOT_GITIGNORE_TEMPLATE=`# Seeded by OpenKnowledge when this project was created. Edit freely.
|
|
955
954
|
.DS_Store
|
|
956
955
|
`;function initContent(e,t){let s=resolve(e,`.ok`),g=[],S=[],w=[];assertNotSymlink(s,`.ok/`),tracedMkdirSync(s,{recursive:!0});let E=ensureGitignoreEntries(join(s,`.gitignore`),OK_GITIGNORE_CONTENT);return E===`created`?g.push(`.gitignore`):E===`updated`?S.push(`.gitignore`):w.push(`.gitignore`),writeIfMissing(join(s,`config.yml`),buildConfigYmlContent(t?.packageVersion??`0.0.0`,{contentDir:t?.contentDir}),`.ok/config.yml`)?g.push(CONFIG_FILENAME):w.push(CONFIG_FILENAME),writeIfMissing(join(e,`.okignore`),OK_OKIGNORE_TEMPLATE,`.okignore`)?g.push(`.okignore`):w.push(`.okignore`),{created:g,updated:S,skipped:w}}function writeRootGitignoreForNewRepo(e){return writeIfMissing(join(e,`.gitignore`),ROOT_GITIGNORE_TEMPLATE,`.gitignore`)?`created`:`skipped`}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function ancestorChainHasSymlink(e,t){let s=dirname(e);for(;s!==t&&s!==dirname(s);){let e;try{e=lstatSync(s)}catch(e){let t=e.code;return console.warn(`[local-op-security] ancestorChainHasSymlink: lstat failed on ${s} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${s}`),!0;s=dirname(s)}return!1}function isPathWithinHome(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let s;try{s=realpathSync(t)}catch(e){let s=e.code;return console.warn(`[local-op-security] realpath failed on home dir ${t} (${s??`unknown`}); rejecting all paths`),!1}let g=resolve(expandTilde(e)),S=[],w=g;for(;;){let e=null;try{e=lstatSync(w)}catch(e){let t=e.code;if(t!==`ENOENT`)return console.warn(`[local-op-security] lstat error at ${w} (${t??`unknown`}); rejecting`),!1}if(e!==null){let g;try{g=realpathSync(w)}catch(s){let S=s.code;if(e.isSymbolicLink())return console.warn(`[local-op-security] realpath failed on symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1;if(S===`EPERM`||S===`EACCES`){if(ancestorChainHasSymlink(w,t))return console.warn(`[local-op-security] EPERM accept-branch refused at ${w}: symlinked ancestor in chain; rejecting`),!1;console.warn(`[local-op-security] realpath denied on non-symlink leaf at ${w} (${S??`unknown`}); trusting lexical path (TCC-class)`),g=w}else return console.warn(`[local-op-security] realpath failed on non-symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1}let E=S.length===0?g:join(g,...S),D=relative(s,E);return D===``||!D.startsWith(`..`)&&!isAbsolute(D)}let g=dirname(w);if(g===w)return!1;S.unshift(basename(w)),w=g}}function isSafeLocalPath(e){return isPathWithinHome(e,homedir())}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,s){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:s.handler}),!1):(errorResponse(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:s.handler}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function runSubprocess(e){let[t,...s]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let g=[...s,...e.trailingArgs],S=!1,w=!1,E=``,D=[],O={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(O.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(delimiter));let k=spawn(t,g,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`],env:O}),j=setTimeout(()=>{S=!0,k.kill(`SIGTERM`)},e.timeoutMs),F=t=>{if(!t.trim())return;let s=null;try{let e=JSON.parse(t);s=e&&typeof e==`object`?e:null}catch{s=null}e.onLine({raw:t,parsed:s})};return k.stdout.on(`data`,e=>{E+=e.toString(`utf-8`);let t=E.split(`
|
|
957
|
-
`);E=t.pop()??``;for(let e of t)F(e)}),k.stderr.on(`data`,t=>{D.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{k.on(`close`,t=>{clearTimeout(j),E.trim()&&F(E),E=``,e({code:t,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})}),k.on(`error`,t=>{clearTimeout(j),D.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})})}),cancel:()=>{if(!w&&(w=!0,!k.killed))try{k.kill(`SIGTERM`)}catch{}}}}const DEFAULT_TIMEOUT_MS$3=600*1e3;function asAuthEvent(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runDeviceFlowSubprocess(e){let t=e.host??`github.com`,s=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,g=!1,S=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asAuthEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(g=!0),e.onEvent(s))}});return{done:S.done.then(s=>{g||(s.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:s.timedOut?`Sign-in timed out`:`auth login exited with code ${s.code??-1}`}))}),cancel:S.cancel}}const DEFAULT_TIMEOUT_MS$2=3e4;async function runAuthStatusSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`status`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`status`)continue;let S=typeof g.host==`string`?g.host:t;if(g.authenticated===!0&&typeof g.login==`string`){let e=g.tier===`A`||g.tier===`B`||g.tier===`C`?g.tier:void 0;return{authenticated:!0,host:S,login:g.login,tier:e,name:typeof g.name==`string`?g.name:void 0,email:typeof g.email==`string`?g.email:void 0}}return{authenticated:!1,host:S,error:typeof g.error==`string`?g.error:void 0}}return{authenticated:!1,host:t,error:g.timedOut?`auth status timed out`:g.code===0?void 0:g.stderr||`auth status exited with code ${g.code??-1}`}}async function runAuthReposSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`repos`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;if(g.timedOut)return{ok:!1,error:`auth repos timed out`};if(g.code!==0)return{ok:!1,error:g.stderr||`auth repos exited with code ${g.code??-1}`};for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`repos`||!Array.isArray(g.repos))continue;let S=[];for(let e of g.repos){if(!e||typeof e!=`object`)continue;let t=e;typeof t.full_name!=`string`||typeof t.clone_url!=`string`||S.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private===!0})}return{ok:!0,host:typeof g.host==`string`?g.host:t,repos:S}}return{ok:!1,error:`auth repos returned no data`}}const GENERIC_TITLE=`Clone subprocess reported an error.`,MAX_DETAIL_LEN=500;function classifyCloneError(e){let t=redactShareSubprocessStderr(e).trim().slice(0,MAX_DETAIL_LEN);return t.length===0?{title:GENERIC_TITLE,detail:``}:/repository not found|returned error:\s*404/i.test(t)?{title:`Can't access this repository. It may be private, or you may not have access.`,detail:t}:/permission denied|access denied|returned error:\s*403/i.test(t)?{title:`You don't have access to this repository.`,detail:t}:/authentication failed/i.test(t)?{title:`GitHub authentication failed. Try signing in again.`,detail:t}:{title:GENERIC_TITLE,detail:t}}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const log$8=getLogger(`clone-flow`),DEFAULT_TIMEOUT_MS$1=600*1e3;function validateCloneInputs(e,t){return isAllowedGitUrl(e)?isSafeLocalPath(t)?{ok:!0}:{ok:!1,reason:`invalid-dir`}:{ok:!1,reason:`invalid-url`}}function asRawCloneEvent(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`branch-fallback`?typeof e.branch==`string`&&e.branch.length>0?{type:`branch-fallback`,branch:e.branch}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runCloneSubprocess(e){let t=expandTilde(e.dir),s=e.timeoutMs??DEFAULT_TIMEOUT_MS$1,g;try{g=assertGitAvailable()}catch(t){t instanceof GitNotAvailableError||t instanceof GitTooOldError?(emitPreflightFailureSpan(t),log$8.warn({event:`git_preflight_fail`,platform:t.platform,reason:t instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:t instanceof GitTooOldError?t.detected:``},t instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log$8.error({event:`clone_preflight_unexpected_error`,err:t},`unexpected error during clone preflight`);let s=t instanceof Error?t.message:String(t);return{done:Promise.resolve().then(()=>{e.onEvent({type:`error`,message:s})}),cancel:()=>{}}}let S=isAbsolute(g.resolvedPath)?[dirname(g.resolvedPath)]:[],w=!1,E=typeof e.branch==`string`&&e.branch.length>0?[`-b`,e.branch]:[],D=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,...E,e.url,t],extraPathDirs:S,timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asRawCloneEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(w=!0),e.onEvent(s))}});return{done:D.done.then(s=>{if(!w){if(s.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(s.code!==0){let t=s.stderr?` — ${s.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${s.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:D.cancel}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let s=e.slice(1,t),g=e.slice(t+1);return g!==``&&!/^:\d+$/.test(g)?!1:s===`::1`}let t=e.lastIndexOf(`:`),s=t>=0?e.slice(0,t):e,g=t>=0?e.slice(t+1):null;return g!==null&&!/^\d+$/.test(g)?!1:!!(s===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return getLocalDir(e)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenamePathSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function isManagedRenameCleanupPath(e){return typeof e==`string`&&e.length>0}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,s=e.pathSnapshots,g=e.cleanupPaths,S=Array.isArray(s)&&s.length>0,w=Array.isArray(g)&&g.length>0;if(!Array.isArray(t)||!t.every(isManagedRenameAffectedDoc)||t.length===0&&!S&&!w)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);if(s!==void 0&&(!Array.isArray(s)||!s.every(isManagedRenamePathSnapshot)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(g!==void 0&&(!Array.isArray(g)||!g.every(isManagedRenameCleanupPath)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let s of t)if(!e.snapshots.some(e=>e.docName===s.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${s.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...S?{pathSnapshots:s}:{},...w?{cleanupPaths:g}:{}}}function parseV1(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let s=managedRenameJournalPath(e);tracedMkdirSync(dirname(s),{recursive:!0});let g=`${s}.tmp`;tracedWriteFileSync(g,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(g,s)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,s){writeManagedRenameJournal(e,t);let g=await s();return clearManagedRenameJournal(e),g}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function resolveRecoveryPath(e,t){let s=resolve(e),g=resolve(s,t);if(t.includes(`\0`)||g===s||!g.startsWith(`${s}${sep}`))throw Error(`Invalid recovery path: ${t}`);return g}function pruneEmptyAncestors(e,t){let s=resolve(t),g=`${s}${sep}`,S=dirname(e);for(;S.startsWith(g)&&S!==s;){let e;try{e=readdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${S}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${S}:`,e);return}S=dirname(S)}}function recoverPendingManagedRename(e,t=e){let s=readManagedRenameJournal(t);if(!s)return{recovered:!1,journal:null,restoredDocNames:[]};let g=new Set,S=new Set,w=[];for(let t of s.snapshots)try{let s=safeContentPath(t.docName,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t.content,`utf-8`),g.add(t.docName)}catch(e){w.push({docName:t.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${t.docName}:`,e)}if(w.length>0){let e=w.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=w.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(s.version===2){let t=[];for(let g of s.pathSnapshots??[])try{let t=resolveRecoveryPath(e,g.path);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,g.content,`utf-8`),S.add(g.path)}catch(e){t.push({path:g.path,cause:e}),console.warn(`[managed-rename] Failed to restore path ${g.path}:`,e)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let s=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(s,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let E=s.version===2?destinationsToCleanV2(s):destinationsToCleanV1(s),D=[];for(let t of E){if(g.has(t))continue;let s=safeContentPath(t,e);try{tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){existsSync(s)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),D.push({destination:t,cause:e})}}if(s.version===2)for(let t of s.cleanupPaths??[]){if(S.has(t))continue;let s=null;try{s=resolveRecoveryPath(e,t),tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){s&&existsSync(s)&&console.warn(`[managed-rename] Both source and destination paths exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination path ${t}:`,e),D.push({destination:t,cause:e})}}if(D.length>0){let e=D.map(e=>e.destination).join(`, `),t=D.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return clearManagedRenameJournal(t),{recovered:!0,journal:s,restoredDocNames:[...g].sort((e,t)=>e.localeCompare(t))}}const PROJECT_SKILL_EDITOR_LABELS={claude:`Claude Code`,cursor:`Cursor`,codex:`Codex`},PLATFORM_SKILL_NAME=BUNDLE_SKILL_NAME.project;function resolvePackSkillSource(e){let t;try{t=resolveBundledSkillDir(`packs/${e}`,{checkDesktop:!0})}catch{return null}return{name:`open-knowledge-pack-${e}`,sourceDir:t}}async function installPackSkill(e,t){let s=resolvePackSkillSource(t);if(!s)return[];let{name:g,sourceDir:S}=s,w=join(e,`.ok`,`skills`,g);if(!existsSync(join(w,`SKILL.md`)))try{tracedRmSync(w,{recursive:!0,force:!0}),tracedMkdirSync(join(e,`.ok`,`skills`),{recursive:!0}),tracedCpSync(S,w,{recursive:!0})}catch(e){return getLogger(`seed`).warn({err:e,packId:t,okSkillDir:w},`pack skill source authoring failed — skill not installed`),[]}let E=projectSkill(w,g,e,PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_SKILL_ROOT[t];return s===null?!1:existsSync(join(e,s,PLATFORM_SKILL_NAME,`SKILL.md`))})),D=E.map(e=>PROJECT_SKILL_EDITOR_LABELS[e]??e);if(E.length>0)try{await recordSkillInstall(e,g,{hosts:E,scope:`project`,scripts:existsSync(join(w,`scripts`)),installedAt:new Date().toISOString()})}catch{}return D}var SeedPrerequisiteError=class extends Error{constructor(e){super(e),this.name=`SeedPrerequisiteError`}},SeedRootDirError=class extends Error{constructor(e){super(e),this.name=`SeedRootDirError`}};function assertEntryPathInProject(e,t){if(typeof t!=`string`||t===``)throw new SeedRootDirError(`entry path must be a non-empty string, got: ${typeof t}`);if(t.includes(`\0`))throw new SeedRootDirError(`entry path must not contain null bytes`);if(isAbsolute(t))throw new SeedRootDirError(`entry path must be relative, got: ${t}`);if(t.split(/[/\\]/).some(e=>e===`..`))throw new SeedRootDirError(`entry path must not contain '..' segments, got: ${t}`);let s=resolve(e),g=resolve(s,t);if(g!==s&&!g.startsWith(s+sep))throw new SeedRootDirError(`entry path must resolve inside the project directory, got: ${t}`);return assertNoSymlinkEscape$1(g,s),g}function assertNoSymlinkEscape$1(e,t){let s;try{s=realpathSync(t)}catch{return}let g=e;for(;;){if(existsSync(g)){let t;try{t=realpathSync(g)}catch(t){throw t.code===`ELOOP`?new SeedRootDirError(`entry path traverses a symlink cycle: ${e}`):t}if(t!==s&&!t.startsWith(s+sep))throw new SeedRootDirError(`entry path resolves outside the project directory via symlink: ${e}`);return}let t=dirname(g);if(t===g)throw new SeedRootDirError(`entry path has no existing ancestor inside the project directory: ${e}`);g=t}}const DEFAULT_PACK_ID=`knowledge-base`,KNOWLEDGE_BASE_FOLDERS=[{path:`external-sources`,title:`External Sources`,description:"Raw sources saved verbatim — the fetched text of URLs, extracted PDFs, and copied files, each with the original URL and access date in frontmatter. Produced by `ingest`. Immutable after capture; no analysis here (that goes in `research/`).",tags:[`source`,`immutable`,`layer-ingest`],starterTemplate:`clip`},{path:`research`,title:`Research`,description:"Provisional analysis that synthesizes the external sources. Every claim cites a doc in `external-sources/`; `status: provisional`. Promoted to `articles/` via `consolidate` once the findings are stable.",tags:[`research`,`provisional`,`layer-research`],starterTemplate:`research-log`},{path:`articles`,title:`Articles`,description:"Canonical knowledge, committed after a team decision. The source of truth for the domain; carries a `supersedes:` chain back to the `research/` docs it replaces.",tags:[`article`,`canonical`,`layer-consolidate`],starterTemplate:`article`}],KNOWLEDGE_BASE_TEMPLATES={clip:`---
|
|
956
|
+
`);E=t.pop()??``;for(let e of t)F(e)}),k.stderr.on(`data`,t=>{D.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{k.on(`close`,t=>{clearTimeout(j),E.trim()&&F(E),E=``,e({code:t,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})}),k.on(`error`,t=>{clearTimeout(j),D.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})})}),cancel:()=>{if(!w&&(w=!0,!k.killed))try{k.kill(`SIGTERM`)}catch{}}}}const DEFAULT_TIMEOUT_MS$3=600*1e3;function asAuthEvent(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runDeviceFlowSubprocess(e){let t=e.host??`github.com`,s=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,g=!1,S=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asAuthEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(g=!0),e.onEvent(s))}});return{done:S.done.then(s=>{g||(s.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:s.timedOut?`Sign-in timed out`:`auth login exited with code ${s.code??-1}`}))}),cancel:S.cancel}}const DEFAULT_TIMEOUT_MS$2=3e4;async function runAuthStatusSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`status`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`status`)continue;let S=typeof g.host==`string`?g.host:t;if(g.authenticated===!0&&typeof g.login==`string`){let e=g.tier===`A`||g.tier===`B`||g.tier===`C`?g.tier:void 0;return{authenticated:!0,host:S,login:g.login,tier:e,name:typeof g.name==`string`?g.name:void 0,email:typeof g.email==`string`?g.email:void 0}}return{authenticated:!1,host:S,error:typeof g.error==`string`?g.error:void 0}}return{authenticated:!1,host:t,error:g.timedOut?`auth status timed out`:g.code===0?void 0:g.stderr||`auth status exited with code ${g.code??-1}`}}async function runAuthReposSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`repos`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;if(g.timedOut)return{ok:!1,error:`auth repos timed out`};if(g.code!==0)return{ok:!1,error:g.stderr||`auth repos exited with code ${g.code??-1}`};for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`repos`||!Array.isArray(g.repos))continue;let S=[];for(let e of g.repos){if(!e||typeof e!=`object`)continue;let t=e;typeof t.full_name!=`string`||typeof t.clone_url!=`string`||S.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private===!0})}return{ok:!0,host:typeof g.host==`string`?g.host:t,repos:S}}return{ok:!1,error:`auth repos returned no data`}}const GENERIC_TITLE=`Clone subprocess reported an error.`,MAX_DETAIL_LEN=500;function classifyCloneError(e){let t=redactShareSubprocessStderr(e).trim().slice(0,MAX_DETAIL_LEN);return t.length===0?{title:GENERIC_TITLE,detail:``}:/repository not found|returned error:\s*404/i.test(t)?{title:`Can't access this repository. It may be private, or you may not have access.`,detail:t}:/permission denied|access denied|returned error:\s*403/i.test(t)?{title:`You don't have access to this repository.`,detail:t}:/authentication failed/i.test(t)?{title:`GitHub authentication failed. Try signing in again.`,detail:t}:{title:GENERIC_TITLE,detail:t}}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const log$8=getLogger(`clone-flow`),DEFAULT_TIMEOUT_MS$1=600*1e3;function validateCloneInputs(e,t){return isAllowedGitUrl(e)?isSafeLocalPath(t)?{ok:!0}:{ok:!1,reason:`invalid-dir`}:{ok:!1,reason:`invalid-url`}}function asRawCloneEvent(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`branch-fallback`?typeof e.branch==`string`&&e.branch.length>0?{type:`branch-fallback`,branch:e.branch}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runCloneSubprocess(e){let t=expandTilde(e.dir),s=e.timeoutMs??DEFAULT_TIMEOUT_MS$1,g;try{g=assertGitAvailable()}catch(t){t instanceof GitNotAvailableError||t instanceof GitTooOldError?(emitPreflightFailureSpan(t),log$8.warn({event:`git_preflight_fail`,platform:t.platform,reason:t instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:t instanceof GitTooOldError?t.detected:``},t instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log$8.error({event:`clone_preflight_unexpected_error`,err:t},`unexpected error during clone preflight`);let s=t instanceof Error?t.message:String(t);return{done:Promise.resolve().then(()=>{e.onEvent({type:`error`,message:s})}),cancel:()=>{}}}let S=isAbsolute(g.resolvedPath)?[dirname(g.resolvedPath)]:[],w=!1,E=typeof e.branch==`string`&&e.branch.length>0?[`-b`,e.branch]:[],D=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,...E,e.url,t],extraPathDirs:S,timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asRawCloneEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(w=!0),e.onEvent(s))}});return{done:D.done.then(s=>{if(!w){if(s.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(s.code!==0){let t=s.stderr?` — ${s.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${s.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:D.cancel}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let s=e.slice(1,t),g=e.slice(t+1);return g!==``&&!/^:\d+$/.test(g)?!1:s===`::1`}let t=e.lastIndexOf(`:`),s=t>=0?e.slice(0,t):e,g=t>=0?e.slice(t+1):null;return g!==null&&!/^\d+$/.test(g)?!1:!!(s===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return getLocalDir(e)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenamePathSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function isManagedRenameCleanupPath(e){return typeof e==`string`&&e.length>0}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,s=e.pathSnapshots,g=e.cleanupPaths,S=Array.isArray(s)&&s.length>0,w=Array.isArray(g)&&g.length>0;if(!Array.isArray(t)||!t.every(isManagedRenameAffectedDoc)||t.length===0&&!S&&!w)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);if(s!==void 0&&(!Array.isArray(s)||!s.every(isManagedRenamePathSnapshot)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(g!==void 0&&(!Array.isArray(g)||!g.every(isManagedRenameCleanupPath)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let s of t)if(!e.snapshots.some(e=>e.docName===s.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${s.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...S?{pathSnapshots:s}:{},...w?{cleanupPaths:g}:{}}}function parseV1(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let s=managedRenameJournalPath(e);tracedMkdirSync(dirname(s),{recursive:!0});let g=`${s}.tmp`;tracedWriteFileSync(g,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(g,s)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,s){writeManagedRenameJournal(e,t);let g=await s();return clearManagedRenameJournal(e),g}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function resolveRecoveryPath(e,t){let s=resolve(e),g=resolve(s,t);if(t.includes(`\0`)||g===s||!g.startsWith(`${s}${sep}`))throw Error(`Invalid recovery path: ${t}`);return g}function pruneEmptyAncestors(e,t){let s=resolve(t),g=`${s}${sep}`,S=dirname(e);for(;S.startsWith(g)&&S!==s;){let e;try{e=readdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${S}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${S}:`,e);return}S=dirname(S)}}function recoverPendingManagedRename(e,t=e){let s=readManagedRenameJournal(t);if(!s)return{recovered:!1,journal:null,restoredDocNames:[]};let g=new Set,S=new Set,w=[];for(let t of s.snapshots)try{let s=safeContentPath(t.docName,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t.content,`utf-8`),g.add(t.docName)}catch(e){w.push({docName:t.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${t.docName}:`,e)}if(w.length>0){let e=w.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=w.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(s.version===2){let t=[];for(let g of s.pathSnapshots??[])try{let t=resolveRecoveryPath(e,g.path);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,g.content,`utf-8`),S.add(g.path)}catch(e){t.push({path:g.path,cause:e}),console.warn(`[managed-rename] Failed to restore path ${g.path}:`,e)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let s=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(s,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let E=s.version===2?destinationsToCleanV2(s):destinationsToCleanV1(s),D=[];for(let t of E){if(g.has(t))continue;let s=safeContentPath(t,e);try{tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){existsSync(s)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),D.push({destination:t,cause:e})}}if(s.version===2)for(let t of s.cleanupPaths??[]){if(S.has(t))continue;let s=null;try{s=resolveRecoveryPath(e,t),tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){s&&existsSync(s)&&console.warn(`[managed-rename] Both source and destination paths exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination path ${t}:`,e),D.push({destination:t,cause:e})}}if(D.length>0){let e=D.map(e=>e.destination).join(`, `),t=D.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return clearManagedRenameJournal(t),{recovered:!0,journal:s,restoredDocNames:[...g].sort((e,t)=>e.localeCompare(t))}}const PROJECT_SKILL_EDITOR_LABELS={claude:`Claude Code`,cursor:`Cursor`,codex:`Codex`},PLATFORM_SKILL_NAME=BUNDLE_SKILL_NAME.project;function resolvePackSkillSource(e){let t;try{t=resolveBundledSkillDir(`packs/${e}`,{checkDesktop:!0})}catch{return null}return{name:`open-knowledge-pack-${e}`,sourceDir:t}}async function installPackSkill(e,t){let s=resolvePackSkillSource(t);if(!s)return[];let{name:g,sourceDir:S}=s,w=join(e,`.ok`,`skills`,g);if(!existsSync(join(w,`SKILL.md`)))try{tracedRmSync(w,{recursive:!0,force:!0}),tracedMkdirSync(join(e,`.ok`,`skills`),{recursive:!0}),tracedCpSync(S,w,{recursive:!0})}catch(e){return getLogger(`seed`).warn({err:e,packId:t,okSkillDir:w},`pack skill source authoring failed — skill not installed`),[]}let E=projectSkill(w,g,e,PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_SKILL_ROOT[t];return s===null?!1:existsSync(join(e,s,PLATFORM_SKILL_NAME,`SKILL.md`))})),D=E.map(e=>PROJECT_SKILL_EDITOR_LABELS[e]??e);if(E.length>0)try{await recordSkillInstall(e,g,{hosts:E,scope:`project`,scripts:existsSync(join(w,`scripts`)),installedAt:new Date().toISOString()})}catch{}return D}var SeedPrerequisiteError=class extends Error{constructor(e){super(e),this.name=`SeedPrerequisiteError`}},SeedRootDirError=class extends Error{constructor(e){super(e),this.name=`SeedRootDirError`}};function assertEntryPathInProject(e,t){if(typeof t!=`string`||t===``)throw new SeedRootDirError(`entry path must be a non-empty string, got: ${typeof t}`);if(t.includes(`\0`))throw new SeedRootDirError(`entry path must not contain null bytes`);if(isAbsolute(t))throw new SeedRootDirError(`entry path must be relative, got: ${t}`);if(t.split(/[/\\]/).some(e=>e===`..`))throw new SeedRootDirError(`entry path must not contain '..' segments, got: ${t}`);let s=resolve(e),g=resolve(s,t);if(g!==s&&!g.startsWith(s+sep))throw new SeedRootDirError(`entry path must resolve inside the project directory, got: ${t}`);return assertNoSymlinkEscape$1(g,s),g}function assertNoSymlinkEscape$1(e,t){let s;try{s=realpathSync(t)}catch{return}let g=e;for(;;){if(existsSync(g)){let t;try{t=realpathSync(g)}catch(t){throw t.code===`ELOOP`?new SeedRootDirError(`entry path traverses a symlink cycle: ${e}`):t}if(t!==s&&!t.startsWith(s+sep))throw new SeedRootDirError(`entry path resolves outside the project directory via symlink: ${e}`);return}let t=dirname(g);if(t===g)throw new SeedRootDirError(`entry path has no existing ancestor inside the project directory: ${e}`);g=t}}const DEFAULT_PACK_ID=`knowledge-base`,KNOWLEDGE_BASE_FOLDERS=[{path:`external-sources`,title:`External Sources`,uiSummary:`The original sources, saved word-for-word.`,description:"Raw sources saved verbatim — the fetched text of URLs, extracted PDFs, and copied files, each with the original URL and access date in frontmatter. Produced by `ingest`. Immutable after capture; no analysis here (that goes in `research/`).",tags:[`source`,`immutable`,`layer-ingest`],starterTemplate:`clip`},{path:`research`,title:`Research`,uiSummary:`Your work-in-progress take on what the sources mean.`,description:"Provisional analysis that synthesizes the external sources. Every claim cites a doc in `external-sources/`; `status: provisional`. Promoted to `articles/` via `consolidate` once the findings are stable.",tags:[`research`,`provisional`,`layer-research`],starterTemplate:`research-log`},{path:`articles`,title:`Articles`,uiSummary:`The finished, trusted version you can rely on.`,description:"Canonical knowledge, committed after a team decision. The source of truth for the domain; carries a `supersedes:` chain back to the `research/` docs it replaces.",tags:[`article`,`canonical`,`layer-consolidate`],starterTemplate:`article`}],KNOWLEDGE_BASE_TEMPLATES={clip:`---
|
|
958
957
|
template:
|
|
959
958
|
title: External Source
|
|
960
959
|
description: Capture a URL or article text verbatim as raw reference material. For binary files (PDFs, images, audio), use the \`ingest\` tool instead — this \`clip\` template is for text sources only.
|
|
@@ -1017,7 +1016,7 @@ description: Append-only audit trail of changes to this knowledge base.
|
|
|
1017
1016
|
# Work Log
|
|
1018
1017
|
|
|
1019
1018
|
Append-only audit trail. Add one dated entry per turn that creates, edits, or restructures content. The knowledge-base skill describes what to log and the entry shape.
|
|
1020
|
-
`,SOFTWARE_LIFECYCLE_FOLDERS=[{path:`proposals`,title:`Proposals`,description:"In-flight design proposals (RFC-shape), one file per proposal (`0001-feature-name.md`). Status flows `draft → fcp → accepted/rejected`; accepted proposals graduate to a record in `decisions/`.",tags:[`proposal`,`design`,`in-flight`],starterTemplate:`proposal`},{path:`decisions`,title:`Decisions`,description:"Architecture Decision Records (MADR / Nygard shape), frozen once accepted. One file per decision (`NNNN-title.md`); a new decision links back via `Supersedes:` to the one it replaces.",tags:[`decision`,`adr`,`frozen`],starterTemplate:`decision`},{path:`specs`,title:`Specs`,description:"Implementation specs derived from accepted proposals. Prefer the `github/spec-kit` triple — one folder per spec with `spec.md` + `plan.md` + `tasks.md` (the folder ships all three templates). References the parent proposal.",tags:[`spec`,`implementation`],starterTemplate:`spec`,extraTemplates:[`spec-plan`,`spec-tasks`]},{path:`postmortems`,title:`Postmortems`,description:"Blameless incident write-ups, one file per incident (`YYYY-MM-DD-name.md`): Summary / Timeline / Root cause / What went well / Action items (Google SRE shape).",tags:[`postmortem`,`incident`,`blameless`],starterTemplate:`postmortem`},{path:`guides`,title:`Guides`,description:'How-to guides, onboarding docs, and service runbooks (Diátaxis "how-to"). Ships `guide`, `onboarding-guide`, and `runbook` templates; carries `last_verified`.',tags:[`guide`,`how-to`,`onboarding`],starterTemplate:`guide`,extraTemplates:[`onboarding-guide`,`runbook`]}],SOFTWARE_LIFECYCLE_TEMPLATES={proposal:`---
|
|
1019
|
+
`,SOFTWARE_LIFECYCLE_FOLDERS=[{path:`proposals`,title:`Proposals`,uiSummary:`Ideas you're putting forward for discussion.`,description:"In-flight design proposals (RFC-shape), one file per proposal (`0001-feature-name.md`). Status flows `draft → fcp → accepted/rejected`; accepted proposals graduate to a record in `decisions/`.",tags:[`proposal`,`design`,`in-flight`],starterTemplate:`proposal`},{path:`decisions`,title:`Decisions`,uiSummary:`Decisions you've made, and why.`,description:"Architecture Decision Records (MADR / Nygard shape), frozen once accepted. One file per decision (`NNNN-title.md`); a new decision links back via `Supersedes:` to the one it replaces.",tags:[`decision`,`adr`,`frozen`],starterTemplate:`decision`},{path:`specs`,title:`Specs`,uiSummary:`Detailed plans for what you're building.`,description:"Implementation specs derived from accepted proposals. Prefer the `github/spec-kit` triple — one folder per spec with `spec.md` + `plan.md` + `tasks.md` (the folder ships all three templates). References the parent proposal.",tags:[`spec`,`implementation`],starterTemplate:`spec`,extraTemplates:[`spec-plan`,`spec-tasks`]},{path:`postmortems`,title:`Postmortems`,uiSummary:`Write-ups of what broke and what you learned.`,description:"Blameless incident write-ups, one file per incident (`YYYY-MM-DD-name.md`): Summary / Timeline / Root cause / What went well / Action items (Google SRE shape).",tags:[`postmortem`,`incident`,`blameless`],starterTemplate:`postmortem`},{path:`guides`,title:`Guides`,uiSummary:`How-to guides, onboarding, and runbooks.`,description:'How-to guides, onboarding docs, and service runbooks (Diátaxis "how-to"). Ships `guide`, `onboarding-guide`, and `runbook` templates; carries `last_verified`.',tags:[`guide`,`how-to`,`onboarding`],starterTemplate:`guide`,extraTemplates:[`onboarding-guide`,`runbook`]}],SOFTWARE_LIFECYCLE_TEMPLATES={proposal:`---
|
|
1021
1020
|
template:
|
|
1022
1021
|
title: Proposal Title
|
|
1023
1022
|
description: One-line summary of the proposal.
|
|
@@ -1208,7 +1207,7 @@ tags: [postmortem]
|
|
|
1208
1207
|
## What went well
|
|
1209
1208
|
|
|
1210
1209
|
## Action items
|
|
1211
|
-
`},CODEBASE_WIKI_FOLDERS=[{path:`wiki/architecture`,title:`Architecture`,description:"System boundaries, layers, subsystems, and cross-cutting concerns — the big-picture structure. One page per architectural area, each with a `mermaid` system-context or component diagram, the key components, and the design decisions behind them. Uses the `architecture-page` template. Cross-link the modules and flows each area touches. Reference source files per the wiki source-reference convention (relative links + symbol code-spans for `internal`; GitHub blob URLs for `public`).",tags:[`wiki`,`architecture`],starterTemplate:`architecture-page`},{path:`wiki/modules`,title:`Modules`,description:"One page per package or module: purpose, responsibilities, public API / entry points, key files (linked per the source-reference convention), dependencies, and the flows it participates in. Uses the `module-page` template. At `depth: tour` these fold into the architecture pages; at `standard`+ each package gets its own page. Cross-link concepts and flows.",tags:[`wiki`,`module`],starterTemplate:`module-page`},{path:`wiki/flows`,title:`Flows`,description:"Key end-to-end flows as `mermaid` sequence or flow diagrams plus narrative — how a request, job, or interaction moves through the system. Uses the `flow-page` template; record failure modes at `depth: exhaustive`. Link every module and concept the flow crosses.",tags:[`wiki`,`flow`],starterTemplate:`flow-page`},{path:`wiki/concepts`,title:`Concepts`,description:"Glossary of atomic pages for domain terms and core abstractions — the vocabulary a newcomer needs. Uses the `concept-page` template: definition, why it matters, where it lives in the code. Keep pages small and densely cross-linked so concepts become hubs for everywhere they appear.",tags:[`wiki`,`concept`],starterTemplate:`concept-page`},{path:`wiki/guides`,title:`Guides`,description:'Task-oriented "how / where do I change X" walkthroughs. Uses the `guide-page` template: goal, steps, relevant code, gotchas. Populated at `depth: standard` and rich at `exhaustive`; thin or empty at `tour`. Link the modules and flows each guide touches.',tags:[`wiki`,`guide`,`how-to`],starterTemplate:`guide-page`}],CODEBASE_WIKI_TEMPLATES={"architecture-page":`---
|
|
1210
|
+
`},CODEBASE_WIKI_FOLDERS=[{path:`wiki/architecture`,title:`Architecture`,uiSummary:`The big-picture structure of your codebase.`,description:"System boundaries, layers, subsystems, and cross-cutting concerns — the big-picture structure. One page per architectural area, each with a `mermaid` system-context or component diagram, the key components, and the design decisions behind them. Uses the `architecture-page` template. Cross-link the modules and flows each area touches. Reference source files per the wiki source-reference convention (relative links + symbol code-spans for `internal`; GitHub blob URLs for `public`).",tags:[`wiki`,`architecture`],starterTemplate:`architecture-page`},{path:`wiki/modules`,title:`Modules`,uiSummary:`What each package or module does.`,description:"One page per package or module: purpose, responsibilities, public API / entry points, key files (linked per the source-reference convention), dependencies, and the flows it participates in. Uses the `module-page` template. At `depth: tour` these fold into the architecture pages; at `standard`+ each package gets its own page. Cross-link concepts and flows.",tags:[`wiki`,`module`],starterTemplate:`module-page`},{path:`wiki/flows`,title:`Flows`,uiSummary:`How key actions move through the system.`,description:"Key end-to-end flows as `mermaid` sequence or flow diagrams plus narrative — how a request, job, or interaction moves through the system. Uses the `flow-page` template; record failure modes at `depth: exhaustive`. Link every module and concept the flow crosses.",tags:[`wiki`,`flow`],starterTemplate:`flow-page`},{path:`wiki/concepts`,title:`Concepts`,uiSummary:`Plain definitions of the terms and ideas in your code.`,description:"Glossary of atomic pages for domain terms and core abstractions — the vocabulary a newcomer needs. Uses the `concept-page` template: definition, why it matters, where it lives in the code. Keep pages small and densely cross-linked so concepts become hubs for everywhere they appear.",tags:[`wiki`,`concept`],starterTemplate:`concept-page`},{path:`wiki/guides`,title:`Guides`,uiSummary:`How and where to make common changes.`,description:'Task-oriented "how / where do I change X" walkthroughs. Uses the `guide-page` template: goal, steps, relevant code, gotchas. Populated at `depth: standard` and rich at `exhaustive`; thin or empty at `tour`. Link the modules and flows each guide touches.',tags:[`wiki`,`guide`,`how-to`],starterTemplate:`guide-page`}],CODEBASE_WIKI_TEMPLATES={"architecture-page":`---
|
|
1212
1211
|
template:
|
|
1213
1212
|
title: Architecture Page
|
|
1214
1213
|
description: One subsystem, layer, or cross-cutting concern — boundaries, a diagram, and the key components.
|
|
@@ -1330,7 +1329,7 @@ description: Append-only audit trail of wiki generation and refresh runs.
|
|
|
1330
1329
|
# Wiki Log
|
|
1331
1330
|
|
|
1332
1331
|
Append-only audit trail. Add one dated entry per generation or refresh run, recording the profile, the \`source_commit\` it was anchored to, and the coverage. The codebase-wiki skill describes the entry shape.
|
|
1333
|
-
`,PLAIN_NOTES_FOLDERS=[{path:`notes`,title:`Notes`,description:`Flat notes, one file per topic. The "I just want to write" home base — link freely and the graph builds itself.`,tags:[`notes`,`flat`],starterTemplate:`note`},{path:`daily`,title:`Daily`,description:"Daily journal entries, one file per day (`YYYY-MM-DD.md`): morning intentions, evening reflection.",tags:[`daily`,`journal`],starterTemplate:`daily`}],PLAIN_NOTES_TEMPLATES={note:`---
|
|
1332
|
+
`,PLAIN_NOTES_FOLDERS=[{path:`notes`,title:`Notes`,uiSummary:`One file per topic. Just write.`,description:`Flat notes, one file per topic. The "I just want to write" home base — link freely and the graph builds itself.`,tags:[`notes`,`flat`],starterTemplate:`note`},{path:`daily`,title:`Daily`,uiSummary:`One journal entry per day.`,description:"Daily journal entries, one file per day (`YYYY-MM-DD.md`): morning intentions, evening reflection.",tags:[`daily`,`journal`],starterTemplate:`daily`}],PLAIN_NOTES_TEMPLATES={note:`---
|
|
1334
1333
|
template:
|
|
1335
1334
|
title: Note title
|
|
1336
1335
|
description: One-line summary.
|
|
@@ -1364,7 +1363,7 @@ tags: [daily]
|
|
|
1364
1363
|
- What shipped:
|
|
1365
1364
|
- What stalled:
|
|
1366
1365
|
- Gratitude:
|
|
1367
|
-
`},WORLDBUILDING_FOLDERS=[{path:`characters`,title:`Characters`,description:"One file per character (PC + NPC); frontmatter carries `type`, status, faction, first appearance.",tags:[`character`,`fiction`,`entity`],starterTemplate:`character`},{path:`settings`,title:`Settings`,description:`Locations, regions, and world-rules — the "where" of the story. Frontmatter carries region, controlling faction, danger level.`,tags:[`setting`,`location`,`world`],starterTemplate:`setting`},{path:`themes`,title:`Themes`,description:`Recurring narrative concerns (love, betrayal, identity) — the "why" of the story. Each entry captures the theme and its tension.`,tags:[`theme`,`narrative`,`meaning`],starterTemplate:`theme`},{path:`factions`,title:`Factions`,description:'Political, social, criminal, magical, or religious groups — the "who-vs-who" of the story. Ships `faction`, `political-faction`, and `religion` templates.',tags:[`faction`,`group`,`politics`],starterTemplate:`faction`,extraTemplates:[`political-faction`,`religion`]},{path:`lore`,title:`Lore`,description:"History, mythology, cosmology, and magic systems — the foundational fabric the story stands on. Ships `lore`, `magic-system`, and `historical-event` templates.",tags:[`lore`,`history`,`world`],starterTemplate:`lore`,extraTemplates:[`magic-system`,`historical-event`]}],WORLDBUILDING_TEMPLATES={character:`---
|
|
1366
|
+
`},WORLDBUILDING_FOLDERS=[{path:`characters`,title:`Characters`,uiSummary:`The people in your story.`,description:"One file per character (PC + NPC); frontmatter carries `type`, status, faction, first appearance.",tags:[`character`,`fiction`,`entity`],starterTemplate:`character`},{path:`settings`,title:`Settings`,uiSummary:`The places and regions of your world.`,description:`Locations, regions, and world-rules — the "where" of the story. Frontmatter carries region, controlling faction, danger level.`,tags:[`setting`,`location`,`world`],starterTemplate:`setting`},{path:`themes`,title:`Themes`,uiSummary:`The big ideas your story keeps returning to.`,description:`Recurring narrative concerns (love, betrayal, identity) — the "why" of the story. Each entry captures the theme and its tension.`,tags:[`theme`,`narrative`,`meaning`],starterTemplate:`theme`},{path:`factions`,title:`Factions`,uiSummary:`The groups and their rivalries.`,description:'Political, social, criminal, magical, or religious groups — the "who-vs-who" of the story. Ships `faction`, `political-faction`, and `religion` templates.',tags:[`faction`,`group`,`politics`],starterTemplate:`faction`,extraTemplates:[`political-faction`,`religion`]},{path:`lore`,title:`Lore`,uiSummary:`History, myth, and how the world works.`,description:"History, mythology, cosmology, and magic systems — the foundational fabric the story stands on. Ships `lore`, `magic-system`, and `historical-event` templates.",tags:[`lore`,`history`,`world`],starterTemplate:`lore`,extraTemplates:[`magic-system`,`historical-event`]}],WORLDBUILDING_TEMPLATES={character:`---
|
|
1368
1367
|
template:
|
|
1369
1368
|
title: Character Name
|
|
1370
1369
|
description: One-line characterization.
|
|
@@ -1563,7 +1562,7 @@ tags: [lore, history]
|
|
|
1563
1562
|
## In-world tellings
|
|
1564
1563
|
|
|
1565
1564
|
## Source
|
|
1566
|
-
`},WRITING_PIPELINE_FOLDERS=[{path:`ideas`,title:`Ideas`,description:"One-line ideas captured before they fade — premises, headlines, fragments. Not a draft folder; promote an idea into `drafts/` when you commit to writing it.",tags:[`idea`,`inbox`,`pre-draft`],starterTemplate:`idea`},{path:`drafts`,title:`Drafts`,description:"Active prose. Frontmatter tracks `status`, word count, and parent idea. CRDT history covers every revision, so no named-revision folders.",tags:[`draft`,`prose`],starterTemplate:`draft`},{path:`published`,title:`Published`,description:"Shipped work; carries `published_at`, `canonical_url`, `channel`. Treat as immutable — to revise, copy to a new draft.",tags:[`published`,`live`],starterTemplate:`published`}],WRITING_PIPELINE_TEMPLATES={idea:`---
|
|
1565
|
+
`},WRITING_PIPELINE_FOLDERS=[{path:`ideas`,title:`Ideas`,uiSummary:`Quick sparks to write about later.`,description:"One-line ideas captured before they fade — premises, headlines, fragments. Not a draft folder; promote an idea into `drafts/` when you commit to writing it.",tags:[`idea`,`inbox`,`pre-draft`],starterTemplate:`idea`},{path:`drafts`,title:`Drafts`,uiSummary:`Pieces you're actively writing.`,description:"Active prose. Frontmatter tracks `status`, word count, and parent idea. CRDT history covers every revision, so no named-revision folders.",tags:[`draft`,`prose`],starterTemplate:`draft`},{path:`published`,title:`Published`,uiSummary:`Finished work you've shared.`,description:"Shipped work; carries `published_at`, `canonical_url`, `channel`. Treat as immutable — to revise, copy to a new draft.",tags:[`published`,`live`],starterTemplate:`published`}],WRITING_PIPELINE_TEMPLATES={idea:`---
|
|
1567
1566
|
template:
|
|
1568
1567
|
title: Idea title
|
|
1569
1568
|
description: One-line hook.
|
|
@@ -1605,7 +1604,7 @@ author: {{user}}
|
|
|
1605
1604
|
tags: [published]
|
|
1606
1605
|
---
|
|
1607
1606
|
|
|
1608
|
-
`},ENTITY_VAULT_FOLDERS=[{path:`people`,title:`People`,description:"Person dossiers. Compiled-truth section above `--- timeline ---` (rewritten as understanding changes); append-only timeline below using `- **YYYY-MM-DD** | source | @author — evidence` bullets. Frontmatter `type: person`. Prefer path-qualified links such as `[[companies/acme|Acme]]` and `[[meetings/2026-05-12-acme|meeting]]` when identity matters. Agent: when a meeting note mentions a person not yet captured, stub a file here; route new facts into either compiled-truth (current synthesis) or timeline (raw evidence). Never rewrite the timeline.",tags:[`person`,`entity`,`dossier`],starterTemplate:`person`},{path:`companies`,title:`Companies`,description:"Company dossiers. Same body convention as `people/`: compiled-truth above `--- timeline ---`, append-only parseable timeline below. Frontmatter `type: company`. Prefer path-qualified links to `people/`, `meetings/`, and `concepts/`. Agent: when a person dossier references a company not yet captured, stub a file here; surface company-to-person edges when both exist.",tags:[`company`,`entity`,`dossier`],starterTemplate:`company`},{path:`meetings`,title:`Meetings`,description:"Meeting notes. Filename `YYYY-MM-DD-<slug>.md`. Frontmatter carries `title`, `date`, `attendees:` (prefer person slugs/names that resolve to `people/` dossiers), and `type: meeting`. Body is raw notes with path-qualified links to the people, companies, and concepts mentioned. Agent: after a meeting note lands, extract entity mentions and append dated timeline bullets to each referenced dossier. Do NOT rewrite the meeting note; it is the verbatim record.",tags:[`meeting`,`note`],starterTemplate:`meeting`},{path:`concepts`,title:`Concepts`,description:'Evergreen idea pages: abstract patterns, frameworks, recurring concepts that surface across people / companies / meetings. Compiled-truth above `--- timeline ---`, append-only parseable timeline below. Frontmatter `type: concept`. Agent: when a meeting note or person dossier references a concept (e.g. "agent-runtime observability") not yet captured, stub a file here; thread path-qualified links so the concept becomes a hub for everywhere it appears.',tags:[`concept`,`idea`,`evergreen`],starterTemplate:`concept`},{path:`originals`,title:`Originals`,description:"Your own thinking, untransformed. Frontmatter `type: original`. Use freely; link to anything that should become its own entity. Agent: treat originals as authoritative source material when extracting facts; these are the user's words, not inferences. Append timeline entries to referenced dossiers when a clear new claim appears, citing the original by markdown link.",tags:[`original`,`thinking`,`user`],starterTemplate:`original`},{path:`media`,title:`Media`,description:"Bulk transcripts, voice notes, articles, large attachments. Frontmatter `type: transcript` (template provided). Often `.okignore`-d so the OK index stays light. Keep raw media/source material here; analysis belongs in dossiers, not here. If you also run Garry Tan's `gbrain`, import/sync can index these Markdown transcripts alongside the entity dossiers.",tags:[`media`,`transcript`,`bulk`],starterTemplate:`transcript`}],ENTITY_VAULT_TEMPLATES={person:`---
|
|
1607
|
+
`},ENTITY_VAULT_FOLDERS=[{path:`people`,title:`People`,uiSummary:`The people you know and work with.`,description:"Person dossiers. Compiled-truth section above `--- timeline ---` (rewritten as understanding changes); append-only timeline below using `- **YYYY-MM-DD** | source | @author — evidence` bullets. Frontmatter `type: person`. Prefer path-qualified links such as `[[companies/acme|Acme]]` and `[[meetings/2026-05-12-acme|meeting]]` when identity matters. Agent: when a meeting note mentions a person not yet captured, stub a file here; route new facts into either compiled-truth (current synthesis) or timeline (raw evidence). Never rewrite the timeline.",tags:[`person`,`entity`,`dossier`],starterTemplate:`person`},{path:`companies`,title:`Companies`,uiSummary:`The companies on your radar.`,description:"Company dossiers. Same body convention as `people/`: compiled-truth above `--- timeline ---`, append-only parseable timeline below. Frontmatter `type: company`. Prefer path-qualified links to `people/`, `meetings/`, and `concepts/`. Agent: when a person dossier references a company not yet captured, stub a file here; surface company-to-person edges when both exist.",tags:[`company`,`entity`,`dossier`],starterTemplate:`company`},{path:`meetings`,title:`Meetings`,uiSummary:`Notes from your meetings.`,description:"Meeting notes. Filename `YYYY-MM-DD-<slug>.md`. Frontmatter carries `title`, `date`, `attendees:` (prefer person slugs/names that resolve to `people/` dossiers), and `type: meeting`. Body is raw notes with path-qualified links to the people, companies, and concepts mentioned. Agent: after a meeting note lands, extract entity mentions and append dated timeline bullets to each referenced dossier. Do NOT rewrite the meeting note; it is the verbatim record.",tags:[`meeting`,`note`],starterTemplate:`meeting`},{path:`concepts`,title:`Concepts`,uiSummary:`Recurring ideas that connect people and companies.`,description:'Evergreen idea pages: abstract patterns, frameworks, recurring concepts that surface across people / companies / meetings. Compiled-truth above `--- timeline ---`, append-only parseable timeline below. Frontmatter `type: concept`. Agent: when a meeting note or person dossier references a concept (e.g. "agent-runtime observability") not yet captured, stub a file here; thread path-qualified links so the concept becomes a hub for everywhere it appears.',tags:[`concept`,`idea`,`evergreen`],starterTemplate:`concept`},{path:`originals`,title:`Originals`,uiSummary:`Your own raw thinking.`,description:"Your own thinking, untransformed. Frontmatter `type: original`. Use freely; link to anything that should become its own entity. Agent: treat originals as authoritative source material when extracting facts; these are the user's words, not inferences. Append timeline entries to referenced dossiers when a clear new claim appears, citing the original by markdown link.",tags:[`original`,`thinking`,`user`],starterTemplate:`original`},{path:`media`,title:`Media`,uiSummary:`Transcripts, voice notes, and long attachments.`,description:"Bulk transcripts, voice notes, articles, large attachments. Frontmatter `type: transcript` (template provided). Often `.okignore`-d so the OK index stays light. Keep raw media/source material here; analysis belongs in dossiers, not here. If you also run Garry Tan's `gbrain`, import/sync can index these Markdown transcripts alongside the entity dossiers.",tags:[`media`,`transcript`,`bulk`],starterTemplate:`transcript`}],ENTITY_VAULT_TEMPLATES={person:`---
|
|
1609
1608
|
template:
|
|
1610
1609
|
title: Person Name
|
|
1611
1610
|
description: One-line characterization. Who they are, why they matter to you.
|
|
@@ -1837,7 +1836,7 @@ description: "When the agent does scheduled work: daily briefings, end-of-day do
|
|
|
1837
1836
|
|
|
1838
1837
|
- Run OK's \`links({ kind: "dead" })\` across the vault. Triage redlinks into new entities (agents create dossiers through OK), typo fixes (OK edits in place), or removal (drop the link; a tracked task captures any future-doc intent).
|
|
1839
1838
|
|
|
1840
|
-
`,OKF_FOLDERS=[{path:`concepts`,title:`Concepts`,description:"Durable ideas and definitions, one file per concept. Each doc carries `type: concept` in its frontmatter. Link related concepts so the graph builds itself.",tags:[`concept`,`okf`],starterTemplate:`concept`},{path:`references`,title:`References`,description:"External sources and citations you rely on, one file per source. Each doc carries `type: reference`. Link the docs that cite a reference so the evidence trail stays navigable.",tags:[`reference`,`okf`],starterTemplate:`reference`},{path:`notes`,title:`Notes`,description:"Working notes and observations, one file per note. Each doc carries `type: note`. The lightest section — capture first, link as ideas connect.",tags:[`note`,`okf`],starterTemplate:`note`}],OKF_TEMPLATES={concept:`---
|
|
1839
|
+
`,OKF_FOLDERS=[{path:`concepts`,title:`Concepts`,uiSummary:`Ideas and definitions worth keeping.`,description:"Durable ideas and definitions, one file per concept. Each doc carries `type: concept` in its frontmatter. Link related concepts so the graph builds itself.",tags:[`concept`,`okf`],starterTemplate:`concept`},{path:`references`,title:`References`,uiSummary:`Sources and citations you rely on.`,description:"External sources and citations you rely on, one file per source. Each doc carries `type: reference`. Link the docs that cite a reference so the evidence trail stays navigable.",tags:[`reference`,`okf`],starterTemplate:`reference`},{path:`notes`,title:`Notes`,uiSummary:`Working notes and observations.`,description:"Working notes and observations, one file per note. Each doc carries `type: note`. The lightest section — capture first, link as ideas connect.",tags:[`note`,`okf`],starterTemplate:`note`}],OKF_TEMPLATES={concept:`---
|
|
1841
1840
|
template:
|
|
1842
1841
|
title: Concept Name
|
|
1843
1842
|
description: One-line definition of the concept.
|
|
@@ -1924,11 +1923,10 @@ Every document outside this file and \`log.md\` carries a non-empty \`type\` in
|
|
|
1924
1923
|
`,OKF_LOG_MD=`# Log
|
|
1925
1924
|
|
|
1926
1925
|
Change history for this knowledge base, newest entry first. Add a dated entry (\`## YYYY-MM-DD: <summary>\`) whenever you create, edit, or restructure content — one entry per working session, not per file.
|
|
1927
|
-
`,STARTER_PACKS={"knowledge-base":{id:`knowledge-base`,name:`Knowledge base`,description:`Trusted articles from your sources.`,defaultSubfolder:`brain`,folders:KNOWLEDGE_BASE_FOLDERS,templates:KNOWLEDGE_BASE_TEMPLATES,rootFiles:{"log.md":KNOWLEDGE_BASE_LOG_MD}},"software-lifecycle":{id:`software-lifecycle`,name:`Software lifecycle`,description:`Proposals, decisions, and specs.`,defaultSubfolder:`project-docs`,folders:SOFTWARE_LIFECYCLE_FOLDERS,templates:SOFTWARE_LIFECYCLE_TEMPLATES},"codebase-wiki":{id:`codebase-wiki`,name:`Codebase wiki`,description:`A wiki to help navigate your codebase.`,defaultSubfolder:void 0,folders:CODEBASE_WIKI_FOLDERS,templates:CODEBASE_WIKI_TEMPLATES,rootFiles:{"wiki/OVERVIEW.md":CODEBASE_WIKI_OVERVIEW_MD,"wiki/log.md":CODEBASE_WIKI_LOG_MD}},"plain-notes":{id:`plain-notes`,name:`Plain notes`,description:`Notes and daily entries.`,defaultSubfolder:void 0,folders:PLAIN_NOTES_FOLDERS,templates:PLAIN_NOTES_TEMPLATES},okf:{id:`okf`,name:`Open Knowledge Format`,description:`Wiki using Google's Open Knowledge Format.`,defaultSubfolder:void 0,folders:OKF_FOLDERS,templates:OKF_TEMPLATES,rootFiles:{"welcome.md":OKF_WELCOME_MD,"index.md":OKF_INDEX_MD,"log.md":OKF_LOG_MD}},"writing-pipeline":{id:`writing-pipeline`,name:`Writing pipeline`,description:`From first draft to finished piece.`,defaultSubfolder:`writing`,folders:WRITING_PIPELINE_FOLDERS,templates:WRITING_PIPELINE_TEMPLATES},"entity-vault":{id:`entity-vault`,name:`Personal CRM`,description:`Track the people, companies, and meetings.`,defaultSubfolder:`vault`,folders:ENTITY_VAULT_FOLDERS,templates:ENTITY_VAULT_TEMPLATES,rootFiles:{"log.md":ENTITY_VAULT_LOG_MD,"USER.md":ENTITY_VAULT_USER_MD,"SOUL.md":ENTITY_VAULT_SOUL_MD,"ACCESS_POLICY.md":ENTITY_VAULT_ACCESS_POLICY_MD,"HEARTBEAT.md":ENTITY_VAULT_HEARTBEAT_MD}},worldbuilding:{id:`worldbuilding`,name:`Worldbuilding`,description:`A wiki for your story world.`,defaultSubfolder:`world`,folders:WORLDBUILDING_FOLDERS,templates:WORLDBUILDING_TEMPLATES}},STARTER_PACK_IDS=Object.keys(STARTER_PACKS);function resolvePack(e){return e&&STARTER_PACKS[e]||STARTER_PACKS[DEFAULT_PACK_ID]}function isKnownPackId(e){return typeof e==`string`&&STARTER_PACK_IDS.includes(e)}function coercePackId(e){return isKnownPackId(e)?e:void 0}function deriveFolderSummary(e){let t=e.trim(),s=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return s.length<=140?s:`${s.slice(0,137)}…`}function listStarterPacks(){return STARTER_PACK_IDS.map(e=>{let t=STARTER_PACKS[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:deriveFolderSummary(e.description)})),entryCounts:computePackEntryCounts(t)}})}function computePackEntryCounts(e){let t=e.folders.length,s=0;for(let t of e.folders)s+=1+(t.extraTemplates?.length??0);return s+=e.rootFiles?Object.keys(e.rootFiles).length:0,{files:s,folders:t}}const STARTER_FOLDERS=KNOWLEDGE_BASE_FOLDERS,STARTER_TEMPLATES=KNOWLEDGE_BASE_TEMPLATES,LOG_MD_TEMPLATE=KNOWLEDGE_BASE_LOG_MD,STARTER_FOLDER_FRONTMATTER_FILENAME=`frontmatter.yml`;function buildStarterFolderFrontmatterYaml(e){let t=[];t.push(`title: ${yamlScalar(e.title)}`),t.push(`description: ${yamlScalar(e.description)}`),t.push(`tags:`);for(let s of e.tags)t.push(` - ${yamlScalar(s)}`);return`${t.join(`
|
|
1926
|
+
`,STARTER_PACKS={"knowledge-base":{id:`knowledge-base`,name:`Knowledge base`,description:`Trusted articles from your sources.`,defaultSubfolder:`brain`,folders:KNOWLEDGE_BASE_FOLDERS,templates:KNOWLEDGE_BASE_TEMPLATES,rootFiles:{"log.md":KNOWLEDGE_BASE_LOG_MD}},"software-lifecycle":{id:`software-lifecycle`,name:`Software lifecycle`,description:`Proposals, decisions, and specs.`,defaultSubfolder:`project-docs`,folders:SOFTWARE_LIFECYCLE_FOLDERS,templates:SOFTWARE_LIFECYCLE_TEMPLATES},"codebase-wiki":{id:`codebase-wiki`,name:`Codebase wiki`,description:`A wiki to help navigate your codebase.`,defaultSubfolder:void 0,folders:CODEBASE_WIKI_FOLDERS,templates:CODEBASE_WIKI_TEMPLATES,rootFiles:{"wiki/OVERVIEW.md":CODEBASE_WIKI_OVERVIEW_MD,"wiki/log.md":CODEBASE_WIKI_LOG_MD}},"plain-notes":{id:`plain-notes`,name:`Plain notes`,description:`Notes and daily entries.`,defaultSubfolder:void 0,folders:PLAIN_NOTES_FOLDERS,templates:PLAIN_NOTES_TEMPLATES},okf:{id:`okf`,name:`Open Knowledge Format`,description:`Wiki using Google's Open Knowledge Format.`,defaultSubfolder:void 0,folders:OKF_FOLDERS,templates:OKF_TEMPLATES,rootFiles:{"welcome.md":OKF_WELCOME_MD,"index.md":OKF_INDEX_MD,"log.md":OKF_LOG_MD}},"writing-pipeline":{id:`writing-pipeline`,name:`Writing pipeline`,description:`From first draft to finished piece.`,defaultSubfolder:`writing`,folders:WRITING_PIPELINE_FOLDERS,templates:WRITING_PIPELINE_TEMPLATES},"entity-vault":{id:`entity-vault`,name:`Personal CRM`,description:`Track the people, companies, and meetings.`,defaultSubfolder:`vault`,folders:ENTITY_VAULT_FOLDERS,templates:ENTITY_VAULT_TEMPLATES,rootFiles:{"log.md":ENTITY_VAULT_LOG_MD,"USER.md":ENTITY_VAULT_USER_MD,"SOUL.md":ENTITY_VAULT_SOUL_MD,"ACCESS_POLICY.md":ENTITY_VAULT_ACCESS_POLICY_MD,"HEARTBEAT.md":ENTITY_VAULT_HEARTBEAT_MD}},worldbuilding:{id:`worldbuilding`,name:`Worldbuilding`,description:`A wiki for your story world.`,defaultSubfolder:`world`,folders:WORLDBUILDING_FOLDERS,templates:WORLDBUILDING_TEMPLATES}},STARTER_PACK_IDS=Object.keys(STARTER_PACKS);function resolvePack(e){return e&&STARTER_PACKS[e]||STARTER_PACKS[DEFAULT_PACK_ID]}function isKnownPackId(e){return typeof e==`string`&&STARTER_PACK_IDS.includes(e)}function coercePackId(e){return isKnownPackId(e)?e:void 0}function deriveFolderSummary(e){let t=e.trim(),s=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return s.length<=140?s:`${s.slice(0,137)}…`}function listStarterPacks(){return STARTER_PACK_IDS.map(e=>{let t=STARTER_PACKS[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:e.uiSummary??deriveFolderSummary(e.description)})),entryCounts:computePackEntryCounts(t)}})}function computePackEntryCounts(e){let t=e.folders.length,s=0;for(let t of e.folders)s+=1+(t.extraTemplates?.length??0);return s+=e.rootFiles?Object.keys(e.rootFiles).length:0,{files:s,folders:t}}const STARTER_FOLDERS=KNOWLEDGE_BASE_FOLDERS,STARTER_TEMPLATES=KNOWLEDGE_BASE_TEMPLATES,LOG_MD_TEMPLATE=KNOWLEDGE_BASE_LOG_MD,STARTER_FOLDER_FRONTMATTER_FILENAME=`frontmatter.yml`;function buildStarterFolderFrontmatterYaml(e){let t=[];t.push(`title: ${yamlScalar(e.title)}`),t.push(`description: ${yamlScalar(e.description)}`),t.push(`tags:`);for(let s of e.tags)t.push(` - ${yamlScalar(s)}`);return`${t.join(`
|
|
1928
1927
|
`)}\n`}function yamlScalar(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function resolveFileContent(e,t){if(t.rootFiles?.[e]!==void 0)return t.rootFiles[e];let s=/^(.+)\/\.ok\/frontmatter\.yml$/.exec(e);if(s){let e=t.folders.find(e=>e.path===s[1]);return e?buildStarterFolderFrontmatterYaml(e):void 0}let g=/^(.+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(g){let e=g[2]??``;return t.templates[e]}}async function applySeed(e,t={}){let s=Date.now(),g=resolve(t.projectDir??process.cwd()),S=resolvePack(t.packId??`knowledge-base`),w=0,E=[],D=[];for(let t of e.created)try{let e=assertEntryPathInProject(g,t.path);D.push({entry:t,absPath:e})}catch(e){E.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof SeedRootDirError||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`folder`))try{mkdirSync(t,{recursive:!0}),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`file`)){let s=e.template??e.path,g=resolveFileContent(s,S);if(g===void 0){E.push({path:e.path,error:`No content template registered for template id "${s}" in pack "${S.id}"`});continue}if(!existsSync(t))try{writeFileSync(t,g,`utf-8`),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}let O=await installPackSkill(g,S.id);return{applied:w,errors:E,durationMs:Date.now()-s,packSkillsInstalled:O}}function frontmatterTemplateId(e){return`${e}/.ok/frontmatter.yml`}function templateFileTemplateId(e,t){return`${e}/.ok/templates/${t}.md`}function normalizeRootDir(e,t){if(!e)return``;let s=e.trim();if(s===``||s===`.`||s===`./`)return``;if(s.startsWith(`/`))throw new SeedRootDirError(`rootDir must be relative to the project directory, got: ${e}`);let g=s.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(g.split(`/`).some(e=>e===`..`))throw new SeedRootDirError(`rootDir must not contain '..' segments, got: ${e}`);return assertEntryPathInProject(t,g),g}function joinRelative(e,t){return e===``?t:`${e}/${t}`}async function planSeed(e={}){let t=resolve(e.projectDir??process.cwd());if(!e.skipPrerequisite&&!isProjectRoot(t))throw new SeedPrerequisiteError(`No ${OK_PROJECT_MARKER} found at ${t}. Run \`ok init\` first to scaffold the tool config.`);let s=normalizeRootDir(e.rootDir,t),g=resolvePack(e.packId??`knowledge-base`),S=[],w=[],E=[];s!==``&&(existsSync(join(t,s))?w.push({path:s,reason:`already-exists`}):S.push({path:s,kind:`folder`}));for(let e of g.folders){let D=joinRelative(s,e.path);existsSync(join(t,D))?w.push({path:D,reason:`already-exists`}):S.push({path:D,kind:`folder`});let O=`${D}/.ok`;existsSync(join(t,O))?w.push({path:O,reason:`already-exists`}):S.push({path:O,kind:`folder`});let k=`${O}/${STARTER_FOLDER_FRONTMATTER_FILENAME}`;existsSync(join(t,k))?w.push({path:k,reason:`already-exists`}):S.push({path:k,kind:`file`,template:frontmatterTemplateId(e.path)});let j=`${O}/templates`;existsSync(join(t,j))?w.push({path:j,reason:`already-exists`}):S.push({path:j,kind:`folder`});let F=[e.starterTemplate,...e.extraTemplates??[]];for(let s of F){let D=`${j}/${s}.md`;if(existsSync(join(t,D))){w.push({path:D,reason:`already-exists`});continue}if(g.templates[s]===void 0){let t=s===e.starterTemplate;E.push(t?`No starter template body registered for "${s}" in pack "${g.id}". The folder will land without a pre-selected template.`:`No body registered for extra template "${s}" in pack "${g.id}". The folder will land without that optional variant.`);continue}S.push({path:D,kind:`file`,template:templateFileTemplateId(e.path,s)})}}if(g.rootFiles)for(let e of Object.keys(g.rootFiles)){let g=joinRelative(s,e);existsSync(join(t,g))?w.push({path:g,reason:`already-exists`}):S.push({path:g,kind:`file`,template:e})}let D=resolvePackSkillSource(g.id),O=D?{name:D.name,pending:!existsSync(join(t,`.ok`,`skills`,D.name,`SKILL.md`))}:void 0;return{created:S,skipped:w,warnings:E,...O?{packSkill:O}:{}}}const PACK_INSPIRATION_NOTE=[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
|
|
1929
1928
|
`);function folderTemplateNames(e){return[e.starterTemplate,...e.extraTemplates??[]].join(`, `)}function formatPackRationale(e){let t=[`Pack: ${e.name} — ${e.description}`,``,PACK_INSPIRATION_NOTE,``];t.push(`Layout & rationale:`);for(let s of e.folders)t.push(` ${s.path}/ — ${s.title}`),t.push(` why: ${s.description}`),t.push(` templates: ${folderTemplateNames(s)}`);let s=e.rootFiles?Object.keys(e.rootFiles):[];return s.length>0&&t.push(``,`Root files: ${s.join(`, `)}`),t.join(`
|
|
1930
|
-
`)}function createSingleFlight(){let e=new Map;return{run(t,s){let g=e.get(t);if(g)return{promise:g,coalesced:!0};let S=s();e.set(t,S);let w=()=>{e.get(t)===S&&e.delete(t)};return S.then(w,w),{promise:S,coalesced:!1}},get size(){return e.size}}}function skillShadowPath(e,t){let s=e===`.`?``:e.replace(/^\.\//,``);return s?`${s}/.ok/skills/${t}`:`.ok/skills/${t}`}function isGitObjectNotFound(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function restoreSkillVersion(e){let{shadow:t,contentDir:s,contentRoot:g,name:S,version:w}=e;if(!existsSync(t.workTree)||!existsSync(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let E=skillShadowPath(g,S),D=shadowGit(t),O;try{O=await D.raw(`ls-tree`,`-r`,`--name-only`,w,`--`,E)}catch(e){let t=e instanceof Error?e.message:String(e);return isGitObjectNotFound(t)?{ok:!1,code:`version-not-found`,error:`Version ${w.slice(0,8)} not found.`}:{ok:!1,code:`io-error`,error:`Failed to read version ${w.slice(0,8)}: ${t}`}}let k=O.
|
|
1931
|
-
`).map(e=>e.trim()).filter(Boolean);if(k.length===0)return{ok:!1,code:`skill-absent`,error:`Skill "${S}" did not exist at version ${w.slice(0,8)}.`};let j=resolve(s,`.ok`,`skills`,S),F=j+sep,L=[];for(let e of k){let t=e.slice(E.length).replace(/^\//,``),s=resolve(j,t);if(s!==j&&!s.startsWith(F))return{ok:!1,code:`path-escape`,error:`Refusing to restore path outside skill dir: ${t}`};try{L.push({rel:t,destAbs:s,content:await D.raw(`show`,`${w}:${e}`)})}catch(e){let s=e instanceof Error?e.message:String(e);return{ok:!1,code:`io-error`,error:`Failed reading ${t} at ${w.slice(0,8)}: ${s}`}}}tracedRmSync(j,{recursive:!0,force:!0});let B=[];for(let{rel:e,destAbs:t,content:s}of L)tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,s,`utf-8`),B.push(e);return{ok:!0,restoredFiles:B}}const log$7=getLogger(`suggest-links`),WORD_CHAR_RE=/[\p{L}\p{N}]/u,WIKI_LINK_RE=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,MD_IMAGE_RE=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var SuggestLinksTargetNotFoundError=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function normalizeSnippet(e){return e.replace(/\s+/g,` `).trim()}function snippetAround(e,t,s){if(!normalizeSnippet(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
1929
|
+
`)}function createSingleFlight(){let e=new Map;return{run(t,s){let g=e.get(t);if(g)return{promise:g,coalesced:!0};let S=s();e.set(t,S);let w=()=>{e.get(t)===S&&e.delete(t)};return S.then(w,w),{promise:S,coalesced:!1}},get size(){return e.size}}}function skillShadowPath(e,t){let s=e===`.`?``:e.replace(/^\.\//,``);return s?`${s}/.ok/skills/${t}`:`.ok/skills/${t}`}function isGitObjectNotFound(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function restoreSkillVersion(e){let{shadow:t,contentDir:s,contentRoot:g,name:S,version:w}=e;if(!existsSync(t.workTree)||!existsSync(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let E=skillShadowPath(g,S),D=shadowGit(t),O;try{O=await D.raw(`ls-tree`,`-r`,`--name-only`,`-z`,w,`--`,E)}catch(e){let t=e instanceof Error?e.message:String(e);return isGitObjectNotFound(t)?{ok:!1,code:`version-not-found`,error:`Version ${w.slice(0,8)} not found.`}:{ok:!1,code:`io-error`,error:`Failed to read version ${w.slice(0,8)}: ${t}`}}let k=splitNulSeparatedPaths(O);if(k.length===0)return{ok:!1,code:`skill-absent`,error:`Skill "${S}" did not exist at version ${w.slice(0,8)}.`};let j=resolve(s,`.ok`,`skills`,S),F=j+sep,L=[];for(let e of k){let t=e.slice(E.length).replace(/^\//,``),s=resolve(j,t);if(s!==j&&!s.startsWith(F))return{ok:!1,code:`path-escape`,error:`Refusing to restore path outside skill dir: ${t}`};try{L.push({rel:t,destAbs:s,content:await D.raw(`show`,`${w}:${e}`)})}catch(e){let s=e instanceof Error?e.message:String(e);return{ok:!1,code:`io-error`,error:`Failed reading ${t} at ${w.slice(0,8)}: ${s}`}}}tracedRmSync(j,{recursive:!0,force:!0});let B=[];for(let{rel:e,destAbs:t,content:s}of L)tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,s,`utf-8`),B.push(e);return{ok:!0,restoredFiles:B}}const log$7=getLogger(`suggest-links`),WORD_CHAR_RE=/[\p{L}\p{N}]/u,WIKI_LINK_RE=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,MD_IMAGE_RE=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var SuggestLinksTargetNotFoundError=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function normalizeSnippet(e){return e.replace(/\s+/g,` `).trim()}function snippetAround(e,t,s){if(!normalizeSnippet(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
1932
1930
|
`,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
|
|
1933
1931
|
`,s)].filter(e=>e>=0),w=g>=0?g+1:Math.max(0,t-60),E=S.length>0?Math.min(...S)+1:Math.min(e.length,s+60),D=w>0?`…`:``,O=E<e.length?`…`:``,k=normalizeSnippet(e.slice(w,E));return k?`${D}${k}${O}`:null}function matchFence(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose(e,t){let s=e.trimStart();if(e.length-s.length>3)return!1;let g=0;for(;s[g]===t.char;)g+=1;return g<t.length?!1:s.slice(g).trim().length===0}function leadingMarkdownPrefixLength(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S+=1;continue}let t=0;for(;e[S+t]==="`";)t+=1;if(t===s)return{text:e.slice(g,S),nextIndex:S+s};S+=t}return{text:e.slice(t,g),nextIndex:g}}function readWikiLink(e,t){WIKI_LINK_RE.lastIndex=t;let s=WIKI_LINK_RE.exec(e);if(!s)return null;let g=s[1]??``,S=g.trim(),w=s[2]?.trim()||null,E=s[3]??null,D=E?.trim()||null;if(!S)return null;let O=D??S,k=D?E:g,j=D?s[0].lastIndexOf(E??``):2,F=k?.indexOf(O)??0;return{target:S,alias:D,anchor:w,label:O,labelStart:t+j+Math.max(F,0),nextIndex:t+s[0].length}}function normalizeMarkdownHref(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink(e,t){MD_LINK_RE.lastIndex=t;let s=MD_LINK_RE.exec(e);return s?{text:s[1]??``,href:normalizeMarkdownHref(s[2]??``),nextIndex:t+s[0].length}:null}function readMarkdownImage(e,t){MD_IMAGE_RE.lastIndex=t;let s=MD_IMAGE_RE.exec(e);return s?{alt:s[1]??``,nextIndex:t+s[0].length}:null}function isWordBoundaryChar(e){return!e||!WORD_CHAR_RE.test(e)}function hasWholeWordBoundaries(e,t,s){return isWordBoundaryChar(e[t-1])&&isWordBoundaryChar(e[s])}function prepareSearchLabels(e){let t=[],s=new Set;for(let g of e.matchLabels){let e=g.trim();if(!e)continue;let S=e.toLocaleLowerCase();s.has(S)||(s.add(S),t.push({raw:e,lower:S,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function findSegmentMatches(e,t){let s=e.toLocaleLowerCase(),g=[];for(let S of t){let t=0;for(;t<=s.length-S.length;){let w=s.indexOf(S.lower,t);if(w===-1)break;let E=w+S.length;hasWholeWordBoundaries(e,w,E)&&g.push({start:w,end:E}),t=w+1}}g.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let s=e.end-e.start,g=t.end-t.start;return g===s?e.end-t.end:g-s});let S=[],w=null;for(let e of g)w&&e.start<w.end||(S.push(e),w=e);return S}function contiguousOffsets(e,t){let s=[];for(let g=0;g<t.length;g+=1)s.push(e+g);return s}function wikiLinkResolvesToTarget(e,t){let s=e.trim();return s?s===t||toWikiLinkSlug(s)===t:!1}function scanLineForMentions(e,t,s,g,S){let w=``,E=[],D=``,O=[];function k(){D&&(E.push({flatStart:w.length,text:D,sourceOffsets:O}),w+=D,D=``,O=[])}function j(e,t){D+=e,O.push(t)}function F(e){k(),w+=e}function L(e,t){k(),e&&(E.push({flatStart:w.length,text:e,sourceOffsets:t}),w+=e)}let B=leadingMarkdownPrefixLength(e);for(;B<e.length;){if(e[B]===`\\`&&B+1<e.length){j(e[B+1]??``,t+B+1),B+=2;continue}if(e[B]==="`"){let t=readInlineCode(e,B);if(t){F(t.text),B=t.nextIndex;continue}}if(e[B]===`!`&&e[B+1]===`[`){let t=readMarkdownImage(e,B);if(t){F(t.alt),B=t.nextIndex;continue}}if(e[B]===`[`&&e[B+1]===`[`){let s=readWikiLink(e,B);if(s){let e=s.label;wikiLinkResolvesToTarget(s.target,g)?F(e):L(e,contiguousOffsets(t+s.labelStart,e)),B=s.nextIndex;continue}}if(e[B]===`[`&&e[B-1]!==`!`){let S=readMarkdownLink(e,B);if(S){resolveInternalHref(S.href,s)?.docName===g?F(S.text):L(S.text,contiguousOffsets(t+B+1,S.text)),B=S.nextIndex;continue}}j(e[B]??``,t+B),B+=1}k();let H=[];for(let e of E){let t=findSegmentMatches(e.text,S);for(let s of t){let t=e.flatStart+s.start,g=e.flatStart+s.end,S=snippetAround(w,t,g)??e.text.slice(s.start,s.end),E=e.sourceOffsets[s.start];typeof E==`number`&&H.push({excerpt:S,offset:E})}}return H}function scanMarkdownForMentions(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=S.length,D=[],O=null,k=0,j=0;for(;j<=w.length;){let e=w[j];if(!(j===w.length||e===`
|
|
1934
1932
|
`||e===`\r`)){j+=1;continue}let S=w.slice(k,j);if(O)isFenceClose(S,O)&&(O=null);else{let e=matchFence(S);e?O=e:D.push(...scanLineForMentions(S,E+k,t,s,g))}if(j===w.length)break;if(e===`\r`&&w[j+1]===`
|
|
@@ -1939,19 +1937,18 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
|
|
|
1939
1937
|
`).filter(e=>e.length===40)}catch{}try{let e=(await oe.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${S}/`)).trim().split(`
|
|
1940
1938
|
`).filter(Boolean);ce.push(...e)}catch{}if(ue&&ce.length===0)try{let e=(await oe.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
|
|
1941
1939
|
`).filter(Boolean);ce.push(...e)}catch{}if(ce.length===0&&se.length===0&&de.length===0)return EMPTY;let fe=[...se,...de],me=[];if(fe.length>0){let t=parseGitLogOutput(await oe.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...fe)).map(e=>({...e,type:`checkpoint`}));if(ne&&(t=await filterEntriesByChain(e,t,O,S,ee,ae,Y)),ue&&se.length>0&&de.length>0){let e=new Set(se),s=t.filter(t=>e.has(t.sha)),g=t.filter(t=>!e.has(t.sha)),S=s.reduce((e,t)=>{let s=new Date(t.timestamp).getTime();return s<e?s:e},1/0);me=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else me=t}let ge=[...ce];for(let e of fe)ge.push(e);let _e=[];if(ge.length>0&&(_e=parseGitLogOutput(await oe.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D),...ge,...ne?[`--`,ne]:[])),_e.length>=D&&(k=!0),J))for(let t=0;t<O.length-1;t++){let s=O[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,Y);if(t.length===0)continue;let g=ee(s.path),w=parseGitLogOutput(await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D)],t,g));w.length>=D&&(k=!0),_e=[..._e,...w]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let ve=[...me,..._e],ye=new Set,Ce=[];for(let e of ve)ye.has(e.sha)||(ye.add(e.sha),Ce.push(e));let we=Ce;Ce.length>0&&O.length>0&&(we=filterEntriesByOkActorDocs(Ce,O,await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,Y);return s.length===0?new Set:buildAncestorShaSet(e,s,S,ae)})))),we.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let Te=we;Te=Te.filter(e=>e.type!==`park`),H||(Te=Te.filter(e=>e.checkpoint?.kind!==`auto-consolidation`)),F.length>0&&(Te=Te.filter(e=>F.includes(e.type))),L.length>0&&(Te=Te.filter(e=>matchesAuthor(e,L))),B.length>0&&(Te=Te.filter(e=>!matchesAuthor(e,B)));let De=Te.length,je=Te.slice(E,E+w),Me=je.map(({rawBody:e,...t})=>t);return j(ge.length,Ce.length),{entries:Me,total:De,hasMore:k&&je.length>0||E+w<De}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),j(0,0,!0),EMPTY}}async function getFolderTimeline(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.includes(`..`)||t.includes(`\0`))return EMPTY;let S=g?.branch??`main`,w=Math.max(1,g?.limit??50),E=Math.max(0,g?.offset??0),D=s===`.`?``:s.replace(/^\.\//,``),O=t.replace(/^\.?\/+/,``).replace(/\/+$/,``),k=[D,O,`.ok`].filter(Boolean).join(`/`),j=shadowGit(e);try{let e=[];for(let t of[`refs/wip/${S}/`,`refs/checkpoints/${S}/`])try{let s=(await j.raw(`for-each-ref`,`--format=%(refname)`,t)).trim().split(`
|
|
1942
|
-
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=historyWalkCap(E,w),s=parseGitLogOutput(await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(t),...e,`--`,k)),g=s.length>=t,D=O?`${O}/.ok/`:`.ok/`,F=new Set,L=[];for(let e of s){if(F.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(D))))continue;F.add(e.sha);let{rawBody:t,...s}=e;L.push(s)}let B=L.length,H=L.slice(E,E+w);return{entries:H,total:B,hasMore:g&&H.length>0||E+w<B}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}let _searchCorpusTruncatedCounter=null;function searchCorpusTruncatedCounter(){return _searchCorpusTruncatedCounter||=getMeter().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of search-corpus rebuilds where the name-only file tier hit OK_SEARCH_MAX_ENTRIES and dropped deepest-tail paths. One increment per truncated build; non-truncated builds do not increment.`}),_searchCorpusTruncatedCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$6=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=managedArtifactTimelinePaths(e);if(g.managed&&g.versioned)return{path:s?`${s}/${g.filePath}`:g.filePath};let S=getDocExtension(e);return{path:s?`${s}/${e}${S}`:`${e}${S}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k=``,j,F,L=!1,B=(e,t)=>{if(!w){if(w=!0,j)try{unlinkSync(j)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},H=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t),e===`placement`&&(k=t)}),S.on(`file`,(e,g,S)=>{L=!0,E=S.filename||`upload`,D=S.mimeType||``;let q;try{q=mintTempUploadPath(t)}catch(e){B(H(e),e),g.resume();return}j=q;let ee=new HashingPassThrough;pipeline(g,ee,createWriteStream(q)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,placement:k,tempPath:q,sha:ee.digest(),byteLength:ee.byteLength()}))}).catch(e=>{F=e,B(H(e),e)})}),S.on(`error`,e=>{B(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||F||L||(w=!0,s({filename:``,mimeType:``,parentDocName:O,placement:k,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||F||e.complete||B(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(!isWithinDir(s,e))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}const DEFAULT_SEARCH_MAX_ENTRIES=5e4;function getSearchMaxEntries(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return DEFAULT_SEARCH_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SEARCH_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>isWithinDir(e,L);async function H(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,{bypassFilters:!0}))continue;try{if(!B(await realpath(join(e,S.name))))continue}catch(t){console.warn(`[document-list][showAll] probe realpath failed for ${e}/${S.name}:`,t);continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,g,L){let q=[{absDir:e,relDir:g,depth:L}];for(let e=0;e<q.length;e++){if(E?.aborted){j=!0;return}let{absDir:g,relDir:L,depth:ee}=q[e],J;try{J=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[document-list][showAll] readdir failed for ${g}:`,e);continue}for(let e of J){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let J=L?`${L}/${e.name}`:e.name;if(e.isDirectory()){if(s.isDirExcluded(J,{bypassFilters:!0}))continue;let t=join(g,e.name),S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(J)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=ee>=D?await H(t,J):void 0;yield{kind:`folder`,path:J,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}ee<D&&q.push({absDir:t,relDir:J,depth:ee+1});continue}if(e.isSymbolicLink()){let w=join(g,e.name),E;try{E=await realpath(w)}catch(e){console.warn(`[document-list][showAll] symlink realpath failed for ${w}:`,e);continue}if(!B(E)){console.warn(`[document-list][showAll] refusing symlink-escape ${w} -> ${E}`);continue}let D;try{D=await stat$1(E)}catch(e){console.warn(`[document-list][showAll] symlink target stat failed for ${w}:`,e);continue}let k=toPosix(relative(t,E));if(D.isDirectory()){if(s.isDirExcluded(J,{bypassFilters:!0})||!F(J))continue;O+=1,yield{kind:`folder`,path:J,size:0,modified:D.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:k,targetPath:k,hasChildren:await H(E,J)};continue}if(!D.isFile()||s.isExcluded(J,{bypassFilters:!0})||!F(J))continue;if(O+=1,isSupportedDocFile(e.name)){let e=J.replace(/\.(md|mdx)$/i,``);yield{kind:`document`,docName:e,docExt:S(e),size:D.size,modified:D.mtime.toISOString(),isSymlink:!0,canonicalDocName:k.replace(/\.(md|mdx)$/i,``),targetPath:k}}else{let t=synthesizeShowAllAssetExt(e.name);yield{kind:`asset`,docName:J,docExt:t,path:J,assetExt:t,mediaKind:mediaKindForSidebarAssetExtension(t),referencedBy:[],size:D.size,modified:D.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:k}}continue}if(!e.isFile()||s.isExcluded(J,{bypassFilters:!0})||!F(J))continue;let Y=null;try{Y=await stat$1(join(g,e.name))}catch(t){console.warn(`[document-list][showAll] stat failed for ${g}/${e.name}:`,t);continue}if(isSupportedDocFile(e.name)){let e=J.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let te=synthesizeShowAllAssetExt(e.name),ne=mediaKindForSidebarAssetExtension(te);O+=1,yield{kind:`asset`,docName:J,docExt:te,path:J,assetExt:te,mediaKind:ne,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*q(g?join(t,g):t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?isSupportedDocFile(s)?s:`${s}${getDocExtension(s)}`:s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);if(isSupportedDocFile(t)){let e=resolve(s,t);e!==s&&e.startsWith(`${s}${sep}`)&&existsSync(e)&®isterDocExtension(stripDocExtension(t),extname(t));return}for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID$1()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function writeFileIfContentDiffers(e,t){(existsSync(e)?readFileSync(e,`utf-8`):null)!==t&&tracedWriteFileSync(e,t,`utf-8`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1940
|
+
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=historyWalkCap(E,w),s=parseGitLogOutput(await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(t),...e,`--`,k)),g=s.length>=t,D=O?`${O}/.ok/`:`.ok/`,F=new Set,L=[];for(let e of s){if(F.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(D))))continue;F.add(e.sha);let{rawBody:t,...s}=e;L.push(s)}let B=L.length,H=L.slice(E,E+w);return{entries:H,total:B,hasMore:g&&H.length>0||E+w<B}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}let _searchCorpusTruncatedCounter=null;function searchCorpusTruncatedCounter(){return _searchCorpusTruncatedCounter||=getMeter().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of search-corpus rebuilds where the name-only file tier hit OK_SEARCH_MAX_ENTRIES and dropped deepest-tail paths. One increment per truncated build; non-truncated builds do not increment.`}),_searchCorpusTruncatedCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$6=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=managedArtifactTimelinePaths(e);if(g.managed&&g.versioned)return{path:s?`${s}/${g.filePath}`:g.filePath};let S=getDocExtension(e);return{path:s?`${s}/${e}${S}`:`${e}${S}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k=``,j,F,L=!1,B=(e,t)=>{if(!w){if(w=!0,j)try{unlinkSync(j)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},H=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t),e===`placement`&&(k=t)}),S.on(`file`,(e,g,S)=>{L=!0,E=S.filename||`upload`,D=S.mimeType||``;let q;try{q=mintTempUploadPath(t)}catch(e){B(H(e),e),g.resume();return}j=q;let ee=new HashingPassThrough;pipeline(g,ee,createWriteStream(q)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,placement:k,tempPath:q,sha:ee.digest(),byteLength:ee.byteLength()}))}).catch(e=>{F=e,B(H(e),e)})}),S.on(`error`,e=>{B(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||F||L||(w=!0,s({filename:``,mimeType:``,parentDocName:O,placement:k,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||F||e.complete||B(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(!isWithinDir(s,e))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}const DEFAULT_SEARCH_MAX_ENTRIES=5e4;function getSearchMaxEntries(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return DEFAULT_SEARCH_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SEARCH_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>isWithinDir(e,L);async function H(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,{bypassFilters:!0}))continue;try{if(!B(await realpath(join(e,S.name))))continue}catch(t){console.warn(`[document-list][showAll] probe realpath failed for ${e}/${S.name}:`,t);continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,g,L){let q=[{absDir:e,relDir:g,depth:L}];for(let e=0;e<q.length;e++){if(E?.aborted){j=!0;return}let{absDir:g,relDir:L,depth:ee}=q[e],J;try{J=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[document-list][showAll] readdir failed for ${g}:`,e);continue}for(let e of J){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let J=L?`${L}/${e.name}`:e.name;if(e.isDirectory()){if(s.isDirExcluded(J,{bypassFilters:!0}))continue;let t=join(g,e.name),S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(J)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=ee>=D?await H(t,J):void 0;yield{kind:`folder`,path:J,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}ee<D&&q.push({absDir:t,relDir:J,depth:ee+1});continue}if(e.isSymbolicLink()){let w=join(g,e.name),E;try{E=await realpath(w)}catch(e){console.warn(`[document-list][showAll] symlink realpath failed for ${w}:`,e);continue}if(!B(E)){console.warn(`[document-list][showAll] refusing symlink-escape ${w} -> ${E}`);continue}let D;try{D=await stat$1(E)}catch(e){console.warn(`[document-list][showAll] symlink target stat failed for ${w}:`,e);continue}let k=toPosix(relative(t,E));if(D.isDirectory()){if(s.isDirExcluded(J,{bypassFilters:!0})||!F(J))continue;O+=1,yield{kind:`folder`,path:J,size:0,modified:D.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:k,targetPath:k,hasChildren:await H(E,J)};continue}if(!D.isFile()||s.isExcluded(J,{bypassFilters:!0})||!F(J))continue;if(O+=1,isSupportedDocFile(e.name)){let e=J.replace(/\.(md|mdx)$/i,``);yield{kind:`document`,docName:e,docExt:S(e),size:D.size,modified:D.mtime.toISOString(),isSymlink:!0,canonicalDocName:k.replace(/\.(md|mdx)$/i,``),targetPath:k}}else{let t=synthesizeShowAllAssetExt(e.name);yield{kind:`asset`,docName:J,docExt:t,path:J,assetExt:t,mediaKind:mediaKindForSidebarAssetExtension(t),referencedBy:[],size:D.size,modified:D.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:k}}continue}if(!e.isFile()||s.isExcluded(J,{bypassFilters:!0})||!F(J))continue;let Y=null;try{Y=await stat$1(join(g,e.name))}catch(t){console.warn(`[document-list][showAll] stat failed for ${g}/${e.name}:`,t);continue}if(isSupportedDocFile(e.name)){let e=J.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let te=synthesizeShowAllAssetExt(e.name),ne=mediaKindForSidebarAssetExtension(te);O+=1,yield{kind:`asset`,docName:J,docExt:te,path:J,assetExt:te,mediaKind:ne,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*q(g?join(t,g):t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?isSupportedDocFile(s)?s:`${s}${getDocExtension(s)}`:s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);if(isSupportedDocFile(t)){let e=resolve(s,t);e!==s&&e.startsWith(`${s}${sep}`)&&existsSync(e)&®isterDocExtension(stripDocExtension(t),extname(t));return}for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function writeFileIfContentDiffers(e,t){(existsSync(e)?readFileSync(e,`utf-8`):null)!==t&&tracedWriteFileSync(e,t,`utf-8`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1943
1941
|
`)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1}=e,Ge=createConcurrencyGuard(),Ke=new Map,Xe=createSingleFlight(),$e=null;function nt(){let e=j?.();return e instanceof Map?e:null}function rt(e){let t=nt();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function it(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)rt(resolve(g,t.slice(0,e).join(`/`)))}function at(e){let t=nt();t&&removeFolderIndexEntries(t,e)}function st(e,t){let s=nt();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&rt(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function vt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1944
|
-
`)}function Tt(){$e=null}F?.(Tt);let Et=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Dt(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return isWithinDir(s,t)?s:null}function jt(e){let t=Dt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(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,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Dt(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$6.debug({docName:e,elapsedMs:g,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 zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$6.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function Kt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function $t(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function en(e){if(!De)return!1;let t=isSupportedDocFile(e)?e:`${e}${getDocExtension(e)}`;return De.isExcluded(t)}function jr(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?nu:g,`.ok`,`skills`);for(let g of lu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(iu(t.source_folder,t.name))}catch(e){log$6.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||en(t)||e.add(t);return e}let Mr=e=>existsSync(resolve(g,e));function Fr(e,t){en(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function Ir(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let Lr=Ir(),zr=e=>e.endsWith(`.`)?e:`${e}.`;function Br(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:zr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:zr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:zr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:zr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:zr(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 Vr(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.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),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return g}function Hr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Ur(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Wr(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Gr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Kr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=Jr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function qr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function Jr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=qr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Yr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=qr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Xr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Wr(g);if(typeof s!=`string`)continue;let S=qr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Zr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Qr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Yr(S.docName,s):S;e.rewrites!==0&&(Gr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function ji(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Hi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ui(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Gi(e,t){return Lr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Xr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Zr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Qr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Ki(e,s){return Lr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Xr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Zr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Vr([w])).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Qr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Yi(e,s,S,E){return Lr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ui(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Hi(k)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Xr(L);Zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Qr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Wr(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Wr(t);typeof e==`string`&&Jr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Zr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ur([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Kr(e,H,L):Jr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Gr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Vr([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>e!==t);t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID$1(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=Jr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Hr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.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`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Xi(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 Zi(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function ka(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 _s(e){return{value:e.value}}function xs(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Cs(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=ka(S),E=g||!w.response?w.response:_s(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),xs(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=ka(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}xs(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function Ts(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Ds(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=ka(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Os(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ks=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=ka(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),xs(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Kt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=$t(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}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$6.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`}),As=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Xi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=ka(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Zi({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),xs(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Kt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();Fr(O,ce);let ue=await validateMermaidFences(ce,O),de=jr();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,Mr),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=$t(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}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$6.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`}),Ns=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=ka(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1942
|
+
`)}function Tt(){$e=null}F?.(Tt);let Et=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Dt(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return isWithinDir(s,t)?s:null}function jt(e){let t=Dt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(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,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Dt(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$6.debug({docName:e,elapsedMs:g,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 zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$6.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function Kt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function $t(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function en(e){if(!De)return!1;let t=isSupportedDocFile(e)?e:`${e}${getDocExtension(e)}`;return De.isExcluded(t)}function jr(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?nu:g,`.ok`,`skills`);for(let g of lu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(iu(t.source_folder,t.name))}catch(e){log$6.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||en(t)||e.add(t);return e}let Mr=e=>existsSync(resolve(g,e));function Fr(e,t){en(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function Ir(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let Lr=Ir(),zr=e=>e.endsWith(`.`)?e:`${e}.`;function Br(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:zr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:zr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:zr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:zr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:zr(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 Vr(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.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),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return g}function Hr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Ur(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Wr(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Gr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Kr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=Jr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function qr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function Jr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=qr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Yr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=qr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Xr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Wr(g);if(typeof s!=`string`)continue;let S=qr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Zr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Qr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Yr(S.docName,s):S;e.rewrites!==0&&(Gr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function ji(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Hi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ui(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Gi(e,t){return Lr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Xr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Zr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Qr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Ki(e,s){return Lr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Xr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Zr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Vr([w])).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Qr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Yi(e,s,S,E){return Lr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ui(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Hi(k)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Xr(L);Zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Qr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Wr(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Wr(t);typeof e==`string`&&Jr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Zr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ur([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Kr(e,H,L):Jr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Gr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Vr([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>e!==t);t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=Jr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Hr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.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`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Xi(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 Zi(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function ka(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 _s(e){return{value:e.value}}function xs(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Cs(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=ka(S),E=g||!w.response?w.response:_s(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),xs(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=ka(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}xs(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function Ts(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Ds(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=ka(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Os(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ks=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=ka(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),xs(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Kt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=$t(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}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$6.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`}),As=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Xi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=ka(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Zi({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),xs(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Kt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();Fr(O,ce);let ue=await validateMermaidFences(ce,O),de=jr();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,Mr),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=$t(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}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$6.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`}),Ns=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=ka(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1945
1943
|
`),S=s.nextFenced+(g?`
|
|
1946
1944
|
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Kt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=$t(ne);Fr(D,te.dc.document.getText(`source`).toString());let ye=jr();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,Mr);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ps(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Is=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ps(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.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:w,content:e.getText(`source`).toString(),lifecycle:Ps(e)},{handler:`document-read`})}finally{await D.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}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.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`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$6.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.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}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{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}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(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}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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 g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{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}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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 g=jr();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),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}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,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:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=jr();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),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:E},{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}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(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}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=jr();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),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}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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 g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(jr(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(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}),oc=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Xi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=ka(J);recordContributor(j,F,L,B,void 0,Zi({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Kt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=ka(J),ye=Y.dc.document.getText(`source`).toString();Fr(j,ye);let Ce=await validateMermaidFences(ye,j),we=jr();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,Mr),De=$t(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}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$6.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`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Xi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Zi({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Kt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$6.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$6.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}),lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$6.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}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$6.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$6.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.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`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(nu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`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}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`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}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Xi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.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}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$6.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`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Il(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{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 gc(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 g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`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(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);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 E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=ka(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=ka(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$6.debug({docName:O,commitSha:k.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(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Kt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$6.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}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$6.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}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{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 xc(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=we?.()??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 Sc(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=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$6.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 Cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function wc(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(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!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:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Tc=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 S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$6.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}),Ec=1048576,Dc=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-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$6.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$6.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}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,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)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{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`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).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(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`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`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=w===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(E)||isConfigDoc(E))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!k)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,B);try{tracedCpSync(D,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of H)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&H.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:B,duplicatedDocNames:H},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Nc=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 g=Dt(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){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(g,`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}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Ki(E,D):await Gi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Tt();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$6.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let k=O===`file`?[stripDocExtension(E)]:Hi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):De.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Yi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Tt();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$6.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Xi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?ji(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[stripDocExtension(D)]:Hi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),Tt();for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ic=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,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Tt(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(Tt(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{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`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}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}),Rc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{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 zc(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,Ce??g)}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:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Xi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===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(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$6.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,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$6.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){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(te),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 ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$6.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc=`local-op-clone`,Gc=withValidation(LocalOpCloneRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Wc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Wc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Wc,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 E=createStreamingErrorWriter(t,Wc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$6.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await qc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(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?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$6.error({err:e,handler:Wc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function qc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$6.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$6.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Jc=`local-op-ok-init`,Yc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Jc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Jc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc});return}if(!Ge.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Jc})}finally{Ge.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`/api/local-op/auth/login`,Zc=`/api/local-op/auth/status`,Qc=`/api/local-op/auth/repos`,$c=`/api/local-op/auth/signout`,nl=null,il=`local-op-auth-login`,al=withValidation(LocalOpAuthHostRequestSchema,cl,{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})});async function cl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){let e=nl;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:il,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),nl=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,il),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});nl=w;let E=()=>{w.cancel(),nl===w&&(nl=null,Ge.release(Xc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}nl===w&&(nl=null,Ge.release(Xc))})}let ll=`local-op-auth-status`,ul=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:ll,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1947
1945
|
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:ll}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:ll})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:ll,cause:e})}finally{Ge.release(Zc)}},{handler:ll,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ll})}),dl=`local-op-auth-repos`,fl=withValidation(LocalOpAuthHostRequestSchema,pl,{handler:dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dl})});async function pl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:dl,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 S=createStreamingErrorWriter(t,dl),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Hc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1948
|
-
`);k=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`){S(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{}}}),j.stderr.on(`data`,e=>{log$6.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Qc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(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=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(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=ve?.();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 Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Dl(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`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{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 Ol=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{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 kl(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 jl=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 Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Et.probeAll)}catch(e){t.headersSent||(log$6.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}))}}let Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.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 Fl(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(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,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 Il(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.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 zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Bl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=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 ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{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}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Il(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?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.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Wl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{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}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,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`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)]);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});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}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),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}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)]);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)]);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)]);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)]);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ru(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(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`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$6.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{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}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{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`}),sd=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 cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$6.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 ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$6.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 ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(Ce);if(e===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readOriginGitHubRepo(Ce);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(Ce,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,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})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),fd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function pd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let md=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.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 pd([`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{Ge.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})}),hd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){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(!Ge.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 pd([`share`,`name-check`,`--owner`,g,`--name`,S,`--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{Ge.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})}),gd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){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(!Ge.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`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await pd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{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{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),_d=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),vd=Ce?getLocalDir(Ce):null;async function yd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}vd&&clearArmedPaneTarget(vd),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:vd?readServerLock(vd)?.port??0:0,paneTarget:vd?readArmedPaneTarget(vd):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let bd=`local-op-embeddings-set-key`,xd=`local-op-embeddings-clear-key`,Sd=`/api/local-op/embeddings`,Cd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:bd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bd,cause:e})}finally{Ge.release(Sd)}},{handler:bd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bd})}),wd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xd,cause:e})}finally{Ge.release(Sd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Ed={"/api/config":yd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Td,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/git/branch-info":dd,"/api/git/checkout":fd,"/api/share/publish/owners":md,"/api/share/publish/name-check":hd,"/api/share/publish":gd,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":Cd,"/api/local-op/embeddings/clear-key":wd,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":_d};q&&(Ed[`/api/test-reset`]=dc,Ed[`/api/test-flush-git`]=uc,Ed[`/api/test-rescan-backlinks`]=fc,Ed[`/api/test-rescan-files`]=pc);let Dd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Od=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),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, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Dd.has(s)||Od.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(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Ed[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Ed[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.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:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$5=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$5.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$5.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$5.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,g=[]){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:S}=await import(`./git-handle-DdgvPBh6-C80s8fFN.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
1949
|
-
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$5.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$5.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!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 j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const 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 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,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1946
|
+
`);k=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`){S(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{}}}),j.stderr.on(`data`,e=>{log$6.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Qc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(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=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(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=ve?.();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 Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Dl(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`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{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 Ol=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{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 kl(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 jl=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 Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Et.probeAll)}catch(e){t.headersSent||(log$6.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}))}}let Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.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 Fl(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(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,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 Il(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.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 zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Bl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=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 ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{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}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Il(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?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.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Wl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{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}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,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`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)]);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});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}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),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}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)]);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)]);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)]);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)]);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ru(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(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`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$6.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{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}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{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`}),sd=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 cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$6.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 ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$6.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 ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),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`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{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})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),fd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),pd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function md(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let hd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.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 md([`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{Ge.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})}),gd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){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(!Ge.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 md([`share`,`name-check`,`--owner`,g,`--name`,S,`--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{Ge.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})}),_d=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){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(!Ge.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`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await md(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{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{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),vd=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),yd=Ce?getLocalDir(Ce):null;async function bd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}yd&&clearArmedPaneTarget(yd),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:yd?readServerLock(yd)?.port??0:0,paneTarget:yd?readArmedPaneTarget(yd):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let xd=`local-op-embeddings-set-key`,Sd=`local-op-embeddings-clear-key`,Cd=`/api/local-op/embeddings`,wd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:xd,cause:e})}finally{Ge.release(Cd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Sd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Sd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Sd,cause:e})}finally{Ge.release(Cd)}},{handler:Sd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Sd})}),Ed=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Dd={"/api/config":bd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Ed,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/share/target-status":fd,"/api/git/branch-info":dd,"/api/git/checkout":pd,"/api/share/publish/owners":hd,"/api/share/publish/name-check":gd,"/api/share/publish":_d,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":wd,"/api/local-op/embeddings/clear-key":Td,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":vd};q&&(Dd[`/api/test-reset`]=dc,Dd[`/api/test-flush-git`]=uc,Dd[`/api/test-rescan-backlinks`]=fc,Dd[`/api/test-rescan-files`]=pc);let Od=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),kd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),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, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Od.has(s)||kd.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(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Dd[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Dd[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.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:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$5=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$5.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$5.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$5.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,g=[]){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:S}=await import(`./git-handle-DjEtQkHv-DQXg1XhZ.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let{splitNulSeparatedPaths:e}=await import(`./git-handle-DjEtQkHv-DQXg1XhZ.mjs`),t=e(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]));for(let e of t)this.addConflict({file:e,detectedAt:s});g=t.length>0}catch(e){log$5.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$5.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!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 j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const 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 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,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1950
1947
|
`)){let e=s.trim();if(!e)continue;let g=e.indexOf(` `);if(g===-1)continue;let S=e.slice(0,g),w=e.slice(g+1),E=Number.parseInt(S,10);!Number.isNaN(E)&&isOkProcess(w)&&t.push({pid:E,command:w})}return t}function parsePsOutput(e){let t=[],s=e.split(`
|
|
1951
1948
|
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
|
|
1952
1949
|
`))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function parseListeningPids(e){let t=[],s=e.split(`
|
|
1953
1950
|
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.split(/\s+/);if(S.length<2)continue;let w=Number.parseInt(S[1]??``,10);Number.isNaN(w)||t.push(w)}return[...new Set(t)]}function hasLockFile(e){return existsSync(join(e,`server.lock`))||existsSync(join(e,`ui.lock`))}function addLockDirsForCwd(e,t){for(let s of[join(t,`.ok`,`local`),join(t,`.ok`)])existsSync(s)&&hasLockFile(s)&&e.add(s)}function addLockDirsUnderCwd(e,t){let s=0,g=(t,S)=>{if(s>=LOCK_SCAN_MAX_ENTRIES||(s++,addLockDirsForCwd(e,t),S>=LOCK_SCAN_MAX_DEPTH))return;let w;try{w=readdirSync(t)}catch{return}for(let e of w){if(s>=LOCK_SCAN_MAX_ENTRIES)return;if(e===`node_modules`||e===`.git`||e===`Library`||e.startsWith(`.`)&&e!==`.ok`)continue;let w=join(t,e),E=!1;try{E=lstatSync(w).isDirectory()}catch{continue}E&&g(w,S+1)}};g(t,0)}async function discoverLockDirs(){let e=new Set,t=await findOkProcessEntries(),s=t.map(e=>pidCwd(e.pid)),g=await Promise.all(s);for(let s of t){let t=extractMarkedLockDir(s.command);t!=null&&existsSync(t)&&e.add(t);let g=extractProjectPathArg(s.command);g!=null&&addLockDirsForCwd(e,g)}for(let t of g)t!=null&&addLockDirsForCwd(e,t);let S=spawnSync(`lsof`,[`-iTCP`,`-sTCP:LISTEN`,`-nP`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(S.error==null&&S.stdout){let s=parseListeningPids(S.stdout),g=new Set(t.map(e=>e.pid)),w=s.filter(e=>!g.has(e)).map(e=>pidCwd(e)),E=await Promise.all(w);for(let t of E)t!=null&&addLockDirsForCwd(e,t)}(e.size===0||g.some(e=>e===`/`))&&addLockDirsUnderCwd(e,process.cwd());let w=new Map;for(let t of e)try{let e=await realpath(t);w.set(e,e)}catch{w.set(t,t)}return[...w.values()]}function isPathInside(e,t){if(e===t)return!0;let s=t.endsWith(sep)?t:t+sep;return e.startsWith(s)}function toDocName(e,t){return relative(e,t).split(sep).join(`/`).replace(/\.(md|mdx)$/i,``)}async function resolveOffCwdTarget(e,t){let s=await t.realpath(resolve(e)).catch(()=>resolve(e)),g=await t.discover(),S=await Promise.all(g.map(e=>t.inspect(e).catch(()=>null))),w=null;for(let e of S)e===null||!e.alive||isPathInside(s,e.contentDir)&&(w===null||e.contentDir.length>w.contentDir.length)&&(w=e);return w===null?null:{baseUrl:w.baseUrl,docName:toDocName(w.contentDir,s)}}function projectDirOfLockDir(e){return dirname(dirname(e))}function createOffCwdResolverDeps(){return{discover:()=>discoverLockDirs(),realpath:e=>realpath(e).catch(()=>e),inspect:async e=>{let t=projectDirOfLockDir(e),s;try{let e=resolve(t,readConfigSafely({absPath:resolveConfigPath(`project`,t),sideline:!1,warn:()=>{}}).value.content?.dir??`.`);s=await realpath(e).catch(()=>e)}catch(t){return process.stderr.write(`[off-cwd-resolver] skipping ${e} (config unreadable): ${t instanceof Error?t.message:String(t)}\n`),null}let g=readUiLock(e),S=g?.port??0,w=g!=null&&S>0&&isProcessAlive(g.pid);return{lockDir:e,contentDir:s,baseUrl:`http://localhost:${S}`,alive:w}}}}const DEFAULT_POLL_INTERVAL_MS=500,DEFAULT_TIMEOUT_MS=15e3,inflight=new Map;function ensureSingleFileSession(e,t){let s=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=t.now??(()=>Date.now()),S=t.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,w=t.timeoutMs??DEFAULT_TIMEOUT_MS;return(async()=>{let E=await t.realpath(resolve(e)).catch(()=>resolve(e)),D=inflight.get(E);if(D)return D;let O=(async()=>{let e=()=>t.isServing(E).catch(()=>!1);if(await e())return!0;t.spawnSession(E);let D=g()+w;for(;g()<D;)if(await s(S),await e())return!0;return!1})().finally(()=>{inflight.delete(E)});return inflight.set(E,O),O})()}function createEnsureSingleFileSession(){let e={spawnSession:e=>{if(!isSupportedDocFile(e)||!existsSync(e))return;let t=process.argv[1];if(!t){process.stderr.write(`[ensure-single-file-session] process.argv[1] is empty — cannot spawn a single-file session
|
|
1954
|
-
`);return}let s={...process.env,OK_SINGLE_FILE_NO_OPEN:`1`,ELECTRON_RUN_AS_NODE:`1`};spawn(process.execPath,[t,e],{detached:!0,stdio:`ignore`,env:s}).unref()},isServing:async e=>await resolveOffCwdTarget(e,createOffCwdResolverDeps())!==null,realpath:e=>realpath(e).catch(()=>e)};return t=>ensureSingleFileSession(t,e)}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID
|
|
1951
|
+
`);return}let s={...process.env,OK_SINGLE_FILE_NO_OPEN:`1`,ELECTRON_RUN_AS_NODE:`1`};spawn(process.execPath,[t,e],{detached:!0,stdio:`ignore`,env:s}).unref()},isServing:async e=>await resolveOffCwdTarget(e,createOffCwdResolverDeps())!==null,realpath:e=>realpath(e).catch(()=>e)};return t=>ensureSingleFileSession(t,e)}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 g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}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 g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}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(`
|
|
1955
1952
|
`).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 g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Save a project-wide checkpoint of every document — a single restore point you can return to.`,``,`**Parameters:**`,'- `summary` — Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Appears as the checkpoint subject in `history`. Avoid secrets or PII — persisted to git history.',``,"Returns `{ version }` — the 40-char checkpoint SHA. Find checkpoints later via `history`; restore a single doc with `restore_version({ document, version })`."].join(`
|
|
1956
1953
|
`);function register$18(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$18,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$17=[`[Operates on disk; no running OK server required] Read the effective merged OpenKnowledge 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 `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"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(`
|
|
1957
1954
|
`),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent 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$17(e,t){e.registerTool(`config`,{description:DESCRIPTION$17,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,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 g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$16=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
|
|
@@ -2005,7 +2002,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
|
|
|
2005
2002
|
`),{document:E,version:e.version,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{},...j?{summary:j}:{},...L?{warnings:L}:{}})})}const DESCRIPTION$4=["[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).",``,"NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only). `exec`-grep covers every content occurrence and needs no server.",``,'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
|
|
2006
2003
|
`),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),semantic:boolean().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`,`file`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number(),vector:number().optional()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),SearchSemanticStatusSchema=object$1({capable:boolean(),applied:boolean(),coverage:object$1({embedded:number().int(),total:number().int()})}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable(),semantic:SearchSemanticStatusSchema.optional(),ready:literal(!1).optional()});function isSearchKind(e){return e===`page`||e===`folder`||e===`file`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0,...typeof e?.vector==`number`?{vector:e.vector}:{}}}function normalizeSemanticStatus(e){if(!(!e||typeof e.capable!=`boolean`))return{capable:e.capable,applied:e.applied===!0,coverage:{embedded:typeof e.coverage?.embedded==`number`?e.coverage.embedded:0,total:typeof e.coverage?.total==`number`?e.coverage.total:0}}}function formatSemanticNote(e){if(!e)return``;if(!e.capable)return`> Semantic: enabled but not ready (no API key, or warming up) — lexical ranking only.`;let{embedded:t,total:s}=e.coverage;return e.applied?`> Semantic: on — vector signal contributed (${t}/${s} pages embedded).`:t<s?`> Semantic: on — indexing ${t}/${s} pages; vectors are still filling in, re-run for fuller coverage.`:`> Semantic: on — no page cleared the similarity threshold for this query.`}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
|
|
2007
2004
|
`)}function register$4(e,t){e.registerTool(`search`,{description:DESCRIPTION$4,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D,semantic:e.semantic??!0,source:`mcp`};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L=normalizeSemanticStatus(k.semantic),B=k.ready!==!1,H={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null,...L?{semantic:L}:{},...B?{}:{ready:!1}},q=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`,ee=formatSemanticNote(L),J=B?F.length===0?`No matches for "${e.query}".`:`${q}\n\n${formatResultsBlock(F)}`:`The workspace search index is still warming — results for "${e.query}" are not ready yet. Wait ~2-3 seconds, then retry; if it is still warming after 2-3 retries, use \`exec("grep ...")\` for an index-free search instead.`;return textPlusStructured(ee?`${J}\n${ee}`:J,H)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
|
|
2008
|
-
`);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$3(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$3,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},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:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},ee={config:t.config,resolveCwd:t.resolveCwd},J=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),ee,g);if(J&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;J={...J,url:t}}let Y=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${Y}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{}})})}function bundleFileKind(e){return e.replace(/\\/g,`/`).startsWith(`scripts/`)?`script`:`reference`}const INTERNAL_BUNDLE_SKILL_NAMES=new Set(Object.values(BUNDLE_SKILL_NAME));function internalSkillHint(e){return[`"${e}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,`It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.`,"The `skills` tool only covers skills authored as KB content (`.ok/skills` = project, `~/.ok/skills` = global). Built-in `open-knowledge*` skills never appear in either scope."].join(` `)}const SCOPE_FIELD_DESCRIBE="Which level the skill lives at. `project` = this KB's `.ok/skills/` (shared via git with everyone on the project); `global` = your user-level `~/.ok/skills/` (available in every project on this machine, not shared).",SkillListEntryOutputSchema=object$1({name:string().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().optional().describe(`The skill's one-line description (when present).`),installed:boolean().describe(`True when projected into ≥1 editor; false = a Draft.`),hosts:array(string()).describe(`Editor ids the skill is installed into.`),updateAvailable:boolean().optional().describe(`Starter-pack skills only: a newer bundled version is available.`)}),SkillBundleFileEntrySchema=object$1({path:string().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:_enum([`reference`,`script`]).describe("`reference` (under references/) or `script` (under scripts/).")}),SkillReadOutputSchema=object$1({name:string().describe(`Skill name (its identity).`),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().describe(`The skill's one-line description (empty if none).`),body:string().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:array(SkillBundleFileEntrySchema).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),SkillFileReadOutputSchema=object$1({path:string().describe(`Skill-relative path read.`),kind:_enum([`reference`,`script`]).describe("`reference` or `script`."),text:string().describe(`Full text of the bundle file.`)}),DESCRIPTION$2=["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you find and read skills. Skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Covers only skills authored as KB content. OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Three modes:**`,"- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts, and (for starter packs) `updateAvailable`.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
|
|
2005
|
+
`);function freshnessWarning(e,t){return e===`absent`?`This ${t} isn't on GitHub yet. The link won't work until it's pushed.\n\n`:e===`stale`?`This ${t} has unpushed changes. Recipients will see the last pushed version.\n\n`:``}function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:_enum([`current`,`stale`,`absent`]).optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), or absent (not on origin). Omitted when the probe could not run.`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$3(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$3,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},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:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H,freshness:q}=F,ee={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind,...q?{freshness:q}:{}},J={config:t.config,resolveCwd:t.resolveCwd},Y=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),J,g);if(Y&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;Y={...Y,url:t}}let te=e.path===``?`(content root)`:e.path;return textPlusStructured(`${freshnessWarning(q,E.kind)}Share link for ${E.kind} \`${te}\` on branch \`${H}\`:\n${L}`,{...ee,previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{}})})}function bundleFileKind(e){return e.replace(/\\/g,`/`).startsWith(`scripts/`)?`script`:`reference`}const INTERNAL_BUNDLE_SKILL_NAMES=new Set(Object.values(BUNDLE_SKILL_NAME));function internalSkillHint(e){return[`"${e}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,`It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.`,"The `skills` tool only covers skills authored as KB content (`.ok/skills` = project, `~/.ok/skills` = global). Built-in `open-knowledge*` skills never appear in either scope."].join(` `)}const SCOPE_FIELD_DESCRIBE="Which level the skill lives at. `project` = this KB's `.ok/skills/` (shared via git with everyone on the project); `global` = your user-level `~/.ok/skills/` (available in every project on this machine, not shared).",SkillListEntryOutputSchema=object$1({name:string().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().optional().describe(`The skill's one-line description (when present).`),installed:boolean().describe(`True when projected into ≥1 editor; false = a Draft.`),hosts:array(string()).describe(`Editor ids the skill is installed into.`),updateAvailable:boolean().optional().describe(`Starter-pack skills only: a newer bundled version is available.`)}),SkillBundleFileEntrySchema=object$1({path:string().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:_enum([`reference`,`script`]).describe("`reference` (under references/) or `script` (under scripts/).")}),SkillReadOutputSchema=object$1({name:string().describe(`Skill name (its identity).`),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().describe(`The skill's one-line description (empty if none).`),body:string().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:array(SkillBundleFileEntrySchema).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),SkillFileReadOutputSchema=object$1({path:string().describe(`Skill-relative path read.`),kind:_enum([`reference`,`script`]).describe("`reference` or `script`."),text:string().describe(`Full text of the bundle file.`)}),DESCRIPTION$2=["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you find and read skills. Skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Covers only skills authored as KB content. OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Three modes:**`,"- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts, and (for starter packs) `updateAvailable`.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
|
|
2009
2006
|
`);function register$2(e,t){e.registerTool(`skills`,{description:DESCRIPTION$2,inputSchema:{name:string().optional().describe(`Omit to LIST all skills; pass a skill name to READ that skill.`),file:string().optional().describe("With `name`: read ONE bundle file by its skill-relative path (`references/...`/`scripts/...`)."),scope:SkillScopeArg.optional(),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({skills:array(SkillListEntryOutputSchema).optional().describe(`Present in LIST mode: every skill across Project + Global levels.`),skill:SkillReadOutputSchema.optional().describe(`Present in READ-skill mode: the named skill (description, body, files list).`),file:SkillFileReadOutputSchema.optional().describe(`Present in READ-file mode: one bundle file (path, kind, text).`)})},async e=>{if(e.name!==void 0&&INTERNAL_BUNDLE_SKILL_NAMES.has(e.name))return textResult(`Error: ${internalSkillHint(e.name)}`,!0);let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.file!==void 0&&e.name===void 0)return textResult('Error: `file` reads ONE bundle file of a skill — pass `name` too: skills({ name, file: "references/x.md" }).',!0);if(e.file!==void 0){let t=resolveSkillFilePath(e.file);if(!t.ok)return textResult(`Error: ${t.error}`,!0)}if(e.name===void 0){let e=await httpGet(g,`/api/skills`);if(!e.ok)return textResult(`Error: ${e.error}`,!0);let{ok:t,...s}=e,S=(Array.isArray(s.skills)?s.skills:[]).map(e=>({name:e.name,scope:e.scope,...typeof e.description==`string`?{description:e.description}:{},installed:e.installed===!0,hosts:Array.isArray(e.hosts)?e.hosts:[],...typeof e.updateAvailable==`boolean`?{updateAvailable:e.updateAvailable}:{}}));return textPlusStructured(JSON.stringify({skills:S},null,2),{skills:S})}let S=e.scope;if(S===void 0){let t=await httpGet(g,`/api/skills`);if(!t.ok)return textResult(`Error: ${t.error}`,!0);let{ok:s,...w}=t,E=(Array.isArray(w.skills)?w.skills:[]).filter(t=>t.name===e.name);if(E.length===0)return textResult(`Error: no skill named "${e.name}" (Project or Global).`,!0);S=E.find(e=>e.scope===`project`)===void 0?E[0]?.scope:`project`}if(e.file!==void 0){let t=await readSkillFile(g,S,e.name,e.file);if(!t.ok)return textResult(`Error: ${t.error}`,!0);let s={path:t.path,kind:t.kind,text:t.text};return textPlusStructured(JSON.stringify({file:s},null,2),{file:s})}let w=await fetchSkill(g,S,e.name);if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E={name:e.name,scope:S,description:w.description,body:w.body,files:w.files.map(e=>({path:e.path,kind:bundleFileKind(e.path)}))};return textPlusStructured(JSON.stringify({skill:E},null,2),{skill:E})})}function buildConsolidateBody(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.
|
|
2010
2007
|
|
|
2011
2008
|
Topic: ${e}
|
|
@@ -2269,6 +2266,11 @@ For **each** folder the user marked \`[KB]\`:
|
|
|
2269
2266
|
5. **Propose folder frontmatter + template.** One \`write\`/\`edit\` call per target:
|
|
2270
2267
|
|
|
2271
2268
|
\`\`\`ts
|
|
2269
|
+
// Folder frontmatter → writes <folder>/.ok/frontmatter.yml.
|
|
2270
|
+
// Open-shape (any key, like a doc's); here the conventional
|
|
2271
|
+
// title/description/tags describing the FOLDER. Self-only — does NOT
|
|
2272
|
+
// cascade into child docs. Use \`write({ folder })\` for a new folder,
|
|
2273
|
+
// \`edit({ folder })\` to add keys to an existing one (merge-patch).
|
|
2272
2274
|
edit({
|
|
2273
2275
|
folder: {
|
|
2274
2276
|
path: '<folder>',
|
|
@@ -2280,6 +2282,9 @@ For **each** folder the user marked \`[KB]\`:
|
|
|
2280
2282
|
},
|
|
2281
2283
|
})
|
|
2282
2284
|
|
|
2285
|
+
// Template → writes <folder>/.ok/templates/<name>.md. This is where
|
|
2286
|
+
// recurring per-doc starting values live (status, owner, …) — bake them
|
|
2287
|
+
// into the template body's frontmatter region so new docs start with them.
|
|
2283
2288
|
write({
|
|
2284
2289
|
template: {
|
|
2285
2290
|
path: '<folder>/<inferred-name>', // e.g., 'specs/SPEC', 'reports/REPORT'
|
|
@@ -3230,31 +3235,22 @@ Incremental by default — don't re-read the whole repo.
|
|
|
3230
3235
|
- **Empty / unreadable repo** (no source detected in Phase 1) → tell the user there's nothing to document yet. Exit.
|
|
3231
3236
|
`}const DESCRIPTION$1=["Procedural guides for the three-layer wiki workflow + brownfield onboarding. Returns a numbered plan (instructional text, not data) — you execute it. Dispatches on `kind`:",``,'- `kind: "ingest"` — capture an external source (URL or local file) into the KB as raw, verbatim reference material (no analysis). Requires `source`.','- `kind: "research"` — gather sources and write provisional findings for a question. Requires `topic`.','- `kind: "consolidate"` — fold provisional material into a canonical article. Requires `topic`.','- `kind: "discover"` — extract conventions from an existing repo (folder frontmatter + templates + link graph). No payload.','- `kind: "wiki"` — generate (or refresh) a navigable, diagram-rich, source-grounded wiki of this codebase into the `wiki/` knowledge base (the `codebase-wiki` pack). No payload; tune via natural-language `audience`/`depth` in your request.',``,`**Parameters:**`,"- `kind` — `ingest` | `research` | `consolidate` | `discover` | `wiki`.","- `source` — Required for `ingest`: the URL / file path / identifier to capture.","- `topic` — Required for `research` / `consolidate`: the topic, question, or anchor URL.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
3232
3237
|
`);function register$1(e,t){let s=buildWorkflowHandler(`ingest`,t,`source`,buildIngestBody),g=buildWorkflowHandler(`research`,t,`topic`,buildResearchBody),S=buildWorkflowHandler(`consolidate`,t,`topic`,buildConsolidateBody);e.registerTool(`workflow`,{description:DESCRIPTION$1,inputSchema:{kind:_enum([`ingest`,`research`,`consolidate`,`discover`,`wiki`]).describe(`Which workflow guide to return.`),source:string().optional().describe('Required for `kind: "ingest"` — the URL / file / identifier to capture.'),topic:string().optional().describe('Required for `kind: "research"` / `"consolidate"` — the topic / question / anchor URL.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({previewUrl:previewUrlOutputField.describe(`Always null — a workflow guide is prose, not a previewable document.`)})},async e=>{switch(e.kind){case`ingest`:return e.source?s(e):textResult('Error: workflow({ kind: "ingest" }) requires `source` — the URL / file / identifier to capture. e.g. workflow({ kind: "ingest", source: "https://example.com/spec" }).',!0);case`research`:return e.topic?g(e):textResult('Error: workflow({ kind: "research" }) requires `topic` — the question or topic to investigate. e.g. workflow({ kind: "research", topic: "rate-limit strategies" }).',!0);case`consolidate`:return e.topic?S(e):textResult('Error: workflow({ kind: "consolidate" }) requires `topic` — the topic to fold into a canonical article. e.g. workflow({ kind: "consolidate", topic: "rate-limit strategies" }).',!0);case`discover`:{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)}case`wiki`:{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildWikiBody(s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)}default:return textResult(`Error: unknown workflow kind.`,!0)}})}const DESCRIPTION=`${["Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).",``,'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.','- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.','- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.','- `skill` — Create or overwrite an agent SKILL (`.ok/skills/<name>/SKILL.md`): reusable agent guidance you author in OK and `install` into your editors. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.','- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',"- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.","- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.",``,"Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit)."].join(`
|
|
3233
|
-
`)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function composeWithFrontmatter(e,t){let{frontmatter:s,body:g}=stripFrontmatter(t),S={};if(s!==``){let e=parseFrontmatterYaml(unwrapFrontmatterFences(s));if(e.map===null)return{ok:!1,error:`EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${e.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`};S=e.map}let w=serializeFrontmatterMap(mergePatch(S,e));return w===``?{ok:!0,markdown:g}:{ok:!0,markdown:withFences(w)+g}}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.path);if(!w.ok)return{docName:e.path,ok:!1,error:okReservedPathRedirect(e.path)??w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:E,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let O=e.content??``,k=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,j=docExtensionOnDisk(s,E)??null,F=j!==null,L=e.extension??requestedDocExtension(e.path),B;if(e.position!==void 0)B=e.position;else if(F)return{docName:E,ok:!1,error:`"${E}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else B=`replace`;if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}O=applySubstitution(instantiateDoc(w),{date:todayIsoUtc(),user:D?.displayName??``}),B=`replace`}else if(k){let t=composeWithFrontmatter(e.frontmatter,O);if(!t.ok)return{docName:E,ok:!1,error:t.error};O=t.markdown,B=`replace`}if(!F&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty — provide non-empty content to create the document.`};let
|
|
3238
|
+
`)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function composeWithFrontmatter(e,t){let{frontmatter:s,body:g}=stripFrontmatter(t),S={};if(s!==``){let e=parseFrontmatterYaml(unwrapFrontmatterFences(s));if(e.map===null)return{ok:!1,error:`EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${e.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`};S=e.map}let w=serializeFrontmatterMap(mergePatch(S,e));return w===``?{ok:!0,markdown:g}:{ok:!0,markdown:withFences(w)+g}}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.path);if(!w.ok)return{docName:e.path,ok:!1,error:okReservedPathRedirect(e.path)??w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:E,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let O=e.content??``,k=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,j=docExtensionOnDisk(s,E)??null,F=j!==null,L=e.extension??requestedDocExtension(e.path),B;if(e.position!==void 0)B=e.position;else if(F)return{docName:E,ok:!1,error:`"${E}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else B=`replace`;let H;if(e.template===void 0&&!F){let e=resolveTemplatesAvailable(t,parentFolderOf(E),{depth:1});e.length>0&&(H=e.map(e=>({name:e.name,...e.description?{description:e.description}:{}})))}if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}O=applySubstitution(instantiateDoc(w),{date:todayIsoUtc(),user:D?.displayName??``}),B=`replace`}else if(k){let t=composeWithFrontmatter(e.frontmatter,O);if(!t.ok)return{docName:E,ok:!1,error:t.error};O=t.markdown,B=`replace`}if(!F&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty — provide non-empty content to create the document.`};let q=await httpPost(g,`/api/agent-write-md`,{docName:E,markdown:O,position:B,...L!==null&&!F?{extension:L}:{},...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(D)});if(!q.ok){let e=typeof q.detail==`string`&&q.detail.length>0?q.detail:``;return{docName:E,ok:!1,error:e?`${String(q.error)} (${e})`:String(q.error)}}if(e.template!==void 0&&k){let t=await httpPost(g,`/api/frontmatter-patch`,{docName:E,patch:e.frontmatter,...agentIdentityFields(D)});if(!t.ok)return{docName:E,ok:!1,error:`document created from template but frontmatter failed: ${String(t.error)}`}}let ee=extensionIgnoredNote(L,j,E);return{docName:E,ok:!0,position:B,...e.template===void 0?{}:{fromTemplate:e.template},...ee?{extensionNote:ee}:{},...H?{templateHint:H}:{},raw:q}}function formatTemplateHintLine(e){return`ℹ This folder has templates you can start from: ${e.map(e=>e.description?`${e.name} (${e.description})`:e.name).join(`, `)}. Pass \`template: "${e[0]?.name??``}"\` next time to match the folder's shape (the doc still landed).`}async function handleFolder(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=g.identityRef?.current,w=await httpPost(s,`/api/create-folder`,{path:e.path,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!w.ok){let e=typeof w.detail==`string`&&w.detail.length>0?w.detail:``;return textResult(e?`Error: ${w.error} (${e})`:`Error: ${w.error}`,!0)}let E=[`Created folder ${e.path}.`];if(e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0){let g=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!g.ok)return textPlusStructured(`Created folder ${e.path}, but writing its properties failed: ${g.error}. Use edit({ folder: { path: "${e.path}", frontmatter } }) to retry the properties.`,{folder:{ok:!0,path:e.path,frontmatterError:String(g.error)}});E.push(`Set folder properties (${e.path}/.ok/frontmatter.yml).`)}return textPlusStructured(E.join(`
|
|
3234
3239
|
`),{folder:{ok:!0,path:e.path}})}async function handleTemplate(e,t,s,g){let S=resolveTemplatePath(e.path);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{folder:w,name:E}=S;if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=await httpPut(s,`/api/template`,{folder:w,name:E,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.created===!0,k=typeof D.path==`string`?D.path:void 0;return textPlusStructured(`${O?`Created`:`Updated`} template "${E}" in ${w||`(root)`}${k?` (${k})`:``}.`,{template:{ok:!0,path:k,created:O}})}async function handleAsset(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.content===void 0==(e.source===void 0))return textResult("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let S;try{S=e.content===void 0?readFileSync(resolve(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return textResult(`Error: could not read asset bytes: ${e.message}`,!0)}if(S.byteLength===0)return textResult(`Error: asset is empty (0 bytes).`,!0);let{folder:w,name:E}=splitTargetPath(e.path),D=w?`${w}/${E}`:E,O=g.identityRef?.current,k=new URLSearchParams;O?.connectionId&&k.set(`agentId`,O.connectionId),O?.displayName&&k.set(`agentName`,O.displayName);let j=k.toString(),F=new FormData;F.append(`parentDocName`,D),F.append(`file`,new Blob([new Uint8Array(S)]),E);let L;try{let e=await fetch(`${s}/api/upload${j?`?${j}`:``}`,{method:`POST`,body:F}),t=await e.json().catch(()=>null);L=e.ok?{ok:!0,status:e.status,data:t??{}}:{ok:!1,status:e.status,error:t&&(typeof t.title==`string`?t.title:t.error)||`Upload failed (HTTP ${e.status}).`}}catch(e){return textResult(`Error: upload request failed: ${e.message}`,!0)}if(!L.ok)return textResult(`Error: ${L.error}`,!0);let B=typeof L.data?.src==`string`?L.data.src:void 0,H=typeof L.data?.path==`string`?L.data.path:void 0,q=L.data?.deduped===!0,ee=B??H??E;return textPlusStructured([`Uploaded asset to ${D}${q?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: `].join(`
|
|
3235
3240
|
`),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleSkillWrite(e,t,s,g,S){let w=g.identityRef?.current,E=e.description!==void 0,D=e.files??[];if(!E&&D.length===0)return textResult("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!E)return textResult('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);for(let e of D){let t=resolveSkillFilePath(e.path);if(!t.ok)return textResult(`Error: ${t.error}`,!0)}let O=[],k=null;if(E&&(k=await writeSkill(s,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:w,lockDir:S}),k.isError))return k;for(let g of D){let S=await writeSkillFile(s,{name:e.name,scope:e.scope,path:g.path,content:g.content,summary:t,identity:w}),E=S.structuredContent;if(S.isError)O.push({path:g.path,ok:!1,error:S.content[0]?.text??`write failed`});else{let e=E?.skill?.file??{};O.push({path:g.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let j=O.filter(e=>e.ok).length,F=O.some(e=>!e.ok),L=k?.structuredContent??{},B=L.skill??{ok:!0},H={...L,skill:{...B,...D.length>0?{files:O}:{}}},q=[];if(E&&k&&q.push(k.content[0]?.text??``),D.length>0){q.push(`${j}/${D.length} bundle file(s) written.`);for(let e of O)q.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return textPlusStructured(q.filter(Boolean).join(`
|
|
3236
|
-
`),H,F)}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseAdvisoryWarnings(e.raw.warnings),g=parseBrokenLinks(e.raw.brokenLinks);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{warnings:s}:{},brokenLinks:g}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=[`Wrote ${e.path} (${s.position}).`];if(g?.ok&&g.warnings&&S.push(...formatAdvisoryBriefs(g.warnings)),g?.ok){let e=formatBrokenLinkBrief(g.brokenLinks);e&&S.push(e)}return S.join(` `)}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
|
|
3237
|
-
`),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,F=Array.isArray(O.hints)?O.hints:void 0,L=O.summary&&typeof O.summary==`object`?O.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H=parseAdvisoryWarnings(O.warnings),q=parseBrokenLinks(O.brokenLinks),ee=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],J=frontmatterIgnoredNote(D.position,e.content);if(J&&ee.push(J),D.extensionNote&&ee.push(D.extensionNote),j&&!k&&ee.push(START_UI_TEXT_HINT),B&&ee.push(B),F)for(let e of F)e.message&&ee.push(e.message);H&&ee.push(...formatAdvisoryLines(H)),ee.push(...formatBrokenLinkLines(q));let Y=ee.join(`
|
|
3238
|
-
`),te={brokenLinks:q};return F&&(te.hints=F),L&&(te.summary=L),H&&(te.warnings=H),textPlusStructured(Y,nestDocResult(k,j?buildPreviewAttachWarning(k,E):void 0,te))}function register(e,t){let s={path:string().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:DocExtensionArg.optional(),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:object$1({name:string().describe(SKILL_NAME_DESCRIBE),description:string().optional().describe(`${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:string().optional().describe(SKILL_BODY_DESCRIBE),files:array(object$1({path:string().describe("Skill-relative path under `references/` or `scripts/`."),content:string().describe(`Full text of the bundle file.`)})).optional().describe(SKILL_FILES_DESCRIBE),scope:SkillScopeArg.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (`.ok/skills/<name>/`). SKILL.md is authored via `description`+`body`; `references/**` and `scripts/**` via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:object$1({ok:boolean(),path:string().optional(),created:boolean().optional().describe(`true if created, false if an existing skill was overwritten.`),files:looseObjectArray.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},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:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?handleAsset(e.asset,g,w,t):handleSkillWrite(e.skill,e.summary,w,t,E):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$13(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$4(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$15(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$10(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`install`),identityRef:t.identityRef}),register$11(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`skills`)}),register$18(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$7(g,{resolveCwd:S(`palette`),config:t.config}),register$17(g,{config:t.config,resolveCwd:S(`config`)}),register$12(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl,isDesktopTerminal:t.isDesktopTerminal,...t.serverUrl?{ensureSingleFileSession:createEnsureSingleFileSession()}:{}}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$6(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$3(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}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 g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID$1(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID$1(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(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:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=new Set,J=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=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}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`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(w?.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`} ${w}`})}).catch(e=>{S.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}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} 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()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));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 ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),J)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.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}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.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)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of ee)try{e.destroy()}catch{}ee.clear();for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}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`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`OpenKnowledge 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:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.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:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)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 E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&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(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=toPosix(relative(g,join(s,e.file)));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set(`node_modules,.venv,venv,env,__pycache__,vendor,dist,build,out,output,.next,.nuxt,.svelte-kit,.astro,.turbo,.cache,.parcel-cache,coverage,.git,.ok,.open-knowledge,.openknowledge,.claude,.cursor,.codex,.agents,.opencode,Library,Applications,.Trash`.split(`,`)),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}function isSkillContentFile(e){return e.startsWith(`${SKILL_CONTENT_ROOT}/`)}function isSkillContentAncestorDir(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}function globBlocksSkillContent(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).trim();return t===`.ok`||t===`.ok/**`||t===`**/.ok`||t===`**/.ok/**`}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){return isReservedForUserTree(stripDocExtension(e))}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3241
|
+
`),H,F)}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseAdvisoryWarnings(e.raw.warnings),g=parseBrokenLinks(e.raw.brokenLinks);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{warnings:s}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:g}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=[`Wrote ${e.path} (${s.position}).`];if(g?.ok&&g.warnings&&S.push(...formatAdvisoryBriefs(g.warnings)),g?.ok){let e=formatBrokenLinkBrief(g.brokenLinks);e&&S.push(e)}return s.ok&&s.templateHint&&S.push(`ℹ ${s.templateHint.length} template${s.templateHint.length===1?``:`s`} available here (pass \`template\`).`),S.join(` `)}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
|
|
3242
|
+
`),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,F=Array.isArray(O.hints)?O.hints:void 0,L=O.summary&&typeof O.summary==`object`?O.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H=parseAdvisoryWarnings(O.warnings),q=parseBrokenLinks(O.brokenLinks),ee=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],J=frontmatterIgnoredNote(D.position,e.content);if(J&&ee.push(J),D.extensionNote&&ee.push(D.extensionNote),j&&!k&&ee.push(START_UI_TEXT_HINT),B&&ee.push(B),F)for(let e of F)e.message&&ee.push(e.message);H&&ee.push(...formatAdvisoryLines(H)),ee.push(...formatBrokenLinkLines(q)),D.templateHint&&ee.push(formatTemplateHintLine(D.templateHint));let Y=ee.join(`
|
|
3243
|
+
`),te={brokenLinks:q};return F&&(te.hints=F),L&&(te.summary=L),H&&(te.warnings=H),D.templateHint&&(te.templateHint=D.templateHint),textPlusStructured(Y,nestDocResult(k,j?buildPreviewAttachWarning(k,E):void 0,te))}function register(e,t){let s={path:string().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:DocExtensionArg.optional(),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:object$1({name:string().describe(SKILL_NAME_DESCRIBE),description:string().optional().describe(`${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:string().optional().describe(SKILL_BODY_DESCRIBE),files:array(object$1({path:string().describe("Skill-relative path under `references/` or `scripts/`."),content:string().describe(`Full text of the bundle file.`)})).optional().describe(SKILL_FILES_DESCRIBE),scope:SkillScopeArg.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (`.ok/skills/<name>/`). SKILL.md is authored via `description`+`body`; `references/**` and `scripts/**` via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:object$1({ok:boolean(),path:string().optional(),created:boolean().optional().describe(`true if created, false if an existing skill was overwritten.`),files:looseObjectArray.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},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:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?handleAsset(e.asset,g,w,t):handleSkillWrite(e.skill,e.summary,w,t,E):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$13(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$4(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$15(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$10(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`install`),identityRef:t.identityRef}),register$11(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`skills`)}),register$18(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$7(g,{resolveCwd:S(`palette`),config:t.config}),register$17(g,{config:t.config,resolveCwd:S(`config`)}),register$12(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl,isDesktopTerminal:t.isDesktopTerminal,...t.serverUrl?{ensureSingleFileSession:createEnsureSingleFileSession()}:{}}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$6(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$3(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}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 g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(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:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=new Set,J=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=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}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`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(w?.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`} ${w}`})}).catch(e=>{S.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}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} 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()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));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 ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),J)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.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}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.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)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of ee)try{e.destroy()}catch{}ee.clear();for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}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`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`OpenKnowledge 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:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.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:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)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 E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&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(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=toPosix(relative(g,join(s,e.file)));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set(`node_modules,.venv,venv,env,__pycache__,vendor,dist,build,out,output,.next,.nuxt,.svelte-kit,.astro,.turbo,.cache,.parcel-cache,coverage,.git,.ok,.open-knowledge,.openknowledge,.claude,.cursor,.codex,.agents,.opencode,Library,Applications,.Trash`.split(`,`)),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}function isSkillContentFile(e){return e.startsWith(`${SKILL_CONTENT_ROOT}/`)}function isSkillContentAncestorDir(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}function globBlocksSkillContent(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).trim();return t===`.ok`||t===`.ok/**`||t===`**/.ok`||t===`**/.ok/**`}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){return isReservedForUserTree(stripDocExtension(e))}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3239
3244
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){let s=e.startsWith(`!`),g=s?e.slice(1):e,S=g.startsWith(`/`)?g.slice(1):g,w=S.endsWith(`/`)?S.slice(0,-1):S,E=g.startsWith(`/`)||w.includes(`/`)?`${t}/${S}`:`${t}/**/${S}`;return s?`!${E}`:E}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=toPosix(relative(t,S));if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=toPosix(relative(s,t));if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){return isReservedForUserTree(stripDocExtension(e))}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}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`),g=t.slice(5),S=s.split(`
|
|
3240
3245
|
`).find(e=>e.endsWith(` ${g}`));if(S)return S.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}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-D1eNAlbX.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}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:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isLinkIndexExcludedDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const log$4=getLogger(`shadow-gc`),GC_GRACE_PERIOD_MS=1440*60*1e3,SESSION_WRITER_TTL_MS=720*60*60*1e3;function extractBranchNames(e){let t=new Set;for(let s of e){let e=s.replace(/^refs\/wip\//,``),g=e.lastIndexOf(`/`);if(g<=0)continue;let S=e.slice(0,g);parseWriterId(e.slice(g+1)).classification!==`unknown`&&t.add(S)}return t}async function getProjectBranchSha(e,t){try{return(await esm_default().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function listProjectBranches(e){let t=new Set;try{let s=(await esm_default().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(s)for(let e of s.split(`
|
|
3241
3246
|
`))e&&t.add(e)}catch(e){log$4.warn({err:e},`[shadow-gc] listProjectBranches failed; treating as no project branches`)}return t}async function gcShadowBranches(e,t,s=DEFAULT_CHECKPOINT_RETENTION,g=`.`){let S={deletedBranches:[],renamedBranches:[],retainedBranches:[],checkpointGc:{},deletedStaleSessionRefs:0},w=shadowGit(e,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),E;try{E=(await w.raw(`for-each-ref`,`refs/wip/`,`--format=%(refname)`)).trim()}catch{return S}if(!E)return S;let D=E.split(`
|
|
3242
3247
|
`).filter(Boolean),O=extractBranchNames(D),k=await listProjectBranches(t),j=[];for(let e of O)e.startsWith(`detached-`)||(k.has(e)?S.retainedBranches.push(e):j.push(e));if(j.length!==0){let e=new Set;for(let t of k)O.has(t)||e.add(t);for(let s of j){let g=!1;if(e.size>0){let E=null;for(let e of D)if(e.startsWith(`refs/wip/${s}/`))try{E=(await w.raw(`rev-parse`,e)).trim();break}catch{}if(E){for(let O of e)if(await getProjectBranchSha(t,O)===E){let t=D.filter(e=>e.startsWith(`refs/wip/${s}/`));for(let e of t){let t=`refs/wip/${O}/${e.slice(`refs/wip/${s}/`.length)}`;try{let s=(await w.raw(`rev-parse`,e)).trim();await w.raw(`update-ref`,t,s),await w.raw(`update-ref`,`-d`,e)}catch(s){log$4.error({err:s,oldRef:e,newRef:t},`[shadow-gc] failed to migrate WIP ref`)}}S.renamedBranches.push({from:s,to:O}),e.delete(O),g=!0;break}}}if(!g){let e=D.filter(e=>e.startsWith(`refs/wip/${s}/`));for(let t of e)try{let e=(await w.raw(`log`,`-1`,`--format=%ci`,t)).trim(),g=new Date(e).getTime();if(Date.now()-g<GC_GRACE_PERIOD_MS){S.retainedBranches.push(s);break}await w.raw(`update-ref`,`-d`,t)}catch{}S.retainedBranches.includes(s)||S.deletedBranches.push(s)}}}let F=new Set([...k,...S.retainedBranches]);for(let t of F)try{let g=await gcCheckpointRefs(e,t,s);(g.scanned>0||g.deletedBridgeMergeLoss>0||g.deletedExternalChangeRescue>0||g.deletedAutoConsolidation>0)&&(S.checkpointGc[t]={scanned:g.scanned,deletedBridgeMergeLoss:g.deletedBridgeMergeLoss,deletedExternalChangeRescue:g.deletedExternalChangeRescue,deletedAutoConsolidation:g.deletedAutoConsolidation,retained:g.retained})}catch(e){log$4.warn({err:e,branch:t},`[shadow-gc] checkpoint GC failed`)}try{await gcRenameLog(e,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$4.warn({err:e},`[shadow-gc] rename-log GC failed`)}let L=Date.now();for(let t of k){let s=await enumerateWipChains(e,t),w=[];for(let e of s)if(!(e.classification===`classified-file-system`||e.classification===`classified-git-upstream`||e.classification===`classified-openknowledge-service`)){if(e.classification===`unknown`){log$4.warn({branch:t,writerId:e.writerId},`[shadow-gc] unknown writer id in active branch ref — preserved`);continue}if(e.classification===`agent`||e.classification===`principal`){if(e.isPark)continue;e.committedAtMs>0&&L-e.committedAtMs>=SESSION_WRITER_TTL_MS&&w.push({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})}}if(w.length>0)try{await saveVersion(e,g,w,t,void 0,{checkpointKind:{foldedRefs:w.length,trigger:`ttl`},includeUpstream:!1,timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),S.deletedStaleSessionRefs+=w.length}catch(e){log$4.warn({err:e,branch:t},`[shadow-gc] TTL consolidation failed`)}}return S}let _runDuration=null,_gcLatch=null,_consolidation=null;function runDurationHist(){return _runDuration||=getMeter().createHistogram(`ok.shadow.maintenance.run_duration_ms`,{description:`Wall-clock duration of one maintenance op. Bounded labels: op ∈ {gc, consolidation, reap}, outcome ∈ {ok, skipped, error}.`,unit:`ms`}),_runDuration}function gcLatchCounter(){return _gcLatch||=getMeter().createCounter(`ok.shadow.maintenance.gc_latch_total`,{description:`Distinct gc.log latch EPISODES (counted on the absent→present transition, not per observation, so one persistent ~1-day latch counts once). A latch means auto-gc is silently disabled until it self-expires; a nonzero rate means a repo is re-degrading invisibly.`}),_gcLatch}function consolidationCounter(){return _consolidation||=getMeter().createCounter(`ok.shadow.maintenance.consolidation_total`,{description:`Auto-consolidation runs that folded ≥1 dead chain. Bounded label: trigger ∈ {dead-chain, session-close, boot, ttl}. Width before/after ride the structured log, not metric labels.`}),_consolidation}function recordMaintenanceRun(e,t,s){runDurationHist().record(Math.max(0,s),{op:e,outcome:t})}function recordGcLatch(){gcLatchCounter().add(1)}function recordConsolidation(e){consolidationCounter().add(1,{trigger:e})}async function countShadowObjects(e){let t=await shadowGit(e).raw(`count-objects`,`-v`),s=new Map;for(let e of t.split(`
|
|
3243
3248
|
`)){let t=e.indexOf(`:`);if(t<0)continue;let g=e.slice(0,t).trim(),S=Number.parseInt(e.slice(t+1).trim(),10);g&&s.set(g,Number.isFinite(S)?S:0)}return{looseObjects:s.get(`count`)??0,looseKiB:s.get(`size`)??0,packfiles:s.get(`packs`)??0,packedObjects:s.get(`in-pack`)??0}}function hasGcLogLatch(e){return existsSync(resolve(e.gitDir,`gc.log`))}async function countWipRefs(e,t){let s=shadowGit(e),g=t?`refs/wip/${t}/`:`refs/wip/`;try{return(await s.raw(`for-each-ref`,`--format=%(refname)`,g)).trim().split(`
|
|
3244
3249
|
`).filter(Boolean).length}catch{return 0}}async function countStaleAgentWipRefs(e,t){let s=shadowGit(e),g;try{g=(await s.raw(`for-each-ref`,`--format=%(refname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/`)).trim().split(`
|
|
3245
|
-
`).filter(Boolean)}catch{return 0}let S=0;for(let e of g){let[s=``,g=``,w=``]=e.split(`\0`);if(w.startsWith(`park:`))continue;let E=s.split(`/`).slice(3).join(`/`);if(!E||parseWriterId(E).classification!==`agent`)continue;let D=Number.parseInt(g,10);Number.isFinite(D)&&D*1e3<t&&(S+=1)}return S}const log$3=getLogger(`shadow-maintenance`),DEAD_CHAIN_THRESHOLD=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),CONSOLIDATION_MIN_SPACING_MS=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function isMaintenanceDisabled(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function consolidationTriggerLabel(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var MaintenanceCoordinator=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){isMaintenanceDisabled()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(isMaintenanceDisabled()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),s,g=new Promise(t=>{s=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),g]),s&&clearTimeout(s),t.catch(e=>{log$3.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let s=performance.now();try{await gcShadowBranches(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),recordMaintenanceRun(`reap`,`ok`,performance.now()-s)}catch(t){recordMaintenanceRun(`reap`,`error`,performance.now()-s),log$3.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(isMaintenanceDisabled()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:s}=this.deps;if(!t||!s)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<CONSOLIDATION_MIN_SPACING_MS)return{consolidated:!1,skipped:`spacing`};let g=this.deps.getShadow();if(!g)return{consolidated:!1,skipped:`no-shadow`};try{let S=t()??`main`,w=await this.findDeadAgentChains(g,S,s);if(w.length<DEAD_CHAIN_THRESHOLD)return{consolidated:!1,skipped:`below-threshold`,deadChains:w.length};let E=await countWipRefs(g,S);await saveVersion(g,this.deps.contentRoot??``,w,S,void 0,{checkpointKind:{foldedRefs:w.length,trigger:consolidationTriggerLabel(e)},timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),this.lastConsolidationAt=Date.now();let D=await countWipRefs(g,S);return recordConsolidation(consolidationTriggerLabel(e)),log$3.info({trigger:e,branch:S,foldedChains:w.length,widthBefore:E,widthAfter:D},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:w.length,widthBefore:E,widthAfter:D}}catch(t){return log$3.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,s){return(await enumerateWipChains(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!s(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(isMaintenanceDisabled())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return recordMaintenanceRun(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();if(!t)return{ran:!1,skipped:`no-shadow`};let s=performance.now();try{let g=await countShadowObjects(t);await shadowGit(t,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}).raw(`gc`,`--auto`);let S=await countShadowObjects(t),w=hasGcLogLatch(t),E=performance.now()-s;return recordMaintenanceRun(`gc`,`ok`,E),w&&(this.lastGcLatch||recordGcLatch(),log$3.warn({trigger:e,looseObjects:S.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=w,log$3.info({trigger:e,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfiles:S.packfiles,durationMs:Math.round(E)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfilesAfter:S.packfiles,latch:w,durationMs:E}}catch(t){return recordMaintenanceRun(`gc`,`error`,performance.now()-s),log$3.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function createMaintenanceCoordinator(e){return new MaintenanceCoordinator(e)}const SKILL_WATCH_OPTIONS={depth:1,acceptLeaf:e=>basename(e)===`SKILL.md`},TEMPLATE_WATCH_OPTIONS={depth:0,acceptLeaf:e=>basename(e).endsWith(`.md`)};async function startManagedArtifactWatcher(e,t,s=SKILL_WATCH_OPTIONS){let g=getLogger(`managed-artifact-watcher`),{watch:S}=await import(`./chokidar-D1eNAlbX.mjs`),w=Array.from(new Set(e));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&g.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let E=S(w,{ignoreInitial:!0,depth:s.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{E.once(`ready`,e)});let D=new Map,O=e=>{if(!s.acceptLeaf(e))return;let S;try{S=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}g.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(S!==D.get(e)){D.set(e,S);try{t(e,S)}catch(t){g.warn({err:t,path:e},`managed-artifact change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{s.acceptLeaf(e)&&(D.delete(e),g.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`))}),E.on(`error`,e=>{g.warn({err:e,watchRoots:w},`[managed-artifact-watcher] chokidar error`)});let j=!1;return async()=>{j||(j=!0,await E.close())}}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:g,email:S}=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$1()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID$1()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}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(isReservedForUserTree(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 g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=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:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,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(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),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 g;try{g=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(g))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:g}}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,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[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.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_SUBCLASS_MESSAGES={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},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/i],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=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();if(matchesAny(g,INDEX_LOCK_PATTERNS))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s};if(matchesAny(g,DIRTY_TREE_PATTERNS))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s};if(matchesAny(g,DISK_FULL_PATTERNS))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s};let S=classifyGitAuthError(t);return S.kind===`auth`?S.subclass===`403`&&matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:S.subclass,retryable:!1,message:AUTH_SUBCLASS_MESSAGES[S.subclass],rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{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}}const DEFAULT_TTL_MS=6e4;function createGhTokenSource(e,t={}){let s=t.ttlMs??DEFAULT_TTL_MS,g=t.now??Date.now,S=new Map;return{get(t){if(!e)return null;let w=g(),E=S.get(t);if(E&&E.expiresAt>w)return E.token==null?null:{token:E.token,host:t};let D=e(t),O=D.available&&D.token?D.token:null;return S.set(t,{token:O,expiresAt:w+s}),O==null?null:{token:O,host:t}},invalidate(){S.clear()}}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w);if(k===`anonymous`)return log$2.info({host:g},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`no-collaborator`};let j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i,SYNC_GH_TOKEN_HOST=`github.com`;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}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(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`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;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;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.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.ghTokenSource=createGhTokenSource(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}gitHandle(e){return createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(SYNC_GH_TOKEN_HOST)??void 0})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();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$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.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&&g)try{let e=(await this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
3246
|
-
`).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$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.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$1.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$1.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.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.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$1.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,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.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 this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
|
|
3247
|
-
`).map(e=>e.trim()).filter(Boolean):[]);for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}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$1.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$1.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`||this.state===`auth-error`)){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=this.gitHandle(),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$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);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{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}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,`pull`);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`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=this.gitHandle(s);if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(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$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,S,O])).trim();if(s){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s.split(`
|
|
3248
|
-
`)){let s=t.trim();if(!s)continue;j.push(s);let g=e.get(s)??toPosix(relative(this.contentDir,join(this.projectDir,s)));g&&!g.startsWith(`..`)&&F.push(g)}}}catch{j=t.map(e=>e.projectRelPath).concat(D),F=t.map(e=>e.contentRelPath)}let L=this.buildCommitMessage(F),B=await resolveGitIdentity(this.projectDir),H=B===null;this.identityUnresolved!==H&&(this.identityUnresolved=H,this.cc1Broadcaster?.signal(`sync-status`));let q=B?.name??`OpenKnowledge`,ee=B?.email??`sync@open-knowledge.local`;applyGitEnv(e,{GIT_AUTHOR_NAME:q,GIT_AUTHOR_EMAIL:ee,GIT_COMMITTER_NAME:q,GIT_COMMITTER_EMAIL:ee});let J=(await e.git.raw([`commit-tree`,O,`-p`,S,`-m`,L])).trim();if(!J||!SHA_HEX_40.test(J)){log$1.warn({raw:J},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,J,S]),await this.resetRealIndexForPaths(j);let Y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),Y=!0}catch{}Y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=J}),g&&(this.lastPushedSha=g,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let s=classifyGitError(t instanceof Error?t:Error(String(t)));if(s.class===`semantic`&&s.subclass===`non-fast-forward`){if(e>0){log$1.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}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,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log$1.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(s,`push`)}finally{try{unlinkSync(s)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),s=this.gatherContentFilesSync(),g=await this.listHeadContentPaths(e,t);if(s.length===0&&g.size===0)return null;let S=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),w=this.gitHandle(S);try{await w.git.raw([`read-tree`,t]);let S=100;for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100).map(e=>e.projectRelPath);await w.git.raw([`add`,`--`,...t])}let E=new Set(s.map(e=>e.projectRelPath)),D=[...g].filter(e=>!E.has(e));await this.removePathsFromIndex(w,D);let O=(await w.git.raw([`write-tree`])).trim();if(O===(await w.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let k=[];try{let e=(await w.git.raw([`diff-tree`,`--name-only`,`-r`,t,O])).trim();k=e?e.split(`
|
|
3249
|
-
`).map(e=>e.trim()).filter(Boolean):[]}catch{k=s.map(e=>e.projectRelPath).concat(D)}let j=await resolveGitIdentity(this.projectDir),F=j?.name??`OpenKnowledge`,L=j?.email??`sync@open-knowledge.local`;applyGitEnv(w,{GIT_AUTHOR_NAME:F,GIT_AUTHOR_EMAIL:L,GIT_COMMITTER_NAME:F,GIT_COMMITTER_EMAIL:L});let B=(await w.git.raw([`commit-tree`,O,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!B||!SHA_HEX_40.test(B)?(log$1.warn({raw:B},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,B,t]),await this.resetRealIndexForPaths(k,e),B)}finally{try{unlinkSync(S)}catch{}}}async prepareForMerge(e,t){let s=``;try{s=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch(e){return log$1.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(!s)return{proceed:!0,needsStashPop:!1};let g=s.split(`
|
|
3250
|
-
`).map(e=>e.trim()).filter(Boolean);if(g.length===0)return{proceed:!0,needsStashPop:!1};let S=``;try{S=(await e.git.raw([`diff`,`--name-only`,`HEAD..origin/${t}`])).trim()}catch(e){return log$1.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let w=new Set(S.split(`
|
|
3251
|
-
`).map(e=>e.trim()).filter(Boolean)),E=g.filter(e=>w.has(e));if(E.length>0){let e=E.slice(0,3).join(`, `),t=E.length>3?`, +${E.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:E},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let D=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,D])}catch(e){return log$1.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){log$1.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=s=>{let g;try{g=readdirSync(s,{withFileTypes:!0})}catch{return}for(let S of g){let g=join(s,S.name);if(S.isDirectory()){let e=toPosix(relative(this.contentDir,g));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(g)}else if(S.isFile()){let t=toPosix(relative(this.contentDir,g));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let s=toPosix(relative(this.projectDir,g));e.push({contentRelPath:t,projectRelPath:s})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let s=new Set;try{let g=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,t])).trim();for(let e of g?g.split(`
|
|
3252
|
-
`):[]){let t=e.trim();if(!t)continue;let g=join(this.projectDir,t),S=toPosix(relative(this.contentDir,g));!S.startsWith(`..`)&&!this.contentFilter.isExcluded(S)&&s.add(t)}}catch{}return s}async removePathsFromIndex(e,t){if(t.length===0)return;let s=[...new Set(t)],g=100;for(let t=0;t<s.length;t+=100){let g=s.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...g])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let s=t??this.gitHandle(),g=[...new Set(e)],S=100;for(let e=0;e<g.length;e+=100){let t=g.slice(e,e+100);try{await s.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{let s=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=s?s.split(`
|
|
3253
|
-
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=toPosix(relative(this.contentDir,t));!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
3250
|
+
`).filter(Boolean)}catch{return 0}let S=0;for(let e of g){let[s=``,g=``,w=``]=e.split(`\0`);if(w.startsWith(`park:`))continue;let E=s.split(`/`).slice(3).join(`/`);if(!E||parseWriterId(E).classification!==`agent`)continue;let D=Number.parseInt(g,10);Number.isFinite(D)&&D*1e3<t&&(S+=1)}return S}const log$3=getLogger(`shadow-maintenance`),DEAD_CHAIN_THRESHOLD=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),CONSOLIDATION_MIN_SPACING_MS=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function isMaintenanceDisabled(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function consolidationTriggerLabel(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var MaintenanceCoordinator=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){isMaintenanceDisabled()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(isMaintenanceDisabled()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),s,g=new Promise(t=>{s=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),g]),s&&clearTimeout(s),t.catch(e=>{log$3.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let s=performance.now();try{await gcShadowBranches(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),recordMaintenanceRun(`reap`,`ok`,performance.now()-s)}catch(t){recordMaintenanceRun(`reap`,`error`,performance.now()-s),log$3.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(isMaintenanceDisabled()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:s}=this.deps;if(!t||!s)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<CONSOLIDATION_MIN_SPACING_MS)return{consolidated:!1,skipped:`spacing`};let g=this.deps.getShadow();if(!g)return{consolidated:!1,skipped:`no-shadow`};try{let S=t()??`main`,w=await this.findDeadAgentChains(g,S,s);if(w.length<DEAD_CHAIN_THRESHOLD)return{consolidated:!1,skipped:`below-threshold`,deadChains:w.length};let E=await countWipRefs(g,S);await saveVersion(g,this.deps.contentRoot??``,w,S,void 0,{checkpointKind:{foldedRefs:w.length,trigger:consolidationTriggerLabel(e)},timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),this.lastConsolidationAt=Date.now();let D=await countWipRefs(g,S);return recordConsolidation(consolidationTriggerLabel(e)),log$3.info({trigger:e,branch:S,foldedChains:w.length,widthBefore:E,widthAfter:D},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:w.length,widthBefore:E,widthAfter:D}}catch(t){return log$3.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,s){return(await enumerateWipChains(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!s(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(isMaintenanceDisabled())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return recordMaintenanceRun(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();if(!t)return{ran:!1,skipped:`no-shadow`};let s=performance.now();try{let g=await countShadowObjects(t);await shadowGit(t,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}).raw(`gc`,`--auto`);let S=await countShadowObjects(t),w=hasGcLogLatch(t),E=performance.now()-s;return recordMaintenanceRun(`gc`,`ok`,E),w&&(this.lastGcLatch||recordGcLatch(),log$3.warn({trigger:e,looseObjects:S.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=w,log$3.info({trigger:e,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfiles:S.packfiles,durationMs:Math.round(E)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfilesAfter:S.packfiles,latch:w,durationMs:E}}catch(t){return recordMaintenanceRun(`gc`,`error`,performance.now()-s),log$3.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function createMaintenanceCoordinator(e){return new MaintenanceCoordinator(e)}const SKILL_WATCH_OPTIONS={depth:1,acceptLeaf:e=>basename(e)===`SKILL.md`},TEMPLATE_WATCH_OPTIONS={depth:0,acceptLeaf:e=>basename(e).endsWith(`.md`)};async function startManagedArtifactWatcher(e,t,s=SKILL_WATCH_OPTIONS){let g=getLogger(`managed-artifact-watcher`),{watch:S}=await import(`./chokidar-D1eNAlbX.mjs`),w=Array.from(new Set(e));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&g.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let E=S(w,{ignoreInitial:!0,depth:s.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{E.once(`ready`,e)});let D=new Map,O=e=>{if(!s.acceptLeaf(e))return;let S;try{S=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}g.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(S!==D.get(e)){D.set(e,S);try{t(e,S)}catch(t){g.warn({err:t,path:e},`managed-artifact change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{s.acceptLeaf(e)&&(D.delete(e),g.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`))}),E.on(`error`,e=>{g.warn({err:e,watchRoots:w},`[managed-artifact-watcher] chokidar error`)});let j=!1;return async()=>{j||(j=!0,await E.close())}}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:g,email:S}=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()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}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(isReservedForUserTree(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 g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=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:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,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(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),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 g;try{g=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(g))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:g}}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,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[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.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_SUBCLASS_MESSAGES={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},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/i],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=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();if(matchesAny(g,INDEX_LOCK_PATTERNS))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s};if(matchesAny(g,DIRTY_TREE_PATTERNS))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s};if(matchesAny(g,DISK_FULL_PATTERNS))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s};let S=classifyGitAuthError(t);return S.kind===`auth`?S.subclass===`403`&&matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:S.subclass,retryable:!1,message:AUTH_SUBCLASS_MESSAGES[S.subclass],rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{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}}const DEFAULT_TTL_MS=6e4;function createGhTokenSource(e,t={}){let s=t.ttlMs??DEFAULT_TTL_MS,g=t.now??Date.now,S=new Map;return{get(t){if(!e)return null;let w=g(),E=S.get(t);if(E&&E.expiresAt>w)return E.token==null?null:{token:E.token,host:t};let D=e(t),O=D.available&&D.token?D.token:null;return S.set(t,{token:O,expiresAt:w+s}),O==null?null:{token:O,host:t}},invalidate(){S.clear()}}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w);if(k===`anonymous`)return log$2.info({host:g},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`no-collaborator`};let j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i,SYNC_GH_TOKEN_HOST=`github.com`;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}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(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`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;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;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.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.ghTokenSource=createGhTokenSource(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}gitHandle(e){return createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(SYNC_GH_TOKEN_HOST)??void 0})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();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$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.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&&g)try{let e=await this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]),t=new Set(splitNulSeparatedPaths(e)),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$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.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$1.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$1.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.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.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$1.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,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.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 this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=await this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]),s=new Set(splitNulSeparatedPaths(t));for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}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$1.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$1.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`||this.state===`auth-error`)){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=this.gitHandle(),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$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);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{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}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,`pull`);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`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=this.gitHandle(s);if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(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$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=splitNulSeparatedPaths(await e.git.raw([`diff-tree`,`--name-only`,`-z`,`-r`,S,O]));if(s.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s){j.push(t);let s=e.get(t)??toPosix(relative(this.contentDir,join(this.projectDir,t)));s&&!s.startsWith(`..`)&&F.push(s)}}}catch{j=t.map(e=>e.projectRelPath).concat(D),F=t.map(e=>e.contentRelPath)}let L=this.buildCommitMessage(F),B=await resolveGitIdentity(this.projectDir),H=B===null;this.identityUnresolved!==H&&(this.identityUnresolved=H,this.cc1Broadcaster?.signal(`sync-status`));let q=B?.name??`OpenKnowledge`,ee=B?.email??`sync@open-knowledge.local`;applyGitEnv(e,{GIT_AUTHOR_NAME:q,GIT_AUTHOR_EMAIL:ee,GIT_COMMITTER_NAME:q,GIT_COMMITTER_EMAIL:ee});let J=(await e.git.raw([`commit-tree`,O,`-p`,S,`-m`,L])).trim();if(!J||!SHA_HEX_40.test(J)){log$1.warn({raw:J},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,J,S]),await this.resetRealIndexForPaths(j);let Y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),Y=!0}catch{}Y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=J}),g&&(this.lastPushedSha=g,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let s=classifyGitError(t instanceof Error?t:Error(String(t)));if(s.class===`semantic`&&s.subclass===`non-fast-forward`){if(e>0){log$1.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}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,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log$1.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(s,`push`)}finally{try{unlinkSync(s)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),s=this.gatherContentFilesSync(),g=await this.listHeadContentPaths(e,t);if(s.length===0&&g.size===0)return null;let S=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),w=this.gitHandle(S);try{await w.git.raw([`read-tree`,t]);let S=100;for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100).map(e=>e.projectRelPath);await w.git.raw([`add`,`--`,...t])}let E=new Set(s.map(e=>e.projectRelPath)),D=[...g].filter(e=>!E.has(e));await this.removePathsFromIndex(w,D);let O=(await w.git.raw([`write-tree`])).trim();if(O===(await w.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let k=[];try{k=splitNulSeparatedPaths(await w.git.raw([`diff-tree`,`--name-only`,`-z`,`-r`,t,O]))}catch{k=s.map(e=>e.projectRelPath).concat(D)}let j=await resolveGitIdentity(this.projectDir),F=j?.name??`OpenKnowledge`,L=j?.email??`sync@open-knowledge.local`;applyGitEnv(w,{GIT_AUTHOR_NAME:F,GIT_AUTHOR_EMAIL:L,GIT_COMMITTER_NAME:F,GIT_COMMITTER_EMAIL:L});let B=(await w.git.raw([`commit-tree`,O,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!B||!SHA_HEX_40.test(B)?(log$1.warn({raw:B},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,B,t]),await this.resetRealIndexForPaths(k,e),B)}finally{try{unlinkSync(S)}catch{}}}async prepareForMerge(e,t){let s=``;try{s=await e.git.raw([`diff-index`,`--name-only`,`-z`,`HEAD`])}catch(e){return log$1.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let g=splitNulSeparatedPaths(s);if(g.length===0)return{proceed:!0,needsStashPop:!1};let S=``;try{S=await e.git.raw([`diff`,`--name-only`,`-z`,`HEAD..origin/${t}`])}catch(e){return log$1.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let w=new Set(splitNulSeparatedPaths(S)),E=g.filter(e=>w.has(e));if(E.length>0){let e=E.slice(0,3).join(`, `),t=E.length>3?`, +${E.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:E},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let D=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,D])}catch(e){return log$1.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){log$1.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=s=>{let g;try{g=readdirSync(s,{withFileTypes:!0})}catch{return}for(let S of g){let g=join(s,S.name);if(S.isDirectory()){let e=toPosix(relative(this.contentDir,g));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(g)}else if(S.isFile()){let t=toPosix(relative(this.contentDir,g));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let s=toPosix(relative(this.projectDir,g));e.push({contentRelPath:t,projectRelPath:s})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let s=new Set;try{let g=await e.git.raw([`ls-tree`,`-r`,`--name-only`,`-z`,t]);for(let e of splitNulSeparatedPaths(g)){let t=join(this.projectDir,e),g=toPosix(relative(this.contentDir,t));!g.startsWith(`..`)&&!this.contentFilter.isExcluded(g)&&s.add(e)}}catch{}return s}async removePathsFromIndex(e,t){if(t.length===0)return;let s=[...new Set(t)],g=100;for(let t=0;t<s.length;t+=100){let g=s.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...g])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let s=t??this.gitHandle(),g=[...new Set(e)],S=100;for(let e=0;e<g.length;e+=100){let t=g.slice(e,e+100);try{await s.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=splitNulSeparatedPaths(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]))}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=toPosix(relative(this.contentDir,t));!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
3254
3251
|
`,`
|
|
3255
3252
|
`).split(`
|
|
3256
|
-
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!isLinkIndexExcludedDoc(e))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isLinkIndexExcludedDoc(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 g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].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 g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.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))}async listDocsWithPaths(){let e=[];await 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))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=toPosix(relative(this.contentDir,s));this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),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 buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}initTelemetry();let se=randomUUID$1(),ce=getLocalDir(s);if(acquireServerLock(ce,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ce,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ce),e}let ue=createBasenameIndex(),de=(e,t)=>ue.resolveEmbed(e,t),fe=(e,s)=>{let g=ue.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},me,ge,_e,ve,ye,Ce,we,Te,De=null,je=null,Me=null,Pe=null,Ie=ae(),Re=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Ie.enabled,providerFingerprint:oe(Ie)}),ze=null,Be=new Set,Ve=!1,Ue,We,Ge,Ke=new Promise((e,t)=>{We=e,Ge=t});function Xe(e){De?.signal(e)}let $e=2e3,nt=null;function rt(){nt!==null&&clearTimeout(nt),nt=setTimeout(()=>{nt=null,ge.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let it=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),at=(e,t)=>{isReservedForUserTree(e)||it.setRenamed(e,t)},st=e=>{if(!isReservedForUserTree(e)){if(it.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}it.setDeleted(e)}},vt=e=>{isReservedForUserTree(e)||it.delete(e)};try{me=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{ge.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),_e.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(Kt).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ge=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:me}),_e=new TagIndex({contentDir:t,contentFilter:me}),_e.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ve={current:F},ye=E?createMaintenanceCoordinator({getShadow:()=>ve.current??null,getCurrentBranch:()=>$t?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Me&&!Te)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Me?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Te?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,Ce=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ve,ephemeral:J,contentRoot:L,backlinkIndex:ge,configHomedirOverride:k,getCurrentBranch:()=>$t?.getLastKnownBranch()??null,resolveEmbed:de,resolveSize:fe,getPrincipal:()=>ze,onAgentCommit:()=>De?.signal(`session-activity`),onFlushCommit:()=>ye?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{De?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Pe?.(),Xe(`files`))},onConfigRejected:(e,t)=>De?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),we=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[Ce.extension]});let B=we.shouldUnloadDocument.bind(we);we.shouldUnloadDocument=e=>{if(Be.has(e)||Ve&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Ue=async e=>{Be.add(e);try{await we.unloadDocument(e)}finally{Be.delete(e)}},De=new CC1Broadcaster(we),je=new AgentFocusBroadcaster(we),Me=new AgentPresenceBroadcaster(we),Te=new AgentSessionManager(we);let q=createLiveDerivedIndexExtension({backlinkIndex:ge,tagIndex:_e,signalChannel:Xe});we.configuration.extensions.push(q),we.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==se)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${se}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(ze&&s.principalId===ze.id?E.principalId=ze.id:ze?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:ze.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),we.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return isWithinDir(t,Y)?t:null}we.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:it,resolveFilePath:ne,fileExists:existsSync})}}),we.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>we.documents.get(e)})}}),we.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 oe=createApiExtension({hocuspocus:we,sessionManager:Te,contentDir:t,contentFilter:me,serverInstanceId:se,getFileIndex:()=>Kt?Kt.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>Kt?Kt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Kt?.getFileIndexGeneration()??0,mutateFileIndex:e=>Kt?.mutateFileIndex(e),getFolderIndex:()=>Kt?Kt.getFolderIndex():new Map,getAliasMap:()=>Kt?Kt.getAliasMap():new Map,getFolderAliasIndex:()=>Kt?Kt.getFolderAliasIndex():new Map,rescanFiles:()=>Kt?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ve,flushGitCommit:()=>Ce.flushPendingGitCommit(),flushContributors:()=>Ce.flushContributors(),takeStoreFailure:e=>Ce.takeStoreFailure(e),takeStoreDivergence:e=>Ce.takeStoreDivergence(e),markAgentWriteStore:e=>Ce.markAgentWriteStore(e),getCurrentBranch:()=>$t?.getLastKnownBranch()??null,getDiskAckSVs:()=>De?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ge,tagIndex:_e,signalChannel:Xe,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>en,localOpCliArgs:H,projectDir:s,resolveEmbed:de,getPrincipal:()=>ze,homeDirOverride:k,forceUnloadDocument:Ue,ready:Ke,recentlyRemovedDocs:it,serializeDoc:Mt,evictManagedArtifactLkg:e=>{Ce.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Re,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Pe=e}});we.configuration.extensions.push(oe),we.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ve,contentRoot:L,getCurrentBranch:()=>$t?.getLastKnownBranch()??null,resolveEmbed:de,resolveSize:fe})),we.configuration.extensions.push(createSyncHandshakeSpanExtension()),we.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>en,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ce),e}let Tt=null,Et=new Map,Dt=[];function jt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return isWithinDir(g,s)?g:null}function Mt(e){let t=we.documents.get(e);return t?serializeYDocSource(t):null}let Ft=(e,t)=>applyExternalChange(we,e,t,de,fe);function It(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Lt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of we.documents){if(isReservedForUserTree(s))continue;let g=we.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,de,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Rt=null,zt=e=>{e&&(Rt===null&&(Rt=new Set,setImmediate(()=>{let e=Rt;if(Rt=null,e)try{for(let t of e)Lt(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Rt.add(e))};function Bt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Vt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ge.updateDocumentFromMarkdown(e.docName,e.content),rt(),_e.updateDocumentFromMarkdown(e.docName,e.content),Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`),vt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=we.documents.get(t);if(!g){ge.updateDocumentFromMarkdown(t,s),rt(),_e.updateDocumentFromMarkdown(t,s),Xe(`backlinks`),Xe(`graph`),Xe(`tags`);return}let S=getReconciledBase(t)??``,w=Mt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:It(g),ge.updateDocumentFromMarkdown(t,s),rt(),_e.updateDocumentFromMarkdown(t,s),Xe(`backlinks`),Xe(`graph`),Xe(`tags`);break;case`clean`:try{Ft(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),It(g),ge.updateDocumentFromMarkdown(t,s),rt(),_e.updateDocumentFromMarkdown(t,s),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),It(g)}break;case`merged`:try{Ft(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),It(g),ge.updateDocumentFromMarkdown(t,s),rt(),_e.updateDocumentFromMarkdown(t,s),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),It(g)}break;case`conflicts`:try{Ft(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ge.updateDocumentFromMarkdown(t,s),rt(),_e.updateDocumentFromMarkdown(t,s),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=we.documents.get(t);if(!s){ge.deleteDocument(t),rt(),_e.deleteDocument(t),Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`),st(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Mt(t)??``,w=S!==g;if(w&&ve.current){let e=ve.current,s=$t?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),ge.deleteDocument(t),rt(),_e.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),we.closeConnections(t),await Ue(s),Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`),st(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:g}=e,S=we.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ge.renameDocument(t,s,g),rt(),_e.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`),at(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=we.documents.get(t);if(!s)return;let g=Mt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ue.add(e.relativePath),Xe(`files`),zt(basename(e.relativePath));break;case`asset-delete`:ue.remove(e.relativePath),Xe(`files`),zt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Xe(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Xe(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Bt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Ht=[];async function Ut(e){if(isBatchInProgress()){Ht.push(e);return}await Vt(e)}async function Wt(){let e=Ht.splice(0,Ht.length);for(let t of e)await Vt(t)}let Kt=null,$t=null,en=null,jr=null;async function Mr(e){if(we.documents.size===0)return;let t=!1,s=new Promise(e=>{we.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(we.documents.keys());we.closeConnections(),we.flushPendingStores();for(let e of we.documents.values())e.getConnectionsCount()===0&&we.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 S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(we.documents.keys()),S=[],E=[];if(ve.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=Mt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=jt(ve.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ve.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Fr(){return jr||(jr=(async()=>{let e=Date.now(),t=[];Ve=!0,nt!==null&&(clearTimeout(nt),nt=null);let g,S=await Promise.race([Ke.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=we.documents.size;ye?.destroy();try{try{try{$t&&=(await $t.unsubscribe(),null),Kt&&=(await Kt.unsubscribe(),null);for(let{docName:e,cleanup:t}of Dt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Dt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{De?.destroy(),Me?.destroy(),Tt&&=(await Tt.disconnect(),null);for(let[e,t]of Et)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Et.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Te.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Mr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await Ce.flushPendingGitCommit(),await Ce.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{en&&=(await en.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ve.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ve.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ve.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ce)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.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)})}}})(),jr)}let Ir=[];async function Lr(){try{ze=await loadPrincipal(s),Y.info({principalId:ze.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ve.current)try{ve.current=await initShadowRepo(s),Y.info({gitDir:ve.current.gitDir},`[server] history repo initialized at ${ve.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Ir.push(`shadow-repo`)}if(ve.current){let e=null;try{e=loadRenameLogIndex(ve.current.gitDir),sweepLazyPopOrphans(ve.current.gitDir,e),setRenameLogIndex(ve.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(ve.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ye?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ve.current)try{await shadowGit(ve.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`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ve.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ve.current=void 0,Ir.includes(`shadow-repo`)||Ir.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ve.current)try{let e=resolve(ve.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==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{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ve.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.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;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Ir.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Ir.push(`upload-tempfile-sweep`)}try{Tt=await we.openDirectConnection(SYSTEM_DOC_NAME),De?.emitServerInfo(se,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Ir.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await we.openDirectConnection(e);Et.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Ir.push(`config-doc:${e}`)}let S=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,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=we.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,Ce.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=ne();en?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}let S=ae();Re.applyConfig({enabled:S.enabled,providerFingerprint:oe(S)})});Dt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Ir.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,Ce.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(we.documents.get(s)??null,s,t,Ce.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&ge.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Ce.managedArtifactCtx),getActiveBranch()).then(()=>{Xe(`backlinks`),Xe(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(Ce.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Dt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Ir.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Dt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Ir.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(we.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,Ce.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 S=await me.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),De?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),De?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Dt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Ir.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),ge.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await ge.loadFromDisk(e)){let t=await ge.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await ge.rebuildFromDisk(e);try{await ge.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Ce.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}ge.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let s=performance.now();Kt=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,Ut,me)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));try{await _e.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Ir.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:me,basenameIndex:ue,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:ue,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Ir.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Ir.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Ir.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),Kt&&setBootField(`fileCount`,Kt.getFileIndex().size)}try{$t=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),we.flushPendingStores(),await Ce.flushPendingGitCommit(),setBatchInProgress(!0),ve.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of we.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=Mt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ve.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Ht.length,g=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Wt(),await Ce.flushDeferredStores(`within-branch`),en!==null)try{await en.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ht.splice(0,Ht.length),switchReconciledBaseScope(g),nt!==null&&(clearTimeout(nt),nt=null),ge.switchBranch(g),me.rebuildDirCount();try{let e=0;ue.clear(),await seedBasenameIndex({contentDir:t,contentFilter:me,basenameIndex:ue,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Ir.includes(`basename-index-partial`)||Ir.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of we.documents)if(!isReservedForUserTree(e))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Mt(e)??``;if(S!==t&&ve.current){let t=ve.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);Ft(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:we.documents.size},`[branch-switch] loaded branch ${g} (${we.documents.size} docs)`);try{if(await ge.loadFromDisk(g)){let e=await ge.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await ge.rebuildFromDisk(g);try{await ge.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Ce.managedArtifactCtx),g)}catch(e){Y.warn({err:e,branch:g},`[backlinks] branch-switch global skill bundle ingest failed`)}ge.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await _e.init(),ve.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of we.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ve.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:Ft(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Ft(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=we.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&ve.current)try{let t=shadowGit(ve.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3257
|
-
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await Ce.flushDeferredStores(`discard-stale`),De?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ve.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ve.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.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){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Ir.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=we.documents.get(S);if(!w)continue;let E=Mt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{en=new SyncEngine({projectDir:s,contentDir:t,contentFilter:me,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.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||Y.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 en.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),en=null}Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Lr().then(We,Ge),{hocuspocus:we,sessionManager:Te,cc1Broadcaster:De,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ye,contentFilter:me,basenameIndex:ue,serverInstanceId:se,destroy:Fr,ready:Ke,degraded:Ir,lockDir:ce,get syncEngine(){return en}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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 g=resolve(e,t);try{existsSync(g)&&statSync(g).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,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-8Lv6A-Xa-xTK-ENFB.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.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 L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=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:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,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=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=bootElapsedMs();we!==void 0&&recordBootPhase(`httpListenMs`,we);let Te=fe.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(ue=De,O(te,De),ge&&updateUiLockPort(te,De),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};ye=async()=>{if(je)return;je=!0;let e=[],t=async(t,s)=>{try{await Me(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:j,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:De,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
|
|
3258
|
-
`)
|
|
3259
|
-
|
|
3260
|
-
//# sourceMappingURL=dist-Bj79e9B6.mjs.map
|
|
3253
|
+
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!isLinkIndexExcludedDoc(e))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isLinkIndexExcludedDoc(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 g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].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 g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.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))}async listDocsWithPaths(){let e=[];await 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))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=toPosix(relative(this.contentDir,s));this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),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 buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),st=(e,t)=>{isReservedForUserTree(e)||at.setRenamed(e,t)},vt=e=>{if(!isReservedForUserTree(e)){if(at.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}at.setDeleted(e)}},Tt=e=>{isReservedForUserTree(e)||at.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild($t).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>en?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>en?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:at,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.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 oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>$t?$t.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>$t?$t.getAllFilesIndex():new Map,getFileIndexGeneration:()=>$t?.getFileIndexGeneration()??0,mutateFileIndex:e=>$t?.mutateFileIndex(e),getFolderIndex:()=>$t?$t.getFolderIndex():new Map,getAliasMap:()=>$t?$t.getAliasMap():new Map,getFolderAliasIndex:()=>$t?$t.getFolderAliasIndex():new Map,rescanFiles:()=>$t?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>en?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:at,serializeDoc:Ft,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>en?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Et=null,Dt=new Map,jt=[];function Mt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return isWithinDir(g,s)?g:null}function Ft(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let It=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Lt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Rt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},zt=null,Bt=e=>{e&&(zt===null&&(zt=new Set,setImmediate(()=>{let e=zt;if(zt=null,e)try{for(let t of e)Rt(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),zt.add(e))};function Vt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Ht(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Tt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=Ft(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{It(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Lt(g)}break;case`merged`:try{It(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Lt(g)}break;case`conflicts`:try{It(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),vt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Ft(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=en?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),vt(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:g}=e,S=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),st(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=Te.documents.get(t);if(!s)return;let g=Ft(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:de.add(e.relativePath),$e(`files`),Bt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Bt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Vt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Ut=[];async function Wt(e){if(isBatchInProgress()){Ut.push(e);return}await Ht(e)}async function Kt(){let e=Ut.splice(0,Ut.length);for(let t of e)await Ht(t)}let $t=null,en=null,jr=null,Mr=null;async function Fr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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 S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=Ft(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Mt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Ir(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}rt!==null&&(clearTimeout(rt),rt=null);let g,S=await Promise.race([Xe.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=Te.documents.size;Ce?.destroy();try{try{try{en&&=(await en.unsubscribe(),null),$t&&=(await $t.unsubscribe(),null);for(let{docName:e,cleanup:t}of jt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}jt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{je?.destroy(),Pe?.destroy(),Et&&=(await Et.disconnect(),null);for(let[e,t]of Dt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Dt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await De.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Fr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{jr&&=(await jr.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.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)})}}})(),Mr)}let Lr=[];async function zr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Lr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(ye.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.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`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Lr.includes(`shadow-repo`)||Lr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==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{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ye.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.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;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Lr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Lr.push(`upload-tempfile-sweep`)}try{Et=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Lr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);Dt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Lr.push(`config-doc:${e}`)}let S=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,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=Te.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});jt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Lr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);jt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Lr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);jt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Lr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.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 S=await ge.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),je?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(jt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Lr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let s=performance.now();$t=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,Wt,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Lr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Lr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Lr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Lr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),$t&&setBootField(`fileCount`,$t.getFileIndex().size)}try{en=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=Ft(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ye.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Ut.length,g=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Kt(),await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ut.splice(0,Ut.length),switchReconciledBaseScope(g),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(g),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Lr.includes(`basename-index-partial`)||Lr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Ft(e)??``;if(S!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);It(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:Te.documents.size},`[branch-switch] loaded branch ${g} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(g)){let e=await _e.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await _e.rebuildFromDisk(g);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),g)}catch(e){Y.warn({err:e,branch:g},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:It(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:It(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3254
|
+
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ye.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.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){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Lr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=Ft(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.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||Y.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 jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return zr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Ir,ready:Xe,degraded:Lr,lockDir:ue,get syncEngine(){return jr}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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 g=resolve(e,t);try{existsSync(g)&&statSync(g).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,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-BG2sFhIR.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.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=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=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:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets?createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]);E=new Set(splitNulSeparatedPaths(g))}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}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 g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`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(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{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),g=0;g<32;g+=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 g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
|
|
3255
|
+
`,`utf-8`),t}export{STARTER_PACKS as $,validateSkillZip as $i,isAllowedWorkspaceHostHeader as $n,resetMetrics as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spansPreviousPath as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedMkdir as Bi,handleCollabSocketError as Bn,readSkillInstallStateSnapshot as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,resolveShadowDir as Ca,seedBasenameIndex as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,shutdownTelemetry as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,shadowGit as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,swapContributors as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedRmdirSync as Gi,initContent as Gn,readUiLock as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRename as Hi,hasGcLogLatch as Hn,readStateManifest as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,teardownToleranceTelemetryWriter as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,tracedWriteFileSync as Ji,initToleranceTelemetryWriter as Jn,recordSkillInstallEvent as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedUnlinkSync as Ki,initShadowRepo as Kn,reconcile as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,toBroadcasterKey as Li,getMeter as Ln,readBundleDecision as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,splitMarkdownBlocks as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,startWatcher as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,skillManagementPath as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,streamingProblemEvent as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateCloneInputs as Qi,isAllowedApiOrigin as Qn,removeLastKnownHash as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,tracedAppendFileSync as Ri,getMetrics as Rn,readProjectLocalSemanticConfig as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,resolveGitDirDetailed as Sa,saveVersion as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,setActiveSpanAttributes as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRenameSync as Ui,incrementCollabSocketFilteredError as Un,readTargetRecordedAt as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedMkdirSync as Vi,handleSpawnCursor as Vn,readSkillManagement as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRmSync as Wi,incrementServerObserverFire as Wn,readTargetVersion as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,updateUiLockPort as Xi,installTestLoggers as Xn,registerWrite as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,updateLastKnownHash as Yi,installPrettyZodErrors as Yn,registerAllTools as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,validateAgentId as Zi,installUserSkill as Zn,releaseUiLock as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,withFileLockSync as _a,safeContentPath as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeStateManifest as aa,resolvePack as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,MalformedGitPointerError as ba,sanitizeClientName as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,McpServer as ca,restoreContributors as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,isInitializedNotification as da,rewriteWikiLinksForDocumentRename as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,withSpan as ea,resolveBundledSkillDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,isJSONRPCRequest as fa,runAuthReposSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,resolveConfigPath as ga,runWithMcpLogger as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,readConfigSafely as ha,runDeviceFlowSubprocess as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeSkillManagement as ia,resolveLockDir as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,spawnDetached as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spansCurrentPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,JSONRPCMessageSchema as la,restoreLifecycleFromConflictsJson as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,atomicWriteFileSync as ma,runCloneSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,writeBundleDecision as na,resolveCursorBinaryDefault as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,writeTargetVersion as oa,resolvePackageVersion as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,isJSONRPCResultResponse as pa,runAuthStatusSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedWriteFile as qi,initTelemetry as qn,recordContributor as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeRootGitignoreForNewRepo as ra,resolveCursorSpawnInvocation as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,writeTracker as sa,resolveUiInfo as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,withSpanSync as ta,resolveContentDir as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,LATEST_PROTOCOL_VERSION as ua,rewriteMarkdownLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,writeConfigPatch as va,safeSubdir as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,serializeError as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,parseCheckpoint as xa,saveInMemoryCheckpoint as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,GitDirAccessError as ya,safetyCheckpoint as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedLinkSync as zi,getTracer as zn,readServerPackageVersion as zr,commitWipFromTree as zt};
|
|
3256
|
+
//# sourceMappingURL=dist-D13xYuEX.mjs.map
|