@inkeep/open-knowledge 0.85.0-beta.4 → 0.85.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-BvlvLl1n.mjs +1 -0
  3. package/dist/{dist-NhLRGMzw.mjs → dist-4xO55Yaw.mjs} +1 -1
  4. package/dist/{dist-BCYVWHsR.mjs → dist-Bkpf6l5f.mjs} +2 -2
  5. package/dist/index.d.mts +33 -1
  6. package/dist/index.mjs +237 -237
  7. package/dist/init-DBZrc26-.mjs +1 -0
  8. package/dist/{init-iH-arA2G.mjs → init-ldk3Lxrs.mjs} +2 -2
  9. package/dist/{launch-json-removal-7EPfW1gR.mjs → launch-json-removal-BXYVKNWi.mjs} +1 -1
  10. package/dist/{loader-BPBqgr-2.mjs → loader-AVkdw8Hm.mjs} +1 -1
  11. package/dist/loader-ClbHn4dH.mjs +1 -0
  12. package/dist/{md-manager-BGnqyqi1-dBGkA2rR.mjs → md-manager-BGnqyqi1-CDSS__qm.mjs} +1 -1
  13. package/dist/{open-browser-BA4x7USG.mjs → open-browser-sLXj2Tjq.mjs} +1 -1
  14. package/dist/parse-worker.mjs +1 -1
  15. package/dist/{preview-C8nGyFNQ.mjs → preview-C-hKLhmn.mjs} +1 -1
  16. package/dist/preview-C8T1hpsw.mjs +1 -0
  17. package/dist/public/assets/{AccountSection-uEZl_mju.js → AccountSection-C2ByOkUI.js} +1 -1
  18. package/dist/public/assets/{ActivityModeContent-D6bm4kJT.js → ActivityModeContent-BULJrReB.js} +1 -1
  19. package/dist/public/assets/{AddPropertiesButton-BbxqMedS.js → AddPropertiesButton-C6E3eAY2.js} +2 -2
  20. package/dist/public/assets/{AgentConnectionsSection-C4Y6AXkF.js → AgentConnectionsSection-BOlCjbB0.js} +1 -1
  21. package/dist/public/assets/{AgentDiffPane-DxqfS7to.js → AgentDiffPane-BVF6LAi_.js} +1 -1
  22. package/dist/public/assets/{AttachmentsSection-D4gD9K5F.js → AttachmentsSection-Ckb1l8E_.js} +1 -1
  23. package/dist/public/assets/{AuthModal-SudaNBin.js → AuthModal-7ZC-1yVV.js} +1 -1
  24. package/dist/public/assets/{CodeMirrorPropInput-Buv5WUqJ.js → CodeMirrorPropInput-Cciy5ifm.js} +1 -1
  25. package/dist/public/assets/{ContentRulesSection-Br-l422Z.js → ContentRulesSection-ujD5Z5Kn.js} +1 -1
  26. package/dist/public/assets/{DiffViewBoundary-BEZkhnbH.js → DiffViewBoundary-Cue9UIPe.js} +1 -1
  27. package/dist/public/assets/{DocumentContext-CorZvYgo.js → DocumentContext-O6SVorx1.js} +28 -28
  28. package/dist/public/assets/{EditorModeToggle-CRzHwk_c.js → EditorModeToggle-CQCRRque.js} +1 -1
  29. package/dist/public/assets/{ExcalidrawDocEditor-EQVCkgpX.js → ExcalidrawDocEditor-Bf9WFyvx.js} +1 -1
  30. package/dist/public/assets/FeedbackForm-Nms6yFro.js +1 -0
  31. package/dist/public/assets/{GraphPanel-fkRF4Ymc.js → GraphPanel-BmqiikMo.js} +1 -1
  32. package/dist/public/assets/{ImportSkillDialog-DuG9JEye.js → ImportSkillDialog-DtBPqJuu.js} +1 -1
  33. package/dist/public/assets/{LinkPreviewsSection--PnKeBLD.js → LinkPreviewsSection-BdPyqNSV.js} +1 -1
  34. package/dist/public/assets/{LintConfigEditor-jcGxgQwc.js → LintConfigEditor-CjrEvNqp.js} +1 -1
  35. package/dist/public/assets/{LintingSection-Dvgj5Ttf.js → LintingSection-CBA982pF.js} +1 -1
  36. package/dist/public/assets/ManagedArtifactProperties-Cp5xFdlU.js +1 -0
  37. package/dist/public/assets/{ManagedArtifactProperties-Bsvat-ju.js → ManagedArtifactProperties-DCTAdGr-.js} +1 -1
  38. package/dist/public/assets/{MermaidDocEditor-VR7GsjSm.js → MermaidDocEditor-DSrgP38T.js} +1 -1
  39. package/dist/public/assets/{NetworkAccessSection-D43WDwx9.js → NetworkAccessSection-Dj1ezrw0.js} +1 -1
  40. package/dist/public/assets/{ProjectTemplatesSection-B-AUPC6m.js → ProjectTemplatesSection-oiahzFKw.js} +1 -1
  41. package/dist/public/assets/{PropertyDisplayRow-CWrQAKBl.js → PropertyDisplayRow-DVJTtG4F.js} +1 -1
  42. package/dist/public/assets/PublishToGitHubDialog-CTLXiHm2.js +1 -0
  43. package/dist/public/assets/{RegisteredAgentIcon-DjlAkIlP.js → RegisteredAgentIcon-DKZ8eOKZ.js} +1 -1
  44. package/dist/public/assets/{SchemaConfigEditor-CGaJB0xn.js → SchemaConfigEditor-B4Sb6R0l.js} +1 -1
  45. package/dist/public/assets/{SearchSection-a8lszdwH.js → SearchSection-caz6Sv4E.js} +1 -1
  46. package/dist/public/assets/{SessionsHost-BjkYqOzo.js → SessionsHost-D5uQjrJt.js} +2 -2
  47. package/dist/public/assets/{SettingsDialogBody-Cg5j6OJH.js → SettingsDialogBody-Drcz-_Cc.js} +2 -2
  48. package/dist/public/assets/{ShareReceiveMissDialog-DRGvyccq.js → ShareReceiveMissDialog-CJ5quzhA.js} +1 -1
  49. package/dist/public/assets/{SkillCostValue-CzBUsuYu.js → SkillCostValue-DPX8ruMM.js} +1 -1
  50. package/dist/public/assets/{SkillForkDialog-QqHr4a1o.js → SkillForkDialog-BB_XS1nP.js} +1 -1
  51. package/dist/public/assets/{SkillInstallMenu-BQHSpQsX.js → SkillInstallMenu-CAjgsxCn.js} +1 -1
  52. package/dist/public/assets/{SkillOriginInline-DzV3iN2B.js → SkillOriginInline-D1tWqOqr.js} +1 -1
  53. package/dist/public/assets/{SkillToolbarControls-uJO_ykPP.js → SkillToolbarControls-6WW0LRUN.js} +1 -1
  54. package/dist/public/assets/{SkillsManagerSection-DJfOBpFG.js → SkillsManagerSection-B0OJHWNm.js} +1 -1
  55. package/dist/public/assets/{SlidesPluginSection-Dc5MqsXL.js → SlidesPluginSection-Bi8J2lVH.js} +1 -1
  56. package/dist/public/assets/{SlidesToolbarControls-BpcUGXo9.js → SlidesToolbarControls-CqXBuf70.js} +1 -1
  57. package/dist/public/assets/{SourceEditor-D0RSGDUt.js → SourceEditor-ChlmoOF6.js} +1 -1
  58. package/dist/public/assets/{SpellingSettings-DUJM89JE.js → SpellingSettings-Dkdy9B2q.js} +1 -1
  59. package/dist/public/assets/{SyncSection-CRG2LkSG.js → SyncSection-Z6vZnE_K.js} +1 -1
  60. package/dist/public/assets/{SyncStatusBadge-DoYJzvIT.js → SyncStatusBadge-CM_7PzwW.js} +1 -1
  61. package/dist/public/assets/{TemplateRow-xwZoU5JB.js → TemplateRow-DoNZxhIJ.js} +1 -1
  62. package/dist/public/assets/{TerminalLaunchContext-CJTkwtCs.js → TerminalLaunchContext-Cwrrh5Ck.js} +1 -1
  63. package/dist/public/assets/{TerminalPanel-Ch3gwsVs.js → TerminalPanel-C5LSq4fA.js} +1 -1
  64. package/dist/public/assets/{TerminalSection-6ExXD5z5.js → TerminalSection-68nvfvrh.js} +1 -1
  65. package/dist/public/assets/{TerminalWindowApp-B2mnEA0Z.js → TerminalWindowApp-CrSGKKKu.js} +1 -1
  66. package/dist/public/assets/{TextDocEditor-CzwNYI5Q.js → TextDocEditor-BXOqsewj.js} +1 -1
  67. package/dist/public/assets/{ThemePluginSection-CizNpiAG.js → ThemePluginSection-BT1NQe1R.js} +1 -1
  68. package/dist/public/assets/{ThreadView-CAfBkY-n.js → ThreadView-DnrRFDwk.js} +5 -5
  69. package/dist/public/assets/{TimelineDiffPane-Oj5zOvzN.js → TimelineDiffPane-1hGv8QvR.js} +1 -1
  70. package/dist/public/assets/_envelope-g8Le8UBe-6j_3zVcA.js +1 -0
  71. package/dist/public/assets/{agent-connections-D2w6claM.js → agent-connections-CykO_Ezy.js} +1 -1
  72. package/dist/public/assets/{agent-registry-B4dxoiaL.js → agent-registry-pREadnY_.js} +1 -1
  73. package/dist/public/assets/{bridge-DsUUjTsy.js → bridge-D8Oy74FE.js} +1 -1
  74. package/dist/public/assets/{card-DdkXkyr5.js → card-DJoKetZ9.js} +1 -1
  75. package/dist/public/assets/{catalog-Bdh906tM.js → catalog-CJ_rs_wb.js} +1 -1
  76. package/dist/public/assets/{client-version-DDIvS8RB.js → client-version-B59eMHEh.js} +1 -1
  77. package/dist/public/assets/{comment-chips-DNwQbxLO.js → comment-chips-DcGtlMew.js} +2 -2
  78. package/dist/public/assets/{config-provider-2W1hFFiT.js → config-provider-CIK_K42_.js} +1 -1
  79. package/dist/public/assets/config-schema-Dh_H8E-u.js +1 -0
  80. package/dist/public/assets/{css-color-to-hex-D-oM_f97.js → css-color-to-hex-Cjxd2Xbp.js} +1 -1
  81. package/dist/public/assets/{doc-undo-manager-1o5q5gwi.js → doc-undo-manager-UW0jSZSz.js} +1 -1
  82. package/dist/public/assets/field-controls-C6S4B1Im.js +1 -0
  83. package/dist/public/assets/{field-controls-BLwJrin4.js → field-controls-DSwLWrMh.js} +1 -1
  84. package/dist/public/assets/{frontmatter-tags-DIPhIb6q.js → frontmatter-tags-CoOxl3mC.js} +1 -1
  85. package/dist/public/assets/{handoff-ClTYrgLm.js → handoff-pwpLEUcJ.js} +1 -1
  86. package/dist/public/assets/index-CM686K03.js +2205 -0
  87. package/dist/public/assets/{lint-config-client-DhP_RDHH.js → lint-config-client-DDZrpVHz.js} +1 -1
  88. package/dist/public/assets/{lint-plugins-BTxsaGaY.js → lint-plugins-ERzf4kg6.js} +1 -1
  89. package/dist/public/assets/{markdown-lint-BmjyI9ZU.js → markdown-lint-DeZBsw3J.js} +1 -1
  90. package/dist/public/assets/{markdownlint-rule-browser-BADH1Lka.js → markdownlint-rule-browser-60Esn3tM.js} +1 -1
  91. package/dist/public/assets/messages-78IX_mb6.js +1 -0
  92. package/dist/public/assets/messages-B6BYNmqo.js +1 -0
  93. package/dist/public/assets/messages-B8EWK_89.js +1 -0
  94. package/dist/public/assets/messages-BBf4KTqG.js +1 -0
  95. package/dist/public/assets/messages-Bwl4NQMF.js +1 -0
  96. package/dist/public/assets/messages-D8vS5v1Q.js +1 -0
  97. package/dist/public/assets/messages-DE1vIF6g.js +1 -0
  98. package/dist/public/assets/messages-DMLet84f.js +1 -0
  99. package/dist/public/assets/messages-DTOPrMXM.js +1 -0
  100. package/dist/public/assets/messages-DZEtkTdx.js +1 -0
  101. package/dist/public/assets/messages-DaxVzGDb.js +1 -0
  102. package/dist/public/assets/messages-GFEtxKER.js +1 -0
  103. package/dist/public/assets/messages-TMbZtDXU.js +1 -0
  104. package/dist/public/assets/{pending-receive-nav-store-CsnZS_Ro.js → pending-receive-nav-store-Ccvl_4v5.js} +1 -1
  105. package/dist/public/assets/{preferred-session-events-DhdzT8Vr.js → preferred-session-events-DknIouR1.js} +1 -1
  106. package/dist/public/assets/{progress-CLlmYVN5.js → progress-D0oG51o9.js} +1 -1
  107. package/dist/public/assets/{saved-themes-client-CSjCi4YD.js → saved-themes-client-ByYw6oZt.js} +1 -1
  108. package/dist/public/assets/{schema-section-H3icVnyE.js → schema-section-C8DGjvNX.js} +1 -1
  109. package/dist/public/assets/{schemas-api-BbYGQuTW.js → schemas-api-CQHNNDP6.js} +1 -1
  110. package/dist/public/assets/{selection-context-BiUjqAKb.js → selection-context-bAocd9VM.js} +1 -1
  111. package/dist/public/assets/{skills-api-DronAhV9.js → skills-api-B7NWq2mZ.js} +1 -1
  112. package/dist/public/assets/{src-DGY0VXnv.js → src-CIp5b6be.js} +1 -1
  113. package/dist/public/assets/storage-scope-lp6Y3sn1.js +1 -0
  114. package/dist/public/assets/{tag-pill-input-etcmLbrt.js → tag-pill-input-C9tJ_ebG.js} +1 -1
  115. package/dist/public/assets/{telemetry-impl-C_SzfD38.js → telemetry-impl-CKW89ItP.js} +1 -1
  116. package/dist/public/assets/{telemetry-startup-CrBJFhWz.js → telemetry-startup-Bs8b3-XO.js} +1 -1
  117. package/dist/public/assets/terminal-cli-display-Bn8rI2FY.js +1 -0
  118. package/dist/public/assets/{terminal-command-events-DylLB9_L.js → terminal-command-events-DYVYsw0p.js} +1 -1
  119. package/dist/public/assets/{terminal-launch-events-BCKO9apj.js → terminal-launch-events-C1I24zal.js} +1 -1
  120. package/dist/public/assets/{typing-burst-detector-BvJppmhO.js → typing-burst-detector-Bxrmsx3r.js} +3 -3
  121. package/dist/public/assets/{uninstall-Bo2t4rIS.js → uninstall-Dg977zNF.js} +1 -1
  122. package/dist/public/assets/{use-activity-panel-vwUB_0Q4.js → use-activity-panel-CdrfMfLb.js} +1 -1
  123. package/dist/public/assets/{use-apply-config-color-theme-DiRXrQH-.js → use-apply-config-color-theme-B9f6n0Cd.js} +1 -1
  124. package/dist/public/assets/{use-apply-config-language-D-iaXzSu.js → use-apply-config-language-CdocdaSu.js} +2 -2
  125. package/dist/public/assets/{use-conflicts-E9tj1NHs.js → use-conflicts-BJFBAg9M.js} +1 -1
  126. package/dist/public/assets/{use-live-xterm-theme-DnTcPzv0.js → use-live-xterm-theme-CMmPbV7u.js} +1 -1
  127. package/dist/public/assets/{use-open-skill-D0ybF2gq.js → use-open-skill-ZYDfMBAv.js} +1 -1
  128. package/dist/public/assets/{use-semantic-search-status-Bq4BpHMI.js → use-semantic-search-status-Cqw3SIgk.js} +1 -1
  129. package/dist/public/assets/{use-skill-origin-BnTpq9XZ.js → use-skill-origin-f6iU7bK5.js} +1 -1
  130. package/dist/public/assets/{use-skill-targets-DcxmfKVk.js → use-skill-targets-CcZTp1aJ.js} +1 -1
  131. package/dist/public/assets/{use-skills-D9Qpt2AT.js → use-skills-D4I9tjyB.js} +1 -1
  132. package/dist/public/assets/{use-terminal-enabled-BAfmRgEk.js → use-terminal-enabled-CrnwtMub.js} +1 -1
  133. package/dist/public/assets/{use-timeline-entry-diff-CFyLJSDJ.js → use-timeline-entry-diff-DZtvF4rg.js} +1 -1
  134. package/dist/public/assets/{use-workspace-Dyz_XHeI.js → use-workspace-CF2-WOaH.js} +1 -1
  135. package/dist/public/index.html +52 -52
  136. package/dist/public/uninstall.html +3 -3
  137. package/dist/{registry-probes-CM3GVnGY.mjs → registry-probes-AWqbJuf-.mjs} +1 -1
  138. package/dist/{removal-file-path-oz6iBHDK.mjs → removal-file-path-Bl0xISuT.mjs} +1 -1
  139. package/dist/{repair-launch-json-DNSuSUsH.mjs → repair-launch-json-C1q2V-kv.mjs} +1 -1
  140. package/dist/{repair-mcp-configs-Bahn7_bp.mjs → repair-mcp-configs-vv41a7xY.mjs} +1 -1
  141. package/dist/src-C3d2YqKO.mjs +1 -0
  142. package/dist/{src-BqzHUD_W.mjs → src-D7NPnfwO.mjs} +10 -10
  143. package/dist/start-BHGwh3sJ.mjs +1 -0
  144. package/dist/{start-CEEWMHcQ.mjs → start-sIP2yOWJ.mjs} +3 -3
  145. package/package.json +4 -4
  146. package/dist/constants-D5w683OR.mjs +0 -1
  147. package/dist/init-CzUtIxs8.mjs +0 -1
  148. package/dist/loader-C15d7cmm.mjs +0 -1
  149. package/dist/preview-CVz9i5jg.mjs +0 -1
  150. package/dist/public/assets/FeedbackForm-B3LCnaN-.js +0 -1
  151. package/dist/public/assets/ManagedArtifactProperties-DQGljSd5.js +0 -1
  152. package/dist/public/assets/PublishToGitHubDialog-C3wLeehy.js +0 -1
  153. package/dist/public/assets/_envelope-Dwl6i2K9-DPqJ_Q4W.js +0 -1
  154. package/dist/public/assets/config-schema-DSj91SAu.js +0 -1
  155. package/dist/public/assets/field-controls-BxZbpvVJ.js +0 -1
  156. package/dist/public/assets/index-ClMapCCf.js +0 -2205
  157. package/dist/public/assets/messages-BT33WTY4.js +0 -1
  158. package/dist/public/assets/messages-B_gBh8es.js +0 -1
  159. package/dist/public/assets/messages-BkJsr6GH.js +0 -1
  160. package/dist/public/assets/messages-CUhRQF6Z.js +0 -1
  161. package/dist/public/assets/messages-CfM_V0is.js +0 -1
  162. package/dist/public/assets/messages-Cilh2EEK.js +0 -1
  163. package/dist/public/assets/messages-CoC6kH02.js +0 -1
  164. package/dist/public/assets/messages-D8jal7DN.js +0 -1
  165. package/dist/public/assets/messages-DHbSVEtI.js +0 -1
  166. package/dist/public/assets/messages-DlgKcLpa.js +0 -1
  167. package/dist/public/assets/messages-Dot6gpGm.js +0 -1
  168. package/dist/public/assets/messages-Dy_NuDHm.js +0 -1
  169. package/dist/public/assets/messages-Zy-8a3Uz.js +0 -1
  170. package/dist/public/assets/storage-scope-DSPgNqch.js +0 -1
  171. package/dist/public/assets/terminal-cli-display-BbrhD8t2.js +0 -1
  172. package/dist/src-DKF_fAWB.mjs +0 -1
  173. package/dist/start-BueKHDx7.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-tZXQYakl.mjs";import{$ as o,$a as s,$c as c,$d as l,$l as u,$n as d,$o as f,$r as p,$s as m,$t as h,$u as g,A as _,Aa as v,Ac as y,Ad as b,Ai as x,Al as S,An as C,Ao as w,Ar as T,As as E,At as D,Au as O,B as k,Ba as A,Bc as j,Bd as ee,Bi as M,Bl as N,Bn as P,Bo as te,Br as ne,Bs as re,Bt as ie,Bu as ae,C as oe,Ca as se,Cc as ce,Cd as F,Ci as le,Cl as ue,Cn as de,Co as fe,Cr as pe,Cs as me,Ct as he,Cu as ge,D as _e,Da as ve,Dc as ye,Dd as be,Di as xe,Dl as Se,Dn as Ce,Do as we,Dr as Te,Ds as Ee,Dt as De,Du as Oe,E as ke,Ed as I,Ei as Ae,El as je,En as Me,Eo as Ne,Er as Pe,Es as Fe,Et as Ie,Eu as Le,Fa as Re,Fd as ze,Fi as Be,Fn as Ve,Fo as He,Fr as Ue,Fs as We,Ft as Ge,Fu as Ke,G as qe,Ga as Je,Gc as Ye,Gd as Xe,Gi as Ze,Gn as Qe,Go as $e,Gr as et,Gs as tt,Gt as nt,Gu as rt,Ha as it,Hc as at,Hd as ot,Hi as st,Hl as ct,Hn as lt,Ho as ut,Hr as dt,Hs as ft,Ht as pt,Hu as mt,I as ht,Ia as gt,Ic as _t,Id as vt,Ii as yt,Il as bt,In as xt,Io as St,Ir as Ct,Is as wt,It as Tt,Iu as Et,J as Dt,Ja as Ot,Jc as kt,Jd as At,Ji as jt,Jn as Mt,Jo as Nt,Jr as Pt,Js as Ft,Jt as It,Ju as Lt,Ka as Rt,Kd as zt,Ki as Bt,Kl as Vt,Kn as Ht,Ko as Ut,Kr as Wt,Ks as Gt,Kt,Ku as qt,L as Jt,La as Yt,Lc as Xt,Ld as Zt,Li as Qt,Ll as $t,Ln as en,Lo as tn,Lr as nn,Ls as rn,Lt as an,Lu as on,Ma as sn,Mc as cn,Md as ln,Mi as un,Mn as dn,Mo as fn,Mr as pn,Ms as mn,Mt as hn,Mu as gn,N as _n,Na as vn,Nc as yn,Nd as L,Ni as bn,Nn as xn,No as Sn,Nr as Cn,Ns as wn,Nt as Tn,Nu as En,Oa as Dn,Oc as eee,Od as On,Oi as kn,Ol as An,On as jn,Oo as Mn,Or as Nn,Os as Pn,Ot as Fn,Ou as In,Pa as Ln,Pc as Rn,Pd as zn,Pi as Bn,Pl as Vn,Pn as Hn,Po as Un,Pr as Wn,Ps as Gn,Pt as Kn,Pu as qn,Q as Jn,Qa as Yn,Qd as Xn,Qi as tee,Ql as Zn,Qn,Qo as $n,Qr as er,Qs as tr,Qt as nr,Qu as rr,Ra as ir,Rc as ar,Rd as or,Ri as sr,Rl as cr,Rn as nee,Ro as ree,Rr as iee,Rs as lr,Rt as ur,Ru as dr,Sa as fr,Sc as pr,Sd as mr,Si as hr,Sl as gr,Sn as _r,So as vr,Sr as yr,Ss as br,St as xr,Su as Sr,T as Cr,Ta as wr,Tc as Tr,Td as Er,Tf as Dr,Ti as Or,Tl as kr,Tn as Ar,To as jr,Tr as Mr,Ts as aee,Tt as Nr,Tu as Pr,Ua as oee,Uc as Fr,Ud as see,Ui as cee,Ul as Ir,Un as lee,Uo as uee,Ur as dee,Us as fee,Ut as pee,Uu as mee,V as Lr,Va as Rr,Vc as hee,Vd as zr,Vi as Br,Vl as Vr,Vn as Hr,Vo as Ur,Vr as Wr,Vs as Gr,Vt as gee,Vu as _ee,Wa as vee,Wd as Kr,Wi as yee,Wl as qr,Wn as bee,Wo as xee,Wr as See,Ws as Cee,Wt as wee,Wu as Tee,Xa as Eee,Xc as Jr,Xd as Yr,Xi as Xr,Xl as Zr,Xn as Dee,Xo as Oee,Xr as kee,Xs as Aee,Xt as Qr,Xu as jee,Ya as $r,Yc as Mee,Yd as Nee,Yi as Pee,Yn as ei,Yo as Fee,Yr as Iee,Ys as Lee,Yt as ti,Yu as Ree,Z as zee,Za as Bee,Zc as ni,Zd as Vee,Zi as ri,Zl as ii,Zn as Hee,Zo as ai,Zr as Uee,Zs as Wee,Zt as oi,Zu as si,_ as Gee,_c as ci,_d as R,_f as li,_i as Kee,_l as qee,_n as ui,_o as Jee,_r as di,_s as Yee,_t as fi,_u as Xee,a as Zee,aa as Qee,ad as $ee,ai as ete,al as tte,an as nte,ao as rte,ar as ite,as as ate,at as pi,au as ote,b as mi,ba as ste,bc as hi,bd as gi,bf as _i,bi as cte,bl as lte,bn as ute,bo as dte,br as fte,bs as pte,bt as vi,bu as yi,c as mte,ca as hte,cc as bi,ci as xi,cl as gte,cn as _te,co as vte,cr as yte,cs as bte,ct as Si,cu as Ci,d as wi,da as xte,dc as Ti,df as Ei,di as Ste,dn as Cte,do as wte,dr as Tte,ds as Ete,dt as Di,du as Oi,ea as Dte,ec as Ote,ed as kte,ei as ki,el as Ate,en as jte,eo as Mte,er as Nte,es as Pte,eu as Fte,fa as Ai,fc as ji,ff as Ite,fi as Lte,fn as Rte,fo as Mi,fr as Ni,fs as Pi,ft as Fi,fu as Ii,g as zte,gc as Bte,gf as Li,gi as Ri,gl as Vte,gn as Hte,go as Ute,gr as zi,gs as Wte,gt as Bi,gu as Gte,h as Kte,ha as qte,hc as Vi,hd as Hi,hf as Jte,hi as Yte,hn as Xte,ho as Ui,hr as Zte,hs as Qte,ht as Wi,hu as $te,ia as Gi,ic as Ki,id as ene,if as qi,ii as tne,il as Ji,in as nne,io as rne,ir as ine,is as ane,it as one,iu as sne,j as cne,ja as lne,jc as une,jd as dne,ji as fne,jn as pne,jo as mne,jr as hne,js as gne,jt as _ne,ju as vne,k as Yi,ka as Xi,kc as Zi,kd as z,ki as yne,kl as bne,kn as xne,ko as Sne,kr as Cne,ks as wne,kt as Tne,ku as Ene,la as Dne,lc as One,ld as kne,li as Ane,ll as jne,ln as Mne,lo as Nne,lr as Pne,ls as Fne,lt as Qi,lu as $i,m as ea,ma as ta,mc as na,md as ra,mi as Ine,ml as Lne,mn as Rne,mo as zne,mr as Bne,ms as Vne,mt as Hne,mu as ia,n as aa,na as Une,nc as Wne,nd as Gne,ni as Kne,nl as qne,nn as Jne,no as Yne,nr as Xne,ns as Zne,nt as Qne,nu as $ne,o as ere,oa,oc as tre,od as nre,of as rre,oi as ire,ol as sa,on as are,oo as ore,or as sre,os as cre,ot as ca,ou as lre,pa as ure,pd as dre,pf as fre,pi as pre,pl as mre,pn as hre,po as gre,pr as _re,ps as vre,pt as yre,pu as bre,q as xre,qa as Sre,qd as Cre,qi as wre,ql as Tre,qn as Ere,qo as Dre,qr as Ore,qt as la,qu as ua,ra as kre,rd as Are,rf as da,ri as jre,rl as fa,rn as Mre,ro as Nre,rr as Pre,rs as Fre,rt as pa,ru as Ire,s as ma,sa as Lre,sc as ha,sd as Rre,sf as ga,si as zre,sl as _a,sn as va,so as Bre,sr as Vre,ss as Hre,st as ya,su as ba,t as xa,ta as Ure,tc as Wre,td as Gre,tf as Sa,ti as Kre,tl as Ca,tn as qre,to as Jre,tr as Yre,ts as Xre,tt as Zre,tu as Qre,ua as wa,uc as Ta,ud as $re,ui as eie,un as tie,uo as nie,ur as rie,us as iie,ut as Ea,uu as aie,v as oie,va as Da,vc as Oa,vd as ka,vf as sie,vi as Aa,vl as cie,vn as ja,vo as lie,vr as uie,vs as die,vt as Ma,vu as Na,w as fie,wa as Pa,wc as Fa,wd as Ia,wi as pie,wl as mie,wn as hie,wo as La,wr as gie,ws as _ie,wt as Ra,wu as za,x as vie,xa as Ba,xc as yie,xd as Va,xf as bie,xi as xie,xl as Sie,xn as Cie,xo as Ha,xr as wie,xs as Tie,xt as Eie,xu as Die,y as Oie,ya as kie,yc as Ua,yd as Aie,yi as jie,yl as Mie,yn as Nie,yo as Pie,yr as Wa,ys as Fie,yt as Iie,yu as Ga,z as Ka,za as qa,zc as Lie,zi as Rie,zl as zie,zn as Ja,zo as Ya,zr as Bie,zs as Vie,zt as Hie,zu as Xa}from"./md-manager-BGnqyqi1-dBGkA2rR.mjs";import{c as Za,d as Qa,h as Uie,i as $a,l as eo,n as to,o as no,p as ro,t as io}from"./esm-B3YyV3nD.mjs";import{t as Wie}from"./libesm-DRoEqbAC.mjs";import{t as Gie}from"./yazl-BBz29IQN.mjs";import{t as ao}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as oo,c as Kie,d as qie,f as so,h as Jie,i as co,l as lo,m as uo,n as fo,o as po,p as mo,r as ho,s as go,t as _o,u as vo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as yo,B as bo,C as xo,D as So,E as Yie,F as Xie,H as Zie,I as Qie,L as Co,M as wo,N as To,O as Eo,P as Do,S as $ie,T as eae,V as tae,_ as nae,a as Oo,b as ko,c as Ao,d as jo,f as Mo,g as rae,h as iae,i as No,j as Po,k as Fo,l as Io,m as aae,n as oae,o as Lo,p as Ro,r as zo,s as Bo,t as sae,u as Vo,v as Ho,w as Uo,x as Wo,y as Go,z as Ko}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as qo,r as Jo,t as Yo}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as Xo}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as Zo}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as Qo,t as $o}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as cae,t as lae}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as es,r as ts,t as uae}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as dae,t as ns}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as rs}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as is}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as fae}from"./wrapper-BF8oRx3G.mjs";import{createRequire as as}from"node:module";import{execFile as os,execFileSync as pae,spawn as ss,spawnSync as cs}from"node:child_process";import*as ls from"node:path";import{basename as us,delimiter as ds,dirname as B,extname as fs,isAbsolute as ps,join as V,normalize as ms,parse as mae,posix as hs,relative as H,resolve as U,sep as gs,win32 as _s}from"node:path";import{URLSearchParams as hae,fileURLToPath as vs,pathToFileURL as ys}from"node:url";import*as bs from"node:fs";import{accessSync as gae,appendFileSync as _ae,chmodSync as xs,closeSync as Ss,constants as Cs,cpSync as vae,createReadStream as ws,createWriteStream as Ts,existsSync as W,fchmodSync as yae,fstatSync as bae,linkSync as xae,lstatSync as Es,mkdirSync as Ds,mkdtempSync as Os,openSync as ks,opendirSync as Sae,readFile as Cae,readFileSync as G,readSync as wae,readdirSync as As,readlinkSync as Tae,realpathSync as js,renameSync as Ms,rmSync as Ns,rmdirSync as Ps,statSync as Fs,symlinkSync as Eae,unlinkSync as Is,watch as Dae,writeFileSync as Ls,writeSync as Rs}from"node:fs";import{arch as zs,availableParallelism as Oae,homedir as Bs,hostname as Vs,platform as Hs,tmpdir as Us,userInfo as kae}from"node:os";import{access as Ws,appendFile as Aae,chmod as jae,constants as Gs,glob as Mae,lstat as Ks,mkdir as qs,readFile as Js,readdir as Ys,readlink as Nae,realpath as Xs,rename as Zs,rm as Pae,stat as Qs,unlink as Fae,writeFile as $s}from"node:fs/promises";import{Readable as ec,Transform as Iae,Writable as tc}from"node:stream";import Lae from"crypto";import nc,{createHash as rc,randomUUID as ic,webcrypto as ac}from"node:crypto";import{EventEmitter as oc}from"node:events";import{Worker as Rae}from"node:worker_threads";import*as zae from"zlib";import{Readable as sc}from"stream";import{readdirSync as Bae,statSync as Vae}from"fs";import{spawn as Hae}from"child_process";import{promisify as cc}from"node:util";import{DatabaseSync as lc}from"node:sqlite";import{monitorEventLoopDelay as Uae,performance as uc}from"node:perf_hooks";import{createInterface as Wae}from"node:readline";import{setImmediate as Gae,setTimeout as dc}from"node:timers/promises";import{pipeline as fc}from"node:stream/promises";import{request as Kae}from"node:http";import{Http2ServerRequest as pc,constants as qae}from"node:http2";import{lookup as Jae}from"node:dns/promises";import{request as Yae}from"node:https";import{createBrotliDecompress as Xae,createGunzip as Zae,createInflate as Qae}from"node:zlib";import{join as mc,resolve as $ae}from"path";import*as eoe from"node:querystring";import{Http2ServerRequest as hc,constants as toe}from"http2";import{AsyncLocalStorage as noe}from"node:async_hooks";import{lookup as roe}from"node:dns";import ioe from"node:tls";const aoe=2,gc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},ooe={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},soe={mcp:!0,"desktop-main":!0,cli:!0};function coe(e){return Object.hasOwn(ooe,e)}function loe(e){if(!(e===void 0||e.length===0||Object.hasOwn(soe,e)))return coe(e)?e:`unknown`}function uoe({kind:e,runtimeVersion:t}){return{[gc.protocol]:`2`,[gc.runtime]:t,[gc.kind]:e}}const doe=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),foe=/^={2,}/,_c=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function poe(e,t){return _c.test(e.slice(t,t+512))}function moe(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:_c.exec(e.slice(n,t+1))?.[0].length===t+1-n}const hoe=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,goe=/^!(?=\[)/,_oe=/^\[\^/,voe=/^\]\[[^\]]*\]/,yoe=/^\[\[[^\][|]*\|/,boe=/^#[^\][|]*(?=\]\])/,xoe=/^\]\([^)]*\)/,Soe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,Coe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,woe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function Toe(e,t){let n=e.indexOf(`
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-tZXQYakl.mjs";import{$ as o,$a as s,$c as c,$d as l,$l as u,$n as d,$o as f,$r as p,$s as m,$t as h,$u as g,A as _,Aa as v,Ac as y,Ad as b,Ai as x,Al as S,An as C,Ao as w,Ar as T,As as E,At as D,Au as O,B as k,Ba as A,Bc as j,Bd as ee,Bi as M,Bl as N,Bn as P,Bo as te,Br as ne,Bs as re,Bt as ie,Bu as ae,C as oe,Ca as se,Cc as ce,Cd as F,Ci as le,Cl as ue,Cn as de,Co as fe,Cr as pe,Cs as me,Ct as he,Cu as ge,D as _e,Da as ve,Dc as ye,Dd as be,Di as xe,Dl as Se,Dn as Ce,Do as we,Dr as Te,Ds as Ee,Dt as De,Du as Oe,E as ke,Ed as I,Ei as Ae,El as je,En as Me,Eo as Ne,Er as Pe,Es as Fe,Et as Ie,Eu as Le,Fa as Re,Fd as ze,Fi as Be,Fn as Ve,Fo as He,Fr as Ue,Fs as We,Ft as Ge,Fu as Ke,G as qe,Ga as Je,Gc as Ye,Gd as Xe,Gi as Ze,Gn as Qe,Go as $e,Gr as et,Gs as tt,Gt as nt,Gu as rt,Ha as it,Hc as at,Hd as ot,Hi as st,Hl as ct,Hn as lt,Ho as ut,Hr as dt,Hs as ft,Ht as pt,Hu as mt,I as ht,Ia as gt,Ic as _t,Id as vt,Ii as yt,Il as bt,In as xt,Io as St,Ir as Ct,Is as wt,It as Tt,Iu as Et,J as Dt,Ja as Ot,Jc as kt,Jd as At,Ji as jt,Jn as Mt,Jo as Nt,Jr as Pt,Js as Ft,Jt as It,Ju as Lt,Ka as Rt,Kd as zt,Ki as Bt,Kl as Vt,Kn as Ht,Ko as Ut,Kr as Wt,Ks as Gt,Kt,Ku as qt,L as Jt,La as Yt,Lc as Xt,Ld as Zt,Li as Qt,Ll as $t,Ln as en,Lo as tn,Lr as nn,Ls as rn,Lt as an,Lu as on,Ma as sn,Mc as cn,Md as ln,Mi as un,Mn as dn,Mo as fn,Mr as pn,Ms as mn,Mt as hn,Mu as gn,N as _n,Na as vn,Nc as yn,Nd as L,Ni as bn,Nn as xn,No as Sn,Nr as Cn,Ns as wn,Nt as Tn,Nu as En,Oa as Dn,Oc as eee,Od as On,Oi as kn,Ol as An,On as jn,Oo as Mn,Or as Nn,Os as Pn,Ot as Fn,Ou as In,Pa as Ln,Pc as Rn,Pd as zn,Pi as Bn,Pl as Vn,Pn as Hn,Po as Un,Pr as Wn,Ps as Gn,Pt as Kn,Pu as qn,Q as Jn,Qa as Yn,Qd as Xn,Qi as tee,Ql as Zn,Qn,Qo as $n,Qr as er,Qs as tr,Qt as nr,Qu as rr,Ra as ir,Rc as ar,Rd as or,Ri as sr,Rl as cr,Rn as nee,Ro as ree,Rr as iee,Rs as lr,Rt as ur,Ru as dr,Sa as fr,Sc as pr,Sd as mr,Si as hr,Sl as gr,Sn as _r,So as vr,Sr as yr,Ss as br,St as xr,Su as Sr,T as Cr,Ta as wr,Tc as Tr,Td as Er,Tf as Dr,Ti as Or,Tl as kr,Tn as Ar,To as jr,Tr as Mr,Ts as aee,Tt as Nr,Tu as Pr,Ua as oee,Uc as Fr,Ud as see,Ui as cee,Ul as Ir,Un as lee,Uo as uee,Ur as dee,Us as fee,Ut as pee,Uu as mee,V as Lr,Va as Rr,Vc as hee,Vd as zr,Vi as Br,Vl as Vr,Vn as Hr,Vo as Ur,Vr as Wr,Vs as Gr,Vt as gee,Vu as _ee,Wa as vee,Wd as Kr,Wi as yee,Wl as qr,Wn as bee,Wo as xee,Wr as See,Ws as Cee,Wt as wee,Wu as Tee,Xa as Eee,Xc as Jr,Xd as Yr,Xi as Xr,Xl as Zr,Xn as Dee,Xo as Oee,Xr as kee,Xs as Aee,Xt as Qr,Xu as jee,Ya as $r,Yc as Mee,Yd as Nee,Yi as Pee,Yn as ei,Yo as Fee,Yr as Iee,Ys as Lee,Yt as ti,Yu as Ree,Z as zee,Za as Bee,Zc as ni,Zd as Vee,Zi as ri,Zl as ii,Zn as Hee,Zo as ai,Zr as Uee,Zs as Wee,Zt as oi,Zu as si,_ as Gee,_c as ci,_d as R,_f as li,_i as Kee,_l as qee,_n as ui,_o as Jee,_r as di,_s as Yee,_t as fi,_u as Xee,a as Zee,aa as Qee,ad as $ee,ai as ete,al as tte,an as nte,ao as rte,ar as ite,as as ate,at as pi,au as ote,b as mi,ba as ste,bc as hi,bd as gi,bf as _i,bi as cte,bl as lte,bn as ute,bo as dte,br as fte,bs as pte,bt as vi,bu as yi,c as mte,ca as hte,cc as bi,ci as xi,cl as gte,cn as _te,co as vte,cr as yte,cs as bte,ct as Si,cu as Ci,d as wi,da as xte,dc as Ti,df as Ei,di as Ste,dn as Cte,do as wte,dr as Tte,ds as Ete,dt as Di,du as Oi,ea as Dte,ec as Ote,ed as kte,ei as ki,el as Ate,en as jte,eo as Mte,er as Nte,es as Pte,eu as Fte,fa as Ai,fc as ji,ff as Ite,fi as Lte,fn as Rte,fo as Mi,fr as Ni,fs as Pi,ft as Fi,fu as Ii,g as zte,gc as Bte,gf as Li,gi as Ri,gl as Vte,gn as Hte,go as Ute,gr as zi,gs as Wte,gt as Bi,gu as Gte,h as Kte,ha as qte,hc as Vi,hd as Hi,hf as Jte,hi as Yte,hn as Xte,ho as Ui,hr as Zte,hs as Qte,ht as Wi,hu as $te,ia as Gi,ic as Ki,id as ene,if as qi,ii as tne,il as Ji,in as nne,io as rne,ir as ine,is as ane,it as one,iu as sne,j as cne,ja as lne,jc as une,jd as dne,ji as fne,jn as pne,jo as mne,jr as hne,js as gne,jt as _ne,ju as vne,k as Yi,ka as Xi,kc as Zi,kd as z,ki as yne,kl as bne,kn as xne,ko as Sne,kr as Cne,ks as wne,kt as Tne,ku as Ene,la as Dne,lc as One,ld as kne,li as Ane,ll as jne,ln as Mne,lo as Nne,lr as Pne,ls as Fne,lt as Qi,lu as $i,m as ea,ma as ta,mc as na,md as ra,mi as Ine,ml as Lne,mn as Rne,mo as zne,mr as Bne,ms as Vne,mt as Hne,mu as ia,n as aa,na as Une,nc as Wne,nd as Gne,ni as Kne,nl as qne,nn as Jne,no as Yne,nr as Xne,ns as Zne,nt as Qne,nu as $ne,o as ere,oa,oc as tre,od as nre,of as rre,oi as ire,ol as sa,on as are,oo as ore,or as sre,os as cre,ot as ca,ou as lre,pa as ure,pd as dre,pf as fre,pi as pre,pl as mre,pn as hre,po as gre,pr as _re,ps as vre,pt as yre,pu as bre,q as xre,qa as Sre,qd as Cre,qi as wre,ql as Tre,qn as Ere,qo as Dre,qr as Ore,qt as la,qu as ua,ra as kre,rd as Are,rf as da,ri as jre,rl as fa,rn as Mre,ro as Nre,rr as Pre,rs as Fre,rt as pa,ru as Ire,s as ma,sa as Lre,sc as ha,sd as Rre,sf as ga,si as zre,sl as _a,sn as va,so as Bre,sr as Vre,ss as Hre,st as ya,su as ba,t as xa,ta as Ure,tc as Wre,td as Gre,tf as Sa,ti as Kre,tl as Ca,tn as qre,to as Jre,tr as Yre,ts as Xre,tt as Zre,tu as Qre,ua as wa,uc as Ta,ud as $re,ui as eie,un as tie,uo as nie,ur as rie,us as iie,ut as Ea,uu as aie,v as oie,va as Da,vc as Oa,vd as ka,vf as sie,vi as Aa,vl as cie,vn as ja,vo as lie,vr as uie,vs as die,vt as Ma,vu as Na,w as fie,wa as Pa,wc as Fa,wd as Ia,wi as pie,wl as mie,wn as hie,wo as La,wr as gie,ws as _ie,wt as Ra,wu as za,x as vie,xa as Ba,xc as yie,xd as Va,xf as bie,xi as xie,xl as Sie,xn as Cie,xo as Ha,xr as wie,xs as Tie,xt as Eie,xu as Die,y as Oie,ya as kie,yc as Ua,yd as Aie,yi as jie,yl as Mie,yn as Nie,yo as Pie,yr as Wa,ys as Fie,yt as Iie,yu as Ga,z as Ka,za as qa,zc as Lie,zi as Rie,zl as zie,zn as Ja,zo as Ya,zr as Bie,zs as Vie,zt as Hie,zu as Xa}from"./md-manager-BGnqyqi1-CDSS__qm.mjs";import{c as Za,d as Qa,h as Uie,i as $a,l as eo,n as to,o as no,p as ro,t as io}from"./esm-B3YyV3nD.mjs";import{t as Wie}from"./libesm-DRoEqbAC.mjs";import{t as Gie}from"./yazl-BBz29IQN.mjs";import{t as ao}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as oo,c as Kie,d as qie,f as so,h as Jie,i as co,l as lo,m as uo,n as fo,o as po,p as mo,r as ho,s as go,t as _o,u as vo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as yo,B as bo,C as xo,D as So,E as Yie,F as Xie,H as Zie,I as Qie,L as Co,M as wo,N as To,O as Eo,P as Do,S as $ie,T as eae,V as tae,_ as nae,a as Oo,b as ko,c as Ao,d as jo,f as Mo,g as rae,h as iae,i as No,j as Po,k as Fo,l as Io,m as aae,n as oae,o as Lo,p as Ro,r as zo,s as Bo,t as sae,u as Vo,v as Ho,w as Uo,x as Wo,y as Go,z as Ko}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as qo,r as Jo,t as Yo}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as Xo}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as Zo}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as Qo,t as $o}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as cae,t as lae}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as es,r as ts,t as uae}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as dae,t as ns}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as rs}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as is}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as fae}from"./wrapper-BF8oRx3G.mjs";import{createRequire as as}from"node:module";import{execFile as os,execFileSync as pae,spawn as ss,spawnSync as cs}from"node:child_process";import*as ls from"node:path";import{basename as us,delimiter as ds,dirname as B,extname as fs,isAbsolute as ps,join as V,normalize as ms,parse as mae,posix as hs,relative as H,resolve as U,sep as gs,win32 as _s}from"node:path";import{URLSearchParams as hae,fileURLToPath as vs,pathToFileURL as ys}from"node:url";import*as bs from"node:fs";import{accessSync as gae,appendFileSync as _ae,chmodSync as xs,closeSync as Ss,constants as Cs,cpSync as vae,createReadStream as ws,createWriteStream as Ts,existsSync as W,fchmodSync as yae,fstatSync as bae,linkSync as xae,lstatSync as Es,mkdirSync as Ds,mkdtempSync as Os,openSync as ks,opendirSync as Sae,readFile as Cae,readFileSync as G,readSync as wae,readdirSync as As,readlinkSync as Tae,realpathSync as js,renameSync as Ms,rmSync as Ns,rmdirSync as Ps,statSync as Fs,symlinkSync as Eae,unlinkSync as Is,watch as Dae,writeFileSync as Ls,writeSync as Rs}from"node:fs";import{arch as zs,availableParallelism as Oae,homedir as Bs,hostname as Vs,platform as Hs,tmpdir as Us,userInfo as kae}from"node:os";import{access as Ws,appendFile as Aae,chmod as jae,constants as Gs,glob as Mae,lstat as Ks,mkdir as qs,readFile as Js,readdir as Ys,readlink as Nae,realpath as Xs,rename as Zs,rm as Pae,stat as Qs,unlink as Fae,writeFile as $s}from"node:fs/promises";import{Readable as ec,Transform as Iae,Writable as tc}from"node:stream";import Lae from"crypto";import nc,{createHash as rc,randomUUID as ic,webcrypto as ac}from"node:crypto";import{EventEmitter as oc}from"node:events";import{Worker as Rae}from"node:worker_threads";import*as zae from"zlib";import{Readable as sc}from"stream";import{readdirSync as Bae,statSync as Vae}from"fs";import{spawn as Hae}from"child_process";import{promisify as cc}from"node:util";import{DatabaseSync as lc}from"node:sqlite";import{monitorEventLoopDelay as Uae,performance as uc}from"node:perf_hooks";import{createInterface as Wae}from"node:readline";import{setImmediate as Gae,setTimeout as dc}from"node:timers/promises";import{pipeline as fc}from"node:stream/promises";import{request as Kae}from"node:http";import{Http2ServerRequest as pc,constants as qae}from"node:http2";import{lookup as Jae}from"node:dns/promises";import{request as Yae}from"node:https";import{createBrotliDecompress as Xae,createGunzip as Zae,createInflate as Qae}from"node:zlib";import{join as mc,resolve as $ae}from"path";import*as eoe from"node:querystring";import{Http2ServerRequest as hc,constants as toe}from"http2";import{AsyncLocalStorage as noe}from"node:async_hooks";import{lookup as roe}from"node:dns";import ioe from"node:tls";const aoe=2,gc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},ooe={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},soe={mcp:!0,"desktop-main":!0,cli:!0};function coe(e){return Object.hasOwn(ooe,e)}function loe(e){if(!(e===void 0||e.length===0||Object.hasOwn(soe,e)))return coe(e)?e:`unknown`}function uoe({kind:e,runtimeVersion:t}){return{[gc.protocol]:`2`,[gc.runtime]:t,[gc.kind]:e}}const doe=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),foe=/^={2,}/,_c=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function poe(e,t){return _c.test(e.slice(t,t+512))}function moe(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:_c.exec(e.slice(n,t+1))?.[0].length===t+1-n}const hoe=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,goe=/^!(?=\[)/,_oe=/^\[\^/,voe=/^\]\[[^\]]*\]/,yoe=/^\[\[[^\][|]*\|/,boe=/^#[^\][|]*(?=\]\])/,xoe=/^\]\([^)]*\)/,Soe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,Coe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,woe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function Toe(e,t){let n=e.indexOf(`
2
2
  `,t),r=n===-1?e.length:n;if(r>t&&e[r-1]===`\r`&&--r,r-t>1024)return 0;let i=e.slice(t,r);return i.length===0||!Coe.test(i)&&!woe.test(i)?0:i.length}const vc=/&#(?:x[0-9A-Fa-f]+|X[0-9A-Fa-f]+|[0-9]+);/y;function yc(e,t){if(e[t]!==`&`)return null;let n=t,r=``;for(;;){vc.lastIndex=n;let t=vc.exec(e)?.[0];if(t===void 0)break;let i=Qre(t);if(i===null)break;r+=i,n+=t.length}return n===t?null:{length:n-t,rendered:r}}function bc(e){return e===` `||e===` `||e===`
3
3
  `||e===`\r`||e===`\f`||e===`\v`}function xc(e,t){for(let n=t-1;n>=0;--n){let t=e[n];if(t===`
4
4
  `)return!0;if(t!==` `&&t!==` `)return!1}return!0}function Sc(e,t){let n=e[t];if(n===void 0)return 0;if(xc(e,t)){let n=Toe(e,t);if(n>0)return n}if(n===`|`)return 1;if(n===`<`){let n=hoe.exec(e.slice(t,t+512))?.[0].length;return n===void 0?+!!poe(e,t):n}if(n===`>`&&moe(e,t))return 1;if(n===`=`){let n=foe.exec(e.slice(t,t+3))?.[0].length;if(n!==void 0)return n}if(n===`!`)return+!!goe.test(e.slice(t,t+2));if(doe.has(n))return 1;if(n===`[`){let n=e.slice(t,t+512),r=yoe.exec(n)?.[0].length;return r===void 0?_oe.test(n)?2:1:r}if(n===`#`){let n=boe.exec(e.slice(t,t+512))?.[0].length;if(n!==void 0)return n}if(n===`]`){if(e[t+1]===`]`)return 2;let n=e.slice(t,t+512),r=xoe.exec(n)?.[0].length;if(r!==void 0)return r;let i=voe.exec(n)?.[0].length;return i===void 0?1:i}return xc(e,t)?Soe.exec(e.slice(t,t+32))?.[0].length??0:0}function Eoe(e,t,{syntaxIn:n}){let r=[];if(t.length===0)return r;let i=n===`haystack`;for(let n=0;n<e.length;n+=1){let a=e[n];if(a===void 0||bc(a)||i&&a!==t[0]&&(Sc(e,n)>0||yc(e,n)!==null))continue;let o=n,s=0;for(;o<e.length&&s<t.length;){let n=e[o],r=t[s];if(n===r){o+=1,s+=1;continue}if(bc(r)){s+=1;continue}if(bc(n)){o+=1;continue}let a=i?Sc(e,o):Sc(t,s);if(a>0){i?o+=a:s+=a;continue}let c=i?yc(e,o):yc(t,s);if(c!==null){let n=i?t:e,r=i?s:o,a=!0;for(let e of c.rendered)if(!bc(e)){for(;r<n.length&&bc(n[r]);)r+=1;if(n[r]!==e){a=!1;break}r+=1}if(!a)break;i?(o+=c.length,s=r):(s+=c.length,o=r);continue}break}for(;s<t.length&&bc(t[s]);)s+=1;s===t.length&&r.push({start:n,end:o})}return r}function Cc(e,t,n,r){let i=``,a=Math.max(0,t),o=Math.min(e.length,n);for(;a<o;){let t=e[a];if(bc(t)){a+=1;continue}if(r){let t=Sc(e,a);if(t>0){a+=t;continue}let n=yc(e,a);if(n!==null){for(let e of n.rendered)bc(e)||(i+=e);a+=n.length;continue}}i+=t,a+=1}return i}function Doe(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[e.length-1-r]===t[t.length-1-r];)r+=1;return r}function Ooe(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function wc(e,t,n,{syntaxIn:r,syntaxInContext:i=!1}){let a=n.prefix??``,o=n.suffix??``,s=r===`haystack`,c=0;if(a.length>0){let n=a.length*8+64;c+=Doe(Cc(a,0,a.length,i),Cc(e,t.start-n,t.start,s))}if(o.length>0){let n=o.length*8+64;c+=Ooe(Cc(o,0,o.length,i),Cc(e,t.end,t.end+n,s))}return c}function koe(e,{syntaxInContext:t=!1}={}){let n=Cc(e.prefix??``,0,1/0,t).length+Cc(e.suffix??``,0,1/0,t).length;return Math.min(8,n)}function Aoe(e){return Math.max(e*4,e+64)}function Tc(e,t){let n=e.length,r=t.length,i=0;for(;i<n&&i<r&&e[i]===t[i];)i++;let a=n,o=r;for(;a>i&&o>i&&e[a-1]===t[o-1];)a--,o--;return o<=i?null:{from:i,to:o}}const Ec=`epoch`,Dc=524288,Oc={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},kc=[`incoming`,`outgoing`,`both`];function Ac(e){return kc.includes(e)}const joe=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
@@ -1109,7 +1109,7 @@ ${vW.join(`
1109
1109
  `,`
1110
1110
  `).split(`
1111
1111
  `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=eat(e);for(Zit.lastIndex=0;;){let e=Zit.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var nat=class{contentDir;contentFilter;projectDir;state=T4();fileMeta=new Map;initChain=Promise.resolve();closed=!1;constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.projectDir=e.projectDir}snapshotPath(){return this.projectDir?U(aJ(this.projectDir),`cache`,`tags.json`):null}enqueue(e){let t=this.initChain.then(e);return this.initChain=t.then(()=>void 0,e=>{w4.warn({err:e},`queued tag-index task failed (chain cleared for next task)`)}),t}close(){return this.closed=!0,this.initChain}updateDocumentFromMarkdown(e,t){if(!mG(e))try{let{frontmatter:n,body:r}=ua(t),i=n?Lt(n):``,a=ste(i),o=tat(r),s=new Set([...a,...o]),c=new Set;for(let e of s)for(let t of cne(e))c.add(t);this.applyDocSnapshot(e,s,c)}catch(t){w4.warn({docName:e,err:t},`Failed to scan ${e} for tag extraction`),this.deleteDocument(e)}}deleteDocument(e){if(mG(e))return;let t=this.state.byDoc.get(e);if(t){for(let n of t){let t=this.state.byTag.get(n);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(n))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,n){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,n)}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 n=[];for(let r of t){let t=this.state.byDocLiteral.get(r);if(!t)continue;let i=o(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){return this.enqueue(()=>q2(`tag`,`full`,()=>this.initOnce()))}async initOnce(){if(this.closed||(this.state=T4(),this.fileMeta=new Map,!W(this.contentDir)))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{let[n,r]=await Promise.all([Qs(t),Js(t,`utf-8`)]);return{docName:e,markdown:r,mtimeMs:n.mtimeMs,size:n.size}}catch(t){return w4.warn({docName:e,err:t},`Failed to read ${e} during init`),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown),this.fileMeta.set(e.docName,{mtimeMs:e.mtimeMs,size:e.size})}catch(t){w4.warn({docName:e.docName,err:t},`Failed to index ${e.docName} during init`)}}}loadFromDisk(){return this.enqueue(()=>this.loadOnce())}async loadOnce(){if(this.closed)return!1;let e=this.snapshotPath();if(!e||!W(e))return!1;let t;try{t=await Js(e,`utf-8`)}catch(e){return w4.warn({err:e},`Failed to read tag snapshot; falling back to full rebuild`),!1}let n;try{n=JSON.parse(t)}catch(t){return w4.warn({err:t},`Corrupt tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`malformed`),!1}if(Qit(n))return!1;if(!$it(n))return w4.warn({},`Incomplete tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`incomplete`),!1;this.state=T4(),this.fileMeta=new Map(Object.entries(n.files));for(let[e,t]of Object.entries(n.docs)){if(mG(e))continue;let n=new Set(t),r=new Set;for(let e of n)for(let t of cne(e))r.add(t);this.applyDocSnapshot(e,n,r)}return!0}async discardCorruptSnapshot(e,t){try{await oU(e,{force:!0})}catch(e){w4.warn({reason:t,err:e},`Failed to discard corrupt tag snapshot`)}}saveToDisk(){return this.enqueue(()=>this.saveOnce())}async saveOnce(){if(this.closed)return;let e=this.snapshotPath();if(!e)return;let t={version:1,docs:Object.fromEntries([...this.state.byDocLiteral.entries()].map(([e,t])=>[e,[...t].sort((e,t)=>e.localeCompare(t))])),files:Object.fromEntries(this.fileMeta)};await cU(B(e),{recursive:!0}),await Qx(e,JSON.stringify(t,null,2),{fs:yU})}reconcileWithDisk(){return this.enqueue(()=>q2(`tag`,`reconcile`,()=>this.reconcileOnce(),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted})))}async reconcileOnce(){if(this.closed||!W(this.contentDir))return{added:0,updated:0,deleted:0};let e=await this.listDocsWithPaths(),t=new Set(e.map(e=>e.docName)),n=new Map,r=0,i=0,a=[],o=await Promise.allSettled(e.map(async({docName:e,filePath:t})=>{let n=await Qs(t);return{docName:e,filePath:t,meta:{mtimeMs:n.mtimeMs,size:n.size}}}));for(let e of o){if(e.status===`rejected`)continue;let{docName:t,filePath:r,meta:i}=e.value,o=this.fileMeta.get(t);if(o!==void 0&&o.mtimeMs===i.mtimeMs&&o.size===i.size){n.set(t,i);continue}a.push({docName:t,filePath:r,meta:i,isNew:o===void 0})}for(let e=0;e<a.length;e+=50){let t=a.slice(e,e+50),o=await Promise.allSettled(t.map(async({docName:e,meta:t,isNew:n,filePath:r})=>({docName:e,meta:t,isNew:n,markdown:await Js(r,`utf-8`)})));for(let e of o){if(e.status===`rejected`){w4.warn({err:e.reason},`Failed to reconcile file`);continue}let{docName:t,meta:a,isNew:o,markdown:s}=e.value;this.updateDocumentFromMarkdown(t,s),n.set(t,a),o?r++:i++}}let s=0,c=new Set([...this.fileMeta.keys(),...this.state.byDoc.keys()]);for(let e of c)t.has(e)||(this.deleteDocument(e),s++);return this.fileMeta=n,{added:r,updated:i,deleted:s}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),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)&&(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await Ys(e,{withFileTypes:!0})}catch(t){w4.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=V(e,r.name);if(r.isDirectory()){let e=vG(H(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!KW(r.name))continue;let i=vG(H(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:YW(i),filePath:n})}}};const E4=K(`derived-document-index`);function rat(e){return typeof e==`string`&&Ac(e)}function D4(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}var iat=class extends Error{constructor(){super(`Derived document index is closed`),this.name=`DerivedDocumentIndexClosedError`}};function O4(e){return e instanceof iat}var aat=class extends Error{constructor(){super(`Local-target index is not ready`),this.name=`LocalTargetIndexNotReadyError`}};function oat(e){return e instanceof aat}var sat=class{testOnly;backlinkIndex;tagIndex;localTargetIndex;contentFilter;getGlobalSkillRoots;getLocalTargetInventory;signalChannel;onRecoveredFileTarget;startupAdmission=D4();readyBarrier=D4();tail=Promise.resolve();saveTimer=null;localTargetRebuildRetryTimer=null;localTargetFileExistenceTimer;localTargetRebuildRetryAttempt=0;graphFileTargetsSource=null;graphFileTargets=null;startupBranch=null;graphBuiltWithoutFileOracle=!1;saveTagsOnNextDebounce=!1;branchTransition=null;startupBegun=!1;startupBegunAt=0;startupSettled=!1;ready=!1;liveUpdateToken=0;lastSignaledLocalTargetGeneration=0;closed=!1;closePromise=null;constructor(e){this.backlinkIndex=new f4({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter,getFileOracle:()=>this.graphFileOracle()}),this.tagIndex=new nat({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter}),this.localTargetIndex=new Oit({contentDir:e.contentDir,contentFilter:e.contentFilter}),this.contentFilter=e.contentFilter,this.getGlobalSkillRoots=e.getGlobalSkillRoots,this.getLocalTargetInventory=e.getLocalTargetInventory??(()=>({documentTargets:[],fileTargets:[],folderTargets:[]})),this.signalChannel=e.signalChannel,this.onRecoveredFileTarget=e.onRecoveredFileTarget,this.testOnly={resetDocumentForTest:e=>this.resetDocumentForTest(e),rescanBacklinksForTest:()=>this.rescanBacklinksForTest()},this.localTargetFileExistenceTimer=setInterval(()=>{this.closed||!this.startupSettled||!this.localTargetIndex.isReady()||this.runCommand(async()=>{let e=await this.localTargetIndex.reconcileDependentFileTargetsFromDisk(this.onRecoveredFileTarget);this.maybeSignalLocalTargets(),e>0&&this.signalChannel(`files`)}).catch(e=>{this.closed||E4.warn({err:e},`[local-target] dependent file-existence sweep failed`)})},5e3),this.localTargetFileExistenceTimer.unref?.()}beginStartup(e){if(this.assertOpen(),this.startupBegun)throw Error(`Derived document index startup has already begun`);this.startupBegun=!0,this.startupBegunAt=performance.now(),this.startupBranch=e,this.backlinkIndex.switchBranch(e);let t=Promise.withResolvers(),n=this.initializeBacklinks(e,t.resolve),r=this.warmTags();return this.tail=Promise.all([n.then(()=>void 0),r]).then(()=>void 0),this.startupAdmission.resolve(),{backlinksReady:n,offlineDeletionsReady:t.promise}}async settleStartupAfterWatcherSeed(){if(this.assertOpen(),!this.startupBegun)throw Error(`Derived document index startup has not begun`);if(this.startupSettled)throw Error(`Derived document index startup has already settled`);this.startupSettled=!0;try{return await this.enqueueInternal(async()=>{let e=!1;try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&E4.info(e,`[tag-index] startup reconcile: offline changes applied`),await this.saveTagsLogOnly(`startup`)}catch(t){E4.error({err:t},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),e=!0}return await this.rebuildLocalTargets(`startup`)&&this.syncLocalTargetBaseline(),this.startupBranch!==null&&await this.reconcileGraphWithFileInventory(this.startupBranch),{tagIndexDegraded:e}})}finally{this.ready=!0,this.readyBarrier.resolve();let e=Math.round(performance.now()-this.startupBegunAt);(e>=1e4?E4.info:E4.debug).call(E4,{startupMs:e},`[derived-index] startup settled; deferred link checks resume`)}}async beginBranchSwitch(e){if(this.assertOpen(),this.branchTransition)throw Error(`Derived document index branch switch already active`);let t={branch:e,barrier:D4()};this.liveUpdateToken++,this.branchTransition=t,this.cancelScheduledSave();try{return await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),await this.enqueueInternal(async()=>{this.backlinkIndex.switchBranch(e)}),t}catch(e){throw this.releaseBranchTransition(t),e}}async settleBranchFromDisk(e){if(this.assertOpen(),this.branchTransition!==e)throw Error(`No derived document index branch switch is active`);try{await this.enqueueInternal(async()=>{let t=e.branch;if(await this.backlinkIndex.loadFromDisk(t)){let e=await this.backlinkIndex.reconcileWithDisk(t);(e.added>0||e.updated>0||e.deleted>0)&&E4.info(e,`[backlinks] branch-switch reconcile for ${t}`)}else await this.backlinkIndex.rebuildFromDisk(t);let n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),t)}catch(e){n=!0,r=e}await this.saveBacklinksLogOnly(`branch-switch`,t);try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&E4.info(e,`[tag-index] branch-switch reconcile for ${t}`)}catch(e){E4.warn({err:e,branch:t},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await this.tagIndex.init()}if(await this.saveTagsLogOnly(`branch-switch`),await this.rebuildLocalTargets(`branch-switch`)&&this.syncLocalTargetBaseline(),n)throw r})}finally{this.releaseBranchTransition(e)}}abortBranchSwitch(e){e&&this.releaseBranchTransition(e)}captureLiveUpdateToken(){return this.closed?null:this.liveUpdateToken}recordLiveDocument(e,t,n){return this.closed||n!==this.liveUpdateToken?Promise.resolve():this.runCommand(async()=>{n===this.liveUpdateToken&&(this.updateBoth(e,t),this.signalAllRelations())})}recordDurableStore(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1)})}recordDiskUpsert(e,t){return this.runCommand(async()=>{this.updateBoth(e,t),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskDelete(e){return this.runCommand(async()=>{this.deleteBoth(e),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskRename(e,t,n){return this.runCommand(async()=>{this.renameBoth(e,t,n),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordInventoryReconciled(){return this.runCommand(async()=>{this.reconcileLocalTargetInventory(),this.maybeSignalLocalTargets()})}recordFileTargetUpsert(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||!t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!0),this.maybeSignalLocalTargets()})}recordFileTargetDelete(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!1),this.maybeSignalLocalTargets()})}recordDirectDocument(e,t){return this.recordDirectMutations([{kind:`upsert`,documentName:e,markdown:t}])}recordDirectDelete(e){return this.recordDirectMutations([{kind:`delete`,documentName:e}])}recordDirectRename(e,t,n){return this.recordDirectMutations([{kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:n}])}recordLinkRewrite(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1),this.signalBacklinks()})}recordDirectMutations(e){return e.length===0?Promise.resolve():this.runCommand(async()=>{let t=!1;for(let n of e)switch(n.kind){case`upsert`:this.updateBoth(n.documentName,n.markdown),t=!0;break;case`delete`:this.deleteBoth(n.documentName),t=!0;break;case`rename`:this.renameBoth(n.oldDocumentName,n.newDocumentName,n.markdown),t=!0;break;case`link-rewrite`:this.updateBacklinks(n.documentName,n.markdown)}t?(this.reconcileLocalTargetInventory(),await this.saveBothLogOnly(`direct-batch`),this.signalAllRelations()):(await this.saveBacklinksLogOnly(`direct-batch`),this.signalBacklinks())})}refreshGlobalSkillNodes(){return this.runCommand(async()=>{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots()),this.reconcileLocalTargetInventory(),this.signalBacklinks()})}refreshContentScope(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch(),t=await this.backlinkIndex.reconcileWithDisk(e),n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(e){n=!0,r=e}await this.tagIndex.reconcileWithDisk(),this.reconcileLocalTargetInventory();for(let{docName:e,filePath:n}of t.changedDocs)try{this.localTargetIndex.setSource(e,await Js(n,`utf-8`))}catch{this.localTargetIndex.removeSource(e)}for(let e of t.deletedDocNames)this.localTargetIndex.removeSource(e);if(await this.saveBothLogOnly(`content-filter`,e),this.signalAllRelations(),n)throw r})}announceReadyViews(){this.assertOpen(),this.signalAllRelations()}isReady(){return this.ready&&!this.closed}getBacklinks(e){return this.runQuery(()=>this.backlinkIndex.getBacklinks(e))}getBacklinkCount(e){return this.runQuery(()=>this.backlinkIndex.getBacklinkCount(e))}getBacklinkCounts(e){return this.runQuery(()=>Object.fromEntries(e.map(e=>[e,this.backlinkIndex.getBacklinkCount(e)])))}getForwardLinkEntries(e){return this.runQuery(()=>this.backlinkIndex.getForwardLinkEntries(e))}getLinkGraphNeighborhood(e,t){return this.runQuery(()=>this.backlinkIndex.getLinkGraphNeighborhood(e,t))}getLinkGraph(){return this.runQuery(()=>this.backlinkIndex.getLinkGraph())}getHubs(e){return this.runQuery(()=>this.backlinkIndex.getHubs(e))}getOrphans(e,t){return this.runQuery(()=>this.backlinkIndex.getOrphans(e,t))}getDeadLinks(e,t){return this.runQuery(()=>this.backlinkIndex.getDeadLinks(e,t,void 0,this.getLocalTargetInventory()?.folderTargets))}getIndexedDocNames(){return this.runQuery(()=>this.backlinkIndex.getIndexedDocNames())}getRenameSourceInventory(){return this.runQuery(()=>this.backlinkIndex.getRenameSourceInventory())}getAllTags(){return this.runQuery(()=>this.tagIndex.getAllTags())}getDocsForTagWithMatches(e){return this.runQuery(()=>this.tagIndex.getDocsForTagWithMatches(e))}getLocalTargetAssessments(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessments(e))}getLocalTargetAssessmentsForSources(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessmentsForSources(e))}getLocalTargetGeneration(){return this.runLocalTargetQuery(()=>this.localTargetIndex.generation)}readLocalTargetGeneration(){return this.localTargetIndex.freshnessToken}getLocalTargetStats(){return this.runLocalTargetQuery(()=>this.localTargetIndex.getStats())}getLocalTargetDocumentDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getDocumentDependents(e))}getLocalTargetFileDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getFileDependents(e))}close(){if(this.closePromise)return this.closePromise;let e=this.cancelScheduledSave();return e!==null&&this.enqueueInternal(()=>this.saveScheduledCache(e,`close-flush`)),this.closed=!0,clearInterval(this.localTargetFileExistenceTimer),this.cancelLocalTargetRebuildRetry(),this.localTargetIndex.close(),this.startupAdmission.resolve(),this.readyBarrier.resolve(),this.releaseBranchTransition(this.branchTransition),this.closePromise=this.tail.then(()=>this.tagIndex.close()).then(()=>void 0,()=>void 0),this.closePromise}resetDocumentForTest(e){return this.runCommand(async()=>{this.deleteBoth(e),await this.saveBothLogOnly(`test-reset`),this.signalAllRelations()})}rescanBacklinksForTest(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch();await this.backlinkIndex.rebuildFromDisk(e),await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e),this.reconcileLocalTargetInventory(),await this.saveBacklinksLogOnly(`test-rescan`,e),this.signalBacklinks()})}async initializeBacklinks(e,t){try{if(this.graphFileOracle(),await this.backlinkIndex.loadFromDisk(e)){let n=await this.backlinkIndex.reconcileWithDisk(e);t(n.deletedDocNames),(n.added>0||n.updated>0||n.deleted>0)&&E4.info({added:n.added,updated:n.updated,deleted:n.deleted},`[backlinks] startup reconcile`)}else t([]),await this.backlinkIndex.rebuildFromDisk(e);return await this.ingestGlobalSkillNodesLogOnly(e,`startup`),await this.saveBacklinksLogOnly(`startup`,e),{backlinkIndexDegraded:!1}}catch(n){return t([]),E4.error({err:n,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`),{backlinkIndexDegraded:!0}}}async warmTags(){try{await this.tagIndex.loadFromDisk()?await this.tagIndex.reconcileWithDisk():await this.tagIndex.init()}catch(e){E4.warn({err:e},`[derived-document-index] tag-index warm boot failed; continuing with stale or empty index`)}}updateBoth(e,t){this.updateBacklinks(e,t),this.isAdmitted(e)?this.tagIndex.updateDocumentFromMarkdown(e,t):this.tagIndex.deleteDocument(e)}updateBacklinks(e,t){this.isAdmitted(e)?(this.backlinkIndex.updateDocumentFromMarkdown(e,t),this.localTargetIndex.setSource(e,t)):(this.backlinkIndex.deleteDocument(e),this.localTargetIndex.removeSource(e))}deleteBoth(e){this.backlinkIndex.deleteDocument(e),this.tagIndex.deleteDocument(e),this.localTargetIndex.removeSource(e)}renameBoth(e,t,n){this.isAdmitted(t)?(this.backlinkIndex.renameDocument(e,t,n),this.tagIndex.renameDocument(e,t,n),this.localTargetIndex.renameSource(e,t,n)):(this.backlinkIndex.deleteDocument(e),this.backlinkIndex.deleteDocument(t),this.tagIndex.deleteDocument(e),this.tagIndex.deleteDocument(t),this.localTargetIndex.removeSource(e),this.localTargetIndex.removeSource(t))}isAdmitted(e){return mG(e)?!1:lG(e)?!0:!this.contentFilter.isExcluded(iG(e))}signalBacklinks(){this.signalChannel(`backlinks`),this.signalChannel(`graph`),this.maybeSignalLocalTargets()}signalAllRelations(){this.signalBacklinks(),this.signalChannel(`tags`)}maybeSignalLocalTargets(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t!==0&&(Qrt(`local-target`,`signal`,t),this.lastSignaledLocalTargetGeneration=e,this.signalChannel(`local-targets`))}graphFileOracle(){let e=this.getLocalTargetInventory();if(!e){this.graphBuiltWithoutFileOracle=!0;return}this.graphFileTargetsSource!==e.fileTargets&&(this.graphFileTargetsSource=e.fileTargets,this.graphFileTargets=Si(`file`,e.fileTargets));let t=this.graphFileTargets;return t?{hasFile:e=>t.resolve(e)!==void 0}:void 0}async reconcileGraphWithFileInventory(e){if(this.graphBuiltWithoutFileOracle&&this.graphFileOracle()){this.graphBuiltWithoutFileOracle=!1;try{await this.backlinkIndex.rebuildFromDisk(e),await this.saveBacklinksLogOnly(`file-inventory-reconcile`,e),this.signalChannel(`backlinks`),this.signalChannel(`graph`)}catch(t){this.graphBuiltWithoutFileOracle=!0,E4.warn({err:t,branch:e},`[backlinks] file-inventory reconciliation failed; graph retains its startup extraction`)}}}async rebuildLocalTargets(e){try{let t=this.getLocalTargetInventory();if(t===null)return this.localTargetIndex.markUnavailable(),E4.warn({reason:e},`[local-target] watcher inventory unavailable; index remains not ready`),!1;let n={documentTargets:new Set([...this.backlinkIndex.getIndexedDocNames(),...t.documentTargets]),fileTargets:t.fileTargets};return await this.localTargetIndex.rebuildFromDisk(n),this.localTargetRebuildRetryAttempt=0,this.cancelLocalTargetRebuildRetry(),!0}catch(t){return E4.warn({err:t,reason:e},`[local-target] rebuild failed; retaining the last complete snapshot and scheduling recovery`),this.scheduleLocalTargetRebuildRetry(e),!1}}reconcileLocalTargetInventory(){let e=this.getLocalTargetInventory();return e===null?(this.localTargetIndex.markUnavailable(),null):(this.localTargetIndex.reconcileDocumentTargets(new Set([...this.backlinkIndex.getIndexedDocNames(),...e.documentTargets])),this.localTargetIndex.reconcileFileTargets(e.fileTargets),this.localTargetIndex.reconcileFolderTargets(e.folderTargets),e)}syncLocalTargetBaseline(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t>0&&Qrt(`local-target`,`baseline`,t),this.lastSignaledLocalTargetGeneration=e}scheduleLocalTargetRebuildRetry(e){if(this.closed||this.localTargetRebuildRetryTimer!==null)return;let t=Math.min(1e3*2**this.localTargetRebuildRetryAttempt,3e4);this.localTargetRebuildRetryAttempt++,this.localTargetRebuildRetryTimer=setTimeout(()=>{this.localTargetRebuildRetryTimer=null,this.runCommand(async()=>{await this.rebuildLocalTargets(`retry:${e}`)&&this.maybeSignalLocalTargets()}).catch(t=>{this.closed||E4.warn({err:t,reason:e},`[local-target] recovery enqueue failed`)})},t),this.localTargetRebuildRetryTimer.unref?.()}cancelLocalTargetRebuildRetry(){this.localTargetRebuildRetryTimer!==null&&(clearTimeout(this.localTargetRebuildRetryTimer),this.localTargetRebuildRetryTimer=null)}scheduleSave(e=!0){let t=this.saveTagsOnNextDebounce||e;this.cancelScheduledSave(),this.saveTagsOnNextDebounce=t,this.saveTimer=setTimeout(()=>{this.saveTimer=null;let e=this.saveTagsOnNextDebounce;this.saveTagsOnNextDebounce=!1,this.enqueueInternal(()=>this.saveScheduledCache(e,`debounced`)).catch(e=>{E4.warn({err:e},`Failed to enqueue debounced derived-index cache save`)})},2e3)}cancelScheduledSave(){let e=this.saveTimer===null?null:this.saveTagsOnNextDebounce;return this.saveTimer!==null&&clearTimeout(this.saveTimer),this.saveTimer=null,this.saveTagsOnNextDebounce=!1,e}saveScheduledCache(e,t){return e?this.saveBothLogOnly(t):this.saveBacklinksLogOnly(`${t}-backlinks`)}releaseBranchTransition(e){let t=this.branchTransition;!e||t!==e||(this.branchTransition=null,t.barrier.resolve())}async saveBothLogOnly(e,t){await this.saveBacklinksLogOnly(e,t),await this.saveTagsLogOnly(e)}async saveBacklinksLogOnly(e,t){try{await this.backlinkIndex.saveToDisk(t)}catch(n){E4.warn({err:n,reason:e,branch:t},`Failed to persist backlink cache`)}}async saveTagsLogOnly(e){try{await this.tagIndex.saveToDisk()}catch(t){E4.warn({err:t,reason:e},`Failed to persist tag snapshot`)}}async ingestGlobalSkillNodesLogOnly(e,t){try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(n){E4.warn({err:n,branch:e,reason:t},`Global skill bundle ingest failed`)}}async runCommand(e){return this.assertOpen(),await this.startupAdmission.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}async runQuery(e){return this.assertOpen(),await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}runLocalTargetQuery(e){return this.runQuery(()=>{if(!this.localTargetIndex.isReady())throw new aat;return e()})}async enqueueAfterBranchAdmission(e){for(;;){let t=this.branchTransition;if(!t)return this.assertOpen(),this.enqueueInternal(()=>(this.assertOpen(),e()));await t.barrier.promise,this.assertOpen()}}enqueueInternal(e){let t=this.tail.then(e);return this.tail=t.then(()=>void 0,e=>{O4(e)?E4.debug({err:e},`Derived document index operation rejected after close`):E4.warn({err:e},`Derived document index operation failed; queue remains available`)}),t}assertOpen(){if(this.closed)throw new iat}};function cat(e){throw Error(`[StorePublishOutcome] unhandled variant: ${JSON.stringify(e)}`)}const k4=18e5;function lat(e){return e.reduce((e,t)=>Math.min(e,t.at+k4),1/0)}function A4(e){let t=[`{"version":1,"branches":{`];for(let[n,r]of Object.entries(Object.fromEntries(e))){t.length>1&&t.push(`,`),t.push(JSON.stringify(n),`:[`);for(let[e,n]of r.entries())e>0&&t.push(`,`),t.push(n);t.push(`]`)}return t.push(`}}`),t}function uat(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function dat(e,t){let n;try{n=t instanceof Error?String(t.message):String(t)}catch{n=`unserializable rejection reason`}console.warn(JSON.stringify({event:`persistence-store-publish-async-rejected`,"doc.name":e.docName,generation:e.generation,error:n}))}function fat(e,t){return e?.docName===t?.docName&&e?.file===t?.file&&e?.diskHash===t?.diskHash&&e?.diskContent===t?.diskContent&&e?.retainedContent===t?.retainedContent&&e?.detectedAt===t?.detectedAt}var j4=class extends Error{kind;path;constructor(e,t,n){let r=n instanceof Error&&`code`in n&&typeof n.code==`string`?n.code:void 0,i=t===`unreadable`?r===`EACCES`||r===`EPERM`?`Check the snapshot and parent-directory permissions for the account running OpenKnowledge, then retry.`:r===`EISDIR`?`The snapshot path must be a regular file, not a directory. Preserve that directory and restore the snapshot file to this path.`:`Check the filesystem or mount and restore read access to this path, then retry.`:t===`incompatible`?`This build does not support the snapshot schema. Preserve the file and restore a compatible backup or contact support to identify a compatible build.`:`Restore this snapshot from a known-good backup, or contact support to recover its protected edits.`;super(`Cannot safely open this project: its stale-write recovery snapshot is ${t}${r?` [${r}]`:``} (${e}). The snapshot has been preserved because it may contain the only copy of protected edits. ${i} Run ok bug-report from the project directory to collect diagnostics without starting the server. Do not delete it to bypass recovery.`,{cause:n}),this.name=`DocumentDurabilityStateError`,this.kind=t,this.path=e}};function M4(e,t,n){n===void 0?e.delete(t):e.set(t,n)}function pat(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.hash==`string`&&typeof t.at==`number`}function mat(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.file==`string`&&typeof t.diskHash==`string`&&typeof t.diskContent==`string`&&typeof t.detectedAt==`string`&&(t.retainedContent===void 0||typeof t.retainedContent==`string`)}function hat(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.version!==1||!t.branches||typeof t.branches!=`object`||Array.isArray(t.branches))return null;let n=new Map;for(let[e,r]of Object.entries(t.branches)){if(!Array.isArray(r))return null;let t=[];for(let e of r){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.docName!=`string`||typeof n.acknowledgedContent!=`string`||!Array.isArray(n.displacedVersions)||!n.displacedVersions.every(pat)||n.staleExternalWrite!==void 0&&(!mat(n.staleExternalWrite)||n.staleExternalWrite.docName!==n.docName||n.staleExternalWrite.diskHash!==PY(n.staleExternalWrite.diskContent)))return null;t.push({docName:n.docName,acknowledgedContent:n.acknowledgedContent,displacedVersions:n.displacedVersions,...n.staleExternalWrite?{staleExternalWrite:n.staleExternalWrite}:{}})}n.set(e,t)}return{version:1,branches:Object.fromEntries(n)}}var N4=class{reconciledBaseByBranch=new Map;displacedVersionsByBranch=new Map;staleExternalWritesByBranch=new Map;inFlightFlushByDoc=new Map;storeAttemptGenerations=new Map;publishedStoreGenerations=new Map;documentsWithPublishInFlight=new Set;agentWriteStores=new Set;refusedStoreDocNames=new Set;storeFailures=new Map;storeDivergences=new Set;staleExternalWriteFreezes=new Set;persistencePath;fileForDocName;onStaleExternalWriteChange;onStoreRefused;hasResolvedExtension;cachedDocumentsByBranch=new Map;lastPersistedParts=A4(new Map);nextDisplacedExpiryAt=1/0;activeBranch;batchInProgress=!1;constructor(e=`main`,t={}){this.activeBranch=e,this.persistencePath=t.persistencePath,this.fileForDocName=t.fileForDocName??(e=>`${e}.md`),this.onStaleExternalWriteChange=t.onStaleExternalWriteChange,this.onStoreRefused=t.onStoreRefused,this.hasResolvedExtension=t.hasResolvedExtension,this.reconciledBaseByBranch.set(e,new Map),this.restore()}switchReconciledBaseScope(e){this.persist(),this.activeBranch=e,this.reconciledBaseByBranch.has(e)||this.reconciledBaseByBranch.set(e,new Map)}getActiveBranch(){return this.activeBranch}getReconciledBase(e){return this.reconciledBaseByBranch.get(this.activeBranch)?.get(e)}setReconciledBase(e,t){let n=this.reconciledBaseByBranch.get(this.activeBranch);if(n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n)),!(n.get(e)===t&&Date.now()<this.nextDisplacedExpiryAt)){if(!this.isPersistedDocument(e)){n.set(e,t);return}this.mutateDocument(e,()=>n.set(e,t))}}recordSuccessfulStore(e,t,n){if(n===void 0){this.setReconciledBase(e,t);return}let r=Date.now(),i=PY(n);this.mutateDocument(e,()=>{let n=this.reconciledBaseByBranch.get(this.activeBranch);n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n));let a=this.displacedVersionsByBranch.get(this.activeBranch);a||(a=new Map,this.displacedVersionsByBranch.set(this.activeBranch,a));let o=(a.get(e)??[]).filter(e=>e.at>r-18e5&&e.hash!==i);o.push({hash:i,at:r}),n.set(e,t),a.set(e,o.slice(-8))})}deleteReconciledBase(e){this.refusedStoreDocNames.delete(e),this.storeFailures.delete(e);let t=this.isPersistedDocument(e);if(!t){this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e);return}this.mutateDocument(e,()=>{this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e),this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e),this.staleExternalWritesByBranch.get(this.activeBranch)?.delete(e)},t)}freshDisplacedVersions(e){let t=this.displacedVersionsByBranch.get(this.activeBranch),n=t?.get(e);if(!t||!n)return[];let r=Date.now()-k4,i=n.filter(e=>e.at>r);return i.length===n.length?n:(this.mutateDocument(e,()=>{i.length===0?t.delete(e):t.set(e,i)}),i)}recordDisplacedVersion(e,t){let n=PY(t),r=this.freshDisplacedVersions(e).filter(e=>e.hash!==n);r.push({hash:n,at:Date.now()});let i=this.displacedVersionsByBranch.get(this.activeBranch);i||(i=new Map,this.displacedVersionsByBranch.set(this.activeBranch,i)),this.mutateDocument(e,()=>i.set(e,r.slice(-8)))}clearDisplacedVersions(e){this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)&&this.mutateDocument(e,()=>this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e))}isDisplacedVersion(e,t){let n=this.freshDisplacedVersions(e);if(n.length===0)return!1;let r=PY(t);return n.some(e=>e.hash===r)}recordStaleExternalWrite(e,t,n){let r=this.staleExternalWritesByBranch.get(this.activeBranch);r||(r=new Map,this.staleExternalWritesByBranch.set(this.activeBranch,r));let i=PY(t),a=r.get(e);if(a?.diskHash===i&&(n===void 0||n===a.retainedContent))return a;let o=a?.diskHash!==i,s=n??a?.retainedContent,c={docName:e,file:this.fileForDocName(e),diskHash:i,diskContent:t,...s===void 0?{}:{retainedContent:s},detectedAt:a?.diskHash===i?a.detectedAt:new Date().toISOString()};return this.mutateDocument(e,()=>r.set(e,c)),o&&zYe(),c}staleExternalWriteMatches(e,t){let n=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return n!==void 0&&n.diskHash===PY(t)}listStaleExternalWrites(){return[...this.staleExternalWritesByBranch.get(this.activeBranch)?.values()??[]].map(e=>this.withResolvedFile(e))}getStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return t===void 0?void 0:this.withResolvedFile(t)}withResolvedFile(e){if(this.hasResolvedExtension&&!this.hasResolvedExtension(e.docName))return e;let t=this.fileForDocName(e.docName);return t===e.file?e:{...e,file:t}}clearStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch);t?.get(e)&&this.mutateDocument(e,()=>t?.delete(e))}restoreStaleExternalWrite(e,t){let n=this.staleExternalWritesByBranch.get(t);n||(n=new Map,this.staleExternalWritesByBranch.set(t,n)),!n.has(e.docName)&&this.mutateDocument(e.docName,()=>n.set(e.docName,e))}mutateDocument(e,t,n=!0){let r=this.reconciledBaseByBranch.get(this.activeBranch)??new Map,i=this.displacedVersionsByBranch.get(this.activeBranch)??new Map,a=this.staleExternalWritesByBranch.get(this.activeBranch)??new Map,o=r.get(e),s=i.get(e),c=a.get(e),l=this.inFlightFlushByDoc.get(e),u;try{u=t(),n&&this.persist()}catch(t){throw M4(r,e,o),M4(i,e,s),M4(a,e,c),M4(this.inFlightFlushByDoc,e,l),this.reconciledBaseByBranch.set(this.activeBranch,r),this.displacedVersionsByBranch.set(this.activeBranch,i),this.staleExternalWritesByBranch.set(this.activeBranch,a),t}return c!==a.get(e)&&this.onStaleExternalWriteChange?.(),u}isPersistedDocument(e){return this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)===!0||this.staleExternalWritesByBranch.get(this.activeBranch)?.has(e)===!0}restore(){if(!this.persistencePath)return;let e;try{e=G(this.persistencePath,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw new j4(this.persistencePath,`unreadable`,e)}let t;try{t=JSON.parse(e)}catch(e){throw new j4(this.persistencePath,`corrupt`,e)}if(t&&typeof t==`object`&&`version`in t&&t.version!==1)throw new j4(this.persistencePath,`incompatible`);let n=hat(t);if(!n)throw new j4(this.persistencePath,`corrupt`);let r=Date.now()-k4,i=new Map;for(let[e,t]of Object.entries(n.branches)){let n=new Map,a=new Map,o=new Map,s=new Map,c=[];for(let e of t){if(e.staleExternalWrite)try{this.fileForDocName(e.docName)}catch(e){throw new j4(this.persistencePath,`corrupt`,e)}let t=JSON.stringify(e);c.push(t);let i=lat(e.displacedVersions);this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,i);let l=e.displacedVersions.filter(e=>e.at>r);l.length===0&&!e.staleExternalWrite||(n.set(e.docName,e.acknowledgedContent),l.length>0&&a.set(e.docName,l),e.staleExternalWrite&&o.set(e.docName,e.staleExternalWrite),l.length===e.displacedVersions.length&&s.set(e.docName,{acknowledgedContent:e.acknowledgedContent,displacedVersions:a.get(e.docName),staleExternalWrite:e.staleExternalWrite?{...e.staleExternalWrite}:void 0,expiresAt:i,serialized:t}))}i.set(e,c),this.reconciledBaseByBranch.set(e,n),a.size>0&&this.displacedVersionsByBranch.set(e,a),o.size>0&&this.staleExternalWritesByBranch.set(e,o),s.size>0&&this.cachedDocumentsByBranch.set(e,s)}this.reconciledBaseByBranch.has(this.activeBranch)||this.reconciledBaseByBranch.set(this.activeBranch,new Map),this.lastPersistedParts=A4(i)}pruneExpiredDisplacedVersions(e){this.nextDisplacedExpiryAt=1/0;for(let[t,n]of this.displacedVersionsByBranch){for(let[t,r]of n){let i=r.filter(t=>t.at>e);i.length===0?n.delete(t):i.length!==r.length&&n.set(t,i);for(let e of i)this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,e.at+k4)}n.size===0&&this.displacedVersionsByBranch.delete(t)}}persist(){let e=Date.now()-k4;if(!this.persistencePath){this.pruneExpiredDisplacedVersions(e);return}let t=new Map,n=new Map,r=new Set([...this.displacedVersionsByBranch.keys(),...this.staleExternalWritesByBranch.keys()]);for(let i of r){let r=new Set([...this.displacedVersionsByBranch.get(i)?.keys()??[],...this.staleExternalWritesByBranch.get(i)?.keys()??[]]),a=[],o=new Map;for(let t of r){let n=this.reconciledBaseByBranch.get(i)?.get(t);if(n===void 0)continue;let r=this.displacedVersionsByBranch.get(i)?.get(t),s=this.staleExternalWritesByBranch.get(i)?.get(t),c=this.cachedDocumentsByBranch.get(i)?.get(t);if(c&&c.acknowledgedContent===n&&c.displacedVersions===r&&fat(c.staleExternalWrite,s)&&c.expiresAt>e+18e5){a.push(c.serialized),o.set(t,c);continue}let l=(r??[]).filter(t=>t.at>e);if(l.length===0&&!s)continue;let u={docName:t,acknowledgedContent:n,displacedVersions:l,...s?{staleExternalWrite:s}:{}},d=JSON.stringify(u);a.push(d),o.set(t,{acknowledgedContent:n,displacedVersions:r,staleExternalWrite:s?{...s}:void 0,expiresAt:lat(l),serialized:d})}a.length>0&&(t.set(i,a),n.set(i,o))}let i=A4(t);if(i.length===this.lastPersistedParts.length&&i.every((e,t)=>e===this.lastPersistedParts[t])){this.cachedDocumentsByBranch=n,this.pruneExpiredDisplacedVersions(e);return}let a=i.join(``);dU(B(this.persistencePath),{recursive:!0});let o=Xx(this.persistencePath);try{lU(o,a,{encoding:`utf-8`,mode:384,flag:`wx`}),fU(o,this.persistencePath),this.lastPersistedParts=i,this.cachedDocumentsByBranch=n}catch(e){try{W(o)&&mU(o)}catch(t){K(`document-durability-state`).warn({err:t,writeError:e instanceof Error?e.message:String(e),temporaryPath:o},`Unable to remove failed recovery snapshot temporary file`)}throw e}this.pruneExpiredDisplacedVersions(e)}freshInFlightFlushes(e){let t=this.inFlightFlushByDoc.get(e);if(!t)return[];let n=Date.now(),r=t.filter(e=>n-e.at<=6e4);return r.length===t.length?t:(eZe(t.length-r.length),r.length===0?this.inFlightFlushByDoc.delete(e):this.inFlightFlushByDoc.set(e,r),r)}beginInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);n.push({value:t,at:Date.now()}),this.inFlightFlushByDoc.set(e,n)}peekInFlightFlush(e){let t=this.freshInFlightFlushes(e);return t[t.length-1]?.value}inFlightFlushCount(e){return this.freshInFlightFlushes(e).length}hasInFlightFlush(e,t){return this.freshInFlightFlushes(e).some(e=>e.value===t)}finishInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);for(let r=n.length-1;r>=0;r--)if(n[r]?.value===t){n.splice(r,1),n.length===0&&this.inFlightFlushByDoc.delete(e);return}}beginStoreAttempt(e){let t=(this.storeAttemptGenerations.get(e)??0)+1;return this.storeAttemptGenerations.set(e,t),{docName:e,generation:t}}tryPublishStore(e,t){if(this.documentsWithPublishInFlight.has(e.docName))return`reentrant`;let n=this.publishedStoreGenerations.get(e.docName)??0;if(e.generation<=n)return`stale`;this.documentsWithPublishInFlight.add(e.docName);try{let n=t();if(uat(n)){try{n.then(()=>{},t=>dat(e,t))}catch{}throw TypeError(`tryPublishStore: the publish callback must complete synchronously, but it returned a thenable (${e.docName} generation ${e.generation})`)}return this.publishedStoreGenerations.set(e.docName,e.generation),`published`}finally{this.documentsWithPublishInFlight.delete(e.docName)}}setBatchInProgress(e){this.batchInProgress=e}isBatchInProgress(){return this.batchInProgress}markAgentWriteStore(e){this.agentWriteStores.add(e)}consumeAgentWriteStore(e){return this.agentWriteStores.delete(e)}markStoreRefused(e){this.refusedStoreDocNames.add(e),this.onStoreRefused?.(e)}clearStoreRefused(e){this.refusedStoreDocNames.delete(e)}isStoreRefused(e){return this.refusedStoreDocNames.has(e)}getRefusedStoreDocNames(){return[...this.refusedStoreDocNames]}recordStoreFailure(e,t){this.storeFailures.set(e,t)}clearStoreFailure(e){this.storeFailures.delete(e)}takeStoreFailure(e){let t=this.storeFailures.get(e)??null;return this.storeFailures.delete(e),t}recordStoreDivergence(e){this.storeDivergences.add(e)}takeStoreDivergence(e){return this.storeDivergences.delete(e)}recordStaleExternalWriteFreeze(e){this.staleExternalWriteFreezes.add(e)}takeStaleExternalWriteFreeze(e){return this.staleExternalWriteFreezes.delete(e)}};const P4=3000000000n,gat=()=>BigInt(Date.now())*1000000n,F4=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,I4=(e,t)=>e.ctimeNs+P4>t||e.mtimeNs+P4>t&&e.mtimeNs<=t+P4,_at=/^[ -~]*$/,vat=new Map,L4=new Map;function yat(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function bat(e){let t=gat();try{let n=Fs(e,{bigint:!0});return{signature:F4(n),racy:I4(n,t)}}catch(e){if(e.code===`ENOENT`)return null;throw e}}function xat(e){let t=new Set;for(let n of e){let e=n;for(;e!==``&&!t.has(e);)t.add(e),e=yat(e)}return t}async function Sat(e,t,n){let r=U(t),i=vat.get(r);i===void 0&&(i=U(r,(await e.raw(`rev-parse`,`--git-path`,`index`)).trim()),vat.set(r,i));let a=bat(i);if(a===null)return L4.delete(r),!1;let o=yat(n),s=L4.get(r),c=!a.racy&&_at.test(n);return c&&s?.indexSignature===a.signature&&s.scope===o?(s.listing??=xat(await CU(e,[`ls-files`,...o===``?[]:qe([o])])),s.listing.has(n)):(c&&L4.set(r,{indexSignature:a.signature,scope:o,listing:void 0}),(await CU(e,[`ls-files`,...qe([n])])).length>0)}function Cat(e){let{assetService:t,log:n}=e,r={"missing-path":[400,`urn:ok:error:invalid-request`,`Missing asset path.`],"unsupported-type":[415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`],"not-found":[404,`urn:ok:error:asset-not-found`,`Asset not found.`],"invalid-path":[400,`urn:ok:error:invalid-request`,`Invalid asset path.`]},i=X(_r,async(e,i)=>{try{let a=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveServableAsset(a);if(!o.ok){let[e,t,n]=r[o.reason];Y(i,e,t,n,{handler:`asset`,...o.cause===void 0?{}:{cause:o.cause}});return}let{asset:s}=o,c={"Content-Type":s.contentType,"Content-Length":String(s.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":s.disposition,"Cache-Control":`no-store`};s.csp!==null&&(c[`Content-Security-Policy`]=s.csp);let l=s.canonicalPath;i.writeHead(200,c);try{await fc(ws(l),i)}catch(e){let t=$a.getActiveSpan(),r=xG(e),o=r===`ERR_STREAM_PREMATURE_CLOSE`||r===`ECONNRESET`||r===`EPIPE`;t?.setAttribute(Ly,o?`connection_closed`:`stream_failure`),t?.recordException(e instanceof Error?e:String(e)),t?.setStatus({code:ro.ERROR,message:`Asset transfer incomplete`}),n.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:a,err:e},`[asset] pipeline failed mid-stream`),i.destroyed||i.destroy(e instanceof Error?e:void 0)}}catch(e){Y(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),a=1048576;return W$({"/api/asset":i,"/api/asset-text":X(_r,async(e,n)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveTextAsset(i);if(!o.ok){let[e,t,i]=r[o.reason];Y(n,e,t,i,{handler:`asset-text`,...o.cause===void 0?{}:{cause:o.cause}});return}if(o.size>a){Y(n,413,`urn:ok:error:payload-too-large`,`File exceeds the ${a}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await Js(o.canonicalPath)).toString(`utf-8`);n.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),n.end(s)}catch(e){Y(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0})})}const R4=`comments`,wat={maxBytes:65536,timeoutMs:1e4},Tat={start:Er().int().nonnegative().optional(),end:Er().int().nonnegative().optional(),quote:b().min(1).optional(),prefix:b().max(1e3).optional(),suffix:b().max(1e3).optional()},Eat=I({docName:b().min(1),...Tat,propertyKey:b().min(1).optional(),propertyPath:R(ln([b(),Er().int().nonnegative()])).optional(),body:b(),queue:ka().optional(),summary:b().optional()}),z4=ze(),Dat=gi(`action`,[I({action:F(`edit`),id:z4,body:b(),summary:b().optional()}),I({action:F(`resolve`),id:z4,summary:b().optional()}),I({action:F(`reopen`),id:z4,summary:b().optional()}),I({action:F(`replace`),id:z4,...Tat,summary:b().optional()}),I({action:F(`queue`),id:z4,summary:b().optional()}),I({action:F(`unqueue`),id:z4,summary:b().optional()}),I({action:F(`dispatch-prepare`),id:z4,summary:b().optional()}),I({action:F(`dispatch-complete`),id:z4,summary:b().optional()}),I({action:F(`dispatch-prepare-batch`),ids:R(z4).min(1).max(200),summary:b().optional()}),I({action:F(`dispatch-complete-batch`),ids:R(z4).min(1).max(200),summary:b().optional()})]);function Oat(e){let{service:t,getPrincipal:n,onChanged:r}=e;async function i(e,n){let r=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??void 0;try{let e=await t.listThreads(r);Z(n,200,yee,{threads:e},{handler:R4})}catch(e){H4(n,e,`Failed to list comment threads.`)}}function a(e,t){let n=new URL(e.url??``,`http://localhost`).searchParams.get(`id`);return n?z4.safeParse(n).success?n:(B4(t,`id must be a comment thread UUID.`),null):(B4(t,`id query parameter is required.`),null)}async function o(e,n){let r=a(e,n);if(r!==null)try{let e=await t.readThread(r);Z(n,200,va,e,{handler:R4})}catch(e){if(e instanceof R1)return V4(n,`Comment thread not found.`);H4(n,e,`Failed to read comment thread.`)}}async function s(e,i){let a=await kat(e,i,Eat);if(!a)return;let o=k$(a,n);if(o.kind===`invalid-summary`)return B4(i,`Summary must be a string.`);let s=Aat(o);if(!s)return B4(i,`A principal or agent identity is required to comment.`);try{let e=await t.createThread({docName:a.docName,start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix,propertyKey:a.propertyKey,propertyPath:a.propertyPath,author:s,body:a.body,queue:a.queue});r?.(),Z(i,201,va,e,{handler:R4})}catch(e){if(e instanceof L1)return V4(i,`Document not found.`);if(e instanceof B1)return B4(i,`The quoted passage is not in the document.`);if(e instanceof z1)return B4(i,`That property is not in the document: ${e.message}`);if(e instanceof RangeError||e instanceof Error&&/invalid selection|is required/.test(e.message))return B4(i,`Selection range is invalid for the document.`);H4(i,e,`Failed to create comment thread.`)}}async function c(e,i){let a=await kat(e,i,Dat);if(!a)return;let o=k$(a,n);if(o.kind===`invalid-summary`)return B4(i,`Summary must be a string.`);try{switch(a.action){case`edit`:return Aat(o)?u(i,await t.editComment(a.id,a.body)):B4(i,`An identity is required to edit a comment.`);case`resolve`:return u(i,await t.resolve(a.id));case`reopen`:return u(i,await t.reopen(a.id));case`replace`:return u(i,await t.replaceAnchor(a.id,{start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix}));case`queue`:{let e=await t.queueForDispatch(a.id);return r?.(),Z(i,200,rie,e,{handler:R4})}case`unqueue`:return u(i,await t.unqueue(a.id));case`dispatch-prepare`:{let e=await t.prepareDispatch(a.id);return r?.(),Z(i,200,Pne,e,{handler:R4})}case`dispatch-complete`:return u(i,await t.completeDispatch(a.id));case`dispatch-prepare-batch`:{let e=await t.prepareDispatchBatch(a.ids);return r?.(),Z(i,200,yte,{results:e},{handler:R4})}case`dispatch-complete-batch`:{let e=await t.completeDispatchBatch(a.ids);return r?.(),Z(i,200,_te,{results:e},{handler:R4})}}}catch(e){if(e instanceof R1)return V4(i,`Comment thread not found.`);if(e instanceof L1)return V4(i,`Document not found.`);if(e instanceof B1)return B4(i,`The quoted passage is not in the document.`);if(e instanceof z1)return B4(i,`That property is not in the document: ${e.message}`);if(e instanceof Error&&/invalid selection|is required/.test(e.message))return B4(i,`Selection range is invalid for the document.`);H4(i,e,`Failed to update comment thread.`)}}async function l(e,n){let i=a(e,n);if(i!==null)try{await t.delete(i),r?.(),Z(n,200,Hte,{threadId:i},{handler:R4})}catch(e){H4(n,e,`Failed to delete comment thread.`)}}function u(e,t){r?.(),Z(e,200,va,t,{handler:R4})}return{list:i,read:o,create:s,mutate:c,remove:l}}async function kat(e,t,n){let r;try{r=await q$(e,wat)}catch(e){return e instanceof J$?(Y$(t,R4),null):(B4(t,`Request body could not be read.`),null)}let i;try{i=JSON.parse(r.toString(`utf8`)||`{}`)}catch{return B4(t,`Request body must be valid JSON.`),null}let a=n.safeParse(i);return a.success?a.data:(B4(t,`Request body is invalid.`),null)}function Aat(e){return e.kind===`agent`||e.kind===`principal`?e.writerId:null}function B4(e,t){Y(e,400,`urn:ok:error:invalid-request`,t,{handler:R4})}function V4(e,t){Y(e,404,`urn:ok:error:not-found`,t,{handler:R4})}function H4(e,t,n){Y(e,500,`urn:ok:error:internal-server-error`,n,{handler:R4,cause:t})}function jat(e){let{commentService:t,getPrincipal:n,signalChannel:r}=e,i=Oat({service:t,getPrincipal:n,onChanged:()=>r?.(`comments`)});return W$({"/api/comments":p2({GET:i.list,POST:i.create},{handler:`comments`}),"/api/comment":p2({GET:i.read,POST:i.mutate,DELETE:i.remove},{handler:`comment`})},{mutating:[`/api/comments`,`/api/comment`]})}function Mat(e,t,n){return e.filter($6e).map(e=>{let r=Y6e(e),i=r.at(-1)??null;return{value:e.slug,label:e.slug,description:null,group:null,source:`native-cli`,fingerprint:t,freshness:{kind:`cached`,at:n},selectability:`candidate`,context:i===null?null:{effectiveTokens:J6e(i,e),origin:`native-catalog`},contextChoices:r,setPhase:`launch-only`}})}function Nat(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function U4(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Pat(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=Nat(t),r=Array.isArray(t)?t:n.models;return Array.isArray(r)?r.flatMap(e=>{let t=Nat(e),n=t.slug;return typeof n!=`string`||n===``?[]:[{slug:n,visibility:typeof t.visibility==`string`?t.visibility:null,contextWindow:U4(t.context_window),maxContextWindow:U4(t.max_context_window),effectivePercent:U4(t.effective_context_window_percent)}]}):[]}function Fat(e,t,n){let r={};for(let[e,n]of Object.entries(t))typeof n==`string`&&(r[e]=n);let i=n===`win32`,a=i?HQ(e,zQ(r)):e,o=i&&/\.(cmd|bat)$/i.test(a);return{...o?UQ(a,[`debug`,`models`]):{cmd:a,args:[`debug`,`models`]},wrap:o,env:r}}async function Iat(e,t=process.env,n=process.platform){let{cmd:r,args:i,wrap:a,env:o}=Fat(e,t,n);return new Promise(e=>{let t;try{t=ss(r,i,{env:o,stdio:[`ignore`,`pipe`,`ignore`],shell:!1,detached:n!==`win32`,windowsHide:!0,windowsVerbatimArguments:a})}catch(t){e(t.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`});return}let s=()=>{qQ(t,{graceMs:1e3})},c=``,l=0,u=!1,d=t=>{u||(u=!0,clearTimeout(f),e(t))},f=setTimeout(()=>{s(),d({outcome:`failed`})},8e3);t.stdout?.on(`data`,e=>{if(l+=e.length,l>4194304){s(),d({outcome:`failed`});return}c+=e.toString(`utf8`)}),t.on(`error`,e=>{d(e.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`})}),t.on(`close`,e=>{d(e===0?{outcome:`ok`,models:Pat(c)}:{outcome:`failed`})})})}let W4,G4;function Lat(e=new Date().toISOString()){W4={startedAt:e},G4=performance.now()}function Rat(){if(G4!==void 0)return Math.round(performance.now()-G4)}function K4(e,t){W4&&(W4[e]=t)}function zat(e,t){W4&&(W4[e]=t)}function Bat(){return W4}function Vat(e){let t=e.host;if(!t)return null;let n=e[`x-forwarded-proto`];return`${(Array.isArray(n)?n[0]:n)===`https`?`wss`:`ws`}://${t}/collab`}const Hat=K(`embeddings`);let Uat=null,Wat=null,Gat=null,Kat=null,qat=null;function Jat(){return Uat||=IH().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),Uat}function Yat(){return Wat||=IH().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),Wat}function Xat(){return Gat||=IH().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),Gat}function Zat(){return Kat||=IH().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),Kat}function Qat(){return qat||=IH().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),qat}function $at(e,t){t>0&&Jat().add(t,{role:e})}function eot(e){Yat().add(1,{reason:e})}function tot(e,t){Xat().record(Math.max(0,t),{role:e})}function not(e){Zat().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&Qat().record(Math.max(0,e.queryEmbedMs)),Hat.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const rot=K(`embeddings`),iot=1536,aot=`OK_EMBEDDINGS_API_KEY`;var q4=class extends Error{reason;status;constructor(e,t,n,r){super(t,r),this.reason=e,this.status=n,this.name=`EmbeddingProviderError`}},J4=class extends q4{name=`EmbeddingDimsMismatchError`;expected;got;constructor(e,t){super(`dims_mismatch`,`embeddings provider returned ${t}-dim vectors, expected ${e}`),this.expected=e,this.got=t}},Y4=class extends q4{name=`MalformedEmbeddingResponseError`;constructor(e){super(`malformed_response`,e)}};function oot(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function sot(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];if(t=Math.sqrt(t),t>0)for(let n=0;n<e.length;n++)e[n]/=t;return e}const X4={maxBatchSize:96,maxBatchChars:jne,docTimeoutMs:gte,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function Z4(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}function cot(e){let t=lte(e);if(t===null)return;if(t===`invalid-url`)throw Error(`embeddings baseUrl is not a valid URL: ${e}`);let n=new URL(e);throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${n.protocol}//${n.host}); use https:// (http:// is allowed only for localhost)`)}const lot=new Set([408,409,429,500,502,503,504]);function Q4(e,t={}){let n=t.fetchImpl??fetch,r=t.sleep??ni,i=t.maxBatchSize??X4.maxBatchSize,a=t.maxBatchChars??X4.maxBatchChars,o=t.maxRetries??X4.maxRetries,s=t.backoffBaseMs??X4.backoffBaseMs,c=t.docTimeoutMs??X4.docTimeoutMs,l=t.queryTimeoutMs??X4.queryTimeoutMs;cot(e.baseUrl);let u=e.dimensions??null,d=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function f(e){let t=[],n=[],r=0;for(let o of e)n.length>0&&(n.length>=i||r+o.length>a)&&(t.push(n),n=[],r=0),n.push(o),r+=o.length;return n.length>0&&t.push(n),t}async function p(t,r,i,a){let o=new AbortController,s=setTimeout(()=>o.abort(),a),c=performance.now();try{let a=await n(d,{method:`POST`,headers:{"Content-Type":`application/json`,...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}},body:t,signal:o.signal});if(tot(i,performance.now()-c),!a.ok){await a.text().catch(()=>``);let e=a.status===429?`rate_limit`:`http_error`,t=new q4(e,`embeddings request failed: HTTP ${a.status}`,a.status);return lot.has(a.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let s;try{s=await a.json()}catch{throw new Y4(`embeddings endpoint returned a non-JSON body — check the base URL`)}let l=h(s,r);return u??=l.dims,$at(i,s.usage?.total_tokens??0),{kind:`ok`,vectors:l.vectors}}catch(e){if(e instanceof J4)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof Y4)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,n=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:n}}finally{clearTimeout(s)}}async function m(t,n){let i=n===`query`?l:c,a=n===`query`?`query`:`document`,u=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),d=0;for(;;){let e=await p(u,t.length,a,i);if(e.kind===`ok`)return e.vectors;if(eot(e.reason),e.kind===`fatal`||d>=o)throw e.error instanceof q4?e.error:new q4(e.reason,e.error.message,void 0,{cause:e.error});d+=1;let n=s*2**(d-1);await r(Math.round(n/2+n/2*Math.random()))}}function h(e,t){let n=e.data;if(!Array.isArray(n)||n.length!==t)throw new Y4(`embeddings response had ${n?.length??0} vectors, expected ${t}`);let r=[...n].sort((e,t)=>(e.index??0)-(t.index??0)),i=[],a=u;for(let e of r){let t=e.embedding;if(!Array.isArray(t))throw new Y4(`embeddings response contained a non-array embedding (expected float vectors)`);if(a??=t.length,t.length!==a)throw new J4(a,t.length);i.push(sot(Float32Array.from(t)))}if(a===null)throw new Y4(`embeddings response contained no vectors`);return{vectors:i,dims:a}}return{providerId:Z4(e.baseUrl),modelId:e.model,get dims(){return u},pinDims(e){u??=e},async embed(e,{role:t}){if(e.length===0)return[];let n=[];for(let r of f(e))n.push(...await m(r,t));return n}}}function uot(e){return Z4(e)===Z4(_a)}async function $4(e,t,n){let r=e?await e.resolveForProject(t,n).catch(e=>(rot.warn({err:e},`[embeddings] failed to read the stored key — treating as unset`),null)):null;if(r?.key){let e=r.source===`file`?`file`:`project`;return{apiKey:r.key,keyless:!1,source:e}}if(uot(n)){let e=process.env[aot];if(e)return{apiKey:e,keyless:!1,source:`env`}}return Sie(n)?{apiKey:null,keyless:!0,source:`none`}:{apiKey:null,keyless:!1,source:`none`}}async function dot(e){let t=await $4(e.keyStore,e.projectDir,e.config.baseUrl);return t.apiKey?Q4({...e.config,apiKey:t.apiKey},e.options):t.keyless?Q4({...e.config},e.options):null}async function fot(e){let t;try{t=Q4({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:e.apiKey},{fetchImpl:e.fetchImpl,maxRetries:0,queryTimeoutMs:e.timeoutMs??1e4})}catch{return{ok:!1,reason:`invalid_endpoint`}}try{let[e]=await t.embed([`OpenKnowledge embeddings connection test`],{role:`query`});return!e||e.length===0?{ok:!1,reason:`malformed_response`}:{ok:!0,dimensions:e.length}}catch(e){return e instanceof q4?{ok:!1,reason:e.reason,status:e.status}:{ok:!1,reason:`network`}}}const pot=Z4(_a),e3=`OPENAI_API_KEY`,t3=`embeddings`,n3=`embeddings_projects`;function r3(e){try{return js.native(e)}catch{return U(e)}}function mot(e){return V(qx(e??Bs()),Xt)}function hot(e){return e&&e.length>=8?e.slice(-4):null}function got(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var i3=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??mot()}withLock(e){let t=`${this.secretsFile}.lock`,n=B(this.secretsFile);W(n)||dU(n,{recursive:!0,mode:448});let r=Date.now(),i=!1;for(;!i;)try{let e=ks(t,`wx`,384);Rs(e,String(process.pid)),Ss(e),i=!0}catch(e){if(e.code!==`EEXIST`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not acquire the secrets write-lock (${t}); proceeding without cross-process serialization.\n`);break}try{if(Date.now()-Fs(t).mtimeMs>1e4){Is(t);continue}}catch{continue}if(Date.now()-r>2e3)break;got(15)}try{return e()}finally{if(i)try{Is(t)}catch{}}}tightenPermsIfLoose(){let e;try{e=Fs(this.secretsFile).mode&511}catch{return}if(e&63)try{xs(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let n=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${n}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!W(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,Mc.parse)(G(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=B(this.secretsFile);W(t)||dU(t,{recursive:!0,mode:448});let n=`${this.secretsFile}.tmp`;lU(n,(0,Mc.stringify)(e),{mode:384}),xs(n,384),fU(n,this.secretsFile),xs(this.secretsFile,384)}writeOrUnlink(e){if(Object.keys(e).length===0){try{mU(this.secretsFile)}catch(e){if(e.code!==`ENOENT`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not remove ${this.secretsFile} (${t}); a cleared key may remain on disk — delete the file manually if needed.\n`)}}return}this.write(e)}readProjects(e){let t=e[n3];return t&&typeof t==`object`?t:{}}legacyKey(e){let t=e[e3]??e[t3];return typeof t==`string`&&t!==``?t:null}resolveForProject(e,t){let n=this.read(),r=Z4(t),i=this.readProjects(n)[r3(e)]?.[r];if(typeof i==`string`&&i!==``)return Promise.resolve({key:i,source:`project`});if(r===pot){let e=this.legacyKey(n);if(e)return Promise.resolve({key:e,source:`file`})}return Promise.resolve({key:null,source:null})}describeForProject(e,t){return this.resolveForProject(e,t).then(({key:e,source:t})=>({present:e!==null,hint:hot(e),source:t}))}getLegacyKey(){return Promise.resolve(this.legacyKey(this.read()))}setForProject(e,t,n){return this.withLock(()=>{let r=this.read(),i=this.readProjects(r),a=r3(e);i[a]={...i[a],[Z4(t)]:n},r[n3]=i,this.write(r)}),Promise.resolve()}clearForProject(e,t){let n=this.withLock(()=>{let n=this.read(),r=this.readProjects(n),i=r3(e),a=Z4(t);return r[i]?.[a]!==void 0&&(delete r[i][a],Object.keys(r[i]).length===0&&delete r[i],Object.keys(r).length===0?delete n[n3]:n[n3]=r,this.writeOrUnlink(n),!0)});return Promise.resolve(n)}clearAllForProject(e){let t=this.withLock(()=>{let t=this.read(),n=this.readProjects(t),r=r3(e);return n[r]!==void 0&&(delete n[r],Object.keys(n).length===0?delete t[n3]:t[n3]=n,this.writeOrUnlink(t),!0)});return Promise.resolve(t)}clearAll(){let e=this.withLock(()=>{let e=this.read(),t=e[n3]!==void 0||e[e3]!==void 0||e[t3]!==void 0;return delete e[n3],delete e[e3],delete e[t3],t&&this.writeOrUnlink(e),t});return Promise.resolve(e?{touched:[`file`]}:{touched:[]})}listProjects(){let e=this.readProjects(this.read()),t=Object.entries(e).map(([e,t])=>({projectKey:e,endpoints:Object.entries(t).map(([e,t])=>({endpoint:e,hint:hot(t)}))}));return Promise.resolve(t)}};function _ot(e){return new i3(e)}function vot(e){return new i3(e)}async function yot(e,t,n){return new i3(n).describeForProject(e,t)}async function bot(e){return new i3(e).clearAll()}function xot(e,t){let n=Kx({absPath:nS(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:n?.enabled===!0,baseUrl:n?.baseUrl??`https://api.openai.com/v1`,model:n?.model??`text-embedding-3-small`,dimensions:n?.dimensions??void 0,similarityFloor:n?.similarityFloor??void 0,maxBatchSize:n?.maxBatchSize??96,maxBatchChars:n?.maxBatchChars??96e3,docTimeoutMs:n?.docTimeoutMs??3e4}}function Sot(e,t={}){let n=Math.max(1,t.targetChars??8e3),r=Math.max(0,Math.min(t.overlapChars??400,n-1)),i=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=n)return[e.trim()];let a=[],o=0;for(;o<e.length&&a.length<i;){let t=Math.min(e.length,o+n);if(t<e.length){let r=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
1112
- `,t));r>o+Math.floor(n/2)&&(t=r)}let i=e.slice(o,t).trim();if(i&&a.push(i),t>=e.length)break;let s=t-r;o=s>o?s:t}return a}const a3=K(`embeddings`);function Cot(e,t){return e.identityDims===void 0?t===`auto`?`auto`:e.dims:e.identityDims}function wot(e){return rc(`sha256`).update(e,`utf-8`).digest(`hex`)}function Tot(e){let t=0;for(let n of e)t+=n.length;let n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Eot(e,t){let n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=new Float32Array(n);if(r.length%t!==0)throw Error(`vector blob length ${r.length} is not a multiple of dims ${t}`);let i=[];for(let e=0;e<r.length;e+=t)i.push(r.slice(e,e+t));return i}var Dot=class{cacheDir;vecDir;manifestPath;providerId;modelId;identityDims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;pinnedDims;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?V(e.cacheDir,`vec`):null,this.manifestPath=e.cacheDir?V(e.cacheDir,`manifest.json`):null,this.providerId=e.providerId,this.modelId=e.modelId,this.identityDims=e.identityDims,this.pinnedDims=e.identityDims===`auto`?null:e.identityDims,this.chunkConfigId=e.chunkConfigId}get dims(){return this.pinnedDims}matchesIdentity(e){return e.providerId===this.providerId&&e.modelId===this.modelId&&e.identityDims===this.identityDims&&e.chunkConfigId===this.chunkConfigId}pinDims(e){this.pinnedDims??=e}discard(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.wipeDisk(),this.dirty=!1}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{W(this.manifestPath)&&(e=JSON.parse(await Js(this.manifestPath,`utf-8`)))}catch(t){a3.warn({err:t},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===1&&this.matchesIdentity({providerId:e.providerId,modelId:e.modelId,identityDims:Cot(e,this.identityDims),chunkConfigId:e.chunkConfigId}))){e!==null&&a3.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(!e)return;if(this.pinnedDims===null){if(!Number.isInteger(e.dims)||e.dims<=0)return;this.pinnedDims=e.dims}let t=this.pinnedDims;for(let[n,r]of Object.entries(e.entries))if(r?.contentHash&&(this.entries.set(n,{contentHash:r.contentHash,mtimeMs:r.mtimeMs??0}),!this.vectorsByHash.has(r.contentHash)))try{let e=V(this.vecDir,`${r.contentHash}.bin`);if(W(e)){let n=await Js(e);this.vectorsByHash.set(r.contentHash,Eot(n,t)),this.persistedHashes.add(r.contentHash)}}catch(e){a3.warn({hash:r.contentHash,err:e},`[embeddings] corrupt vector blob — will re-embed`)}}isFresh(e,t){let n=this.entries.get(e);return n!==void 0&&n.mtimeMs===t&&this.vectorsByHash.has(n.contentHash)}link(e,t,n){if(!this.vectorsByHash.has(t))return!1;let r=this.entries.get(e);return(!r||r.contentHash!==t||r.mtimeMs!==n)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:n}),!0}store(e,t,n,r){this.vectorsByHash.set(t,r),this.entries.set(e,{contentHash:t,mtimeMs:n}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let n=this.vectorsByHash.get(t.contentHash);n&&n.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!this.cacheDir||!this.manifestPath||!this.vecDir||!this.dirty)return;let e=this.pinnedDims;if(e!==null)try{await cU(this.vecDir,{recursive:!0});let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of t){if(this.persistedHashes.has(e))continue;let t=this.vectorsByHash.get(e);t&&(await iU(V(this.vecDir,`${e}.bin`),Tot(t)),this.persistedHashes.add(e))}let n={schemaVersion:1,providerId:this.providerId,modelId:this.modelId,dims:e,identityDims:this.identityDims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},r=`${this.manifestPath}.tmp`;await iU(r,JSON.stringify(n)),await sU(r,this.manifestPath);for(let e of As(this.vecDir)){if(!e.endsWith(`.bin`))continue;let n=e.slice(0,-4);t.has(n)||(mU(V(this.vecDir,e)),this.persistedHashes.delete(n))}this.dirty=!1}catch(e){a3.warn({err:e},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{_U(this.cacheDir,{recursive:!0,force:!0})}catch(e){a3.warn({err:e},`[embeddings] failed to wipe stale cache`)}}};const o3=K(`embeddings`);function Oot(e){return e instanceof Error?e.message:String(e)}var s3=class extends Error{name=`DimsMismatchSignal`;cause;constructor(e){super(e.message),this.cause=e}},kot=class{loadEmbedder;cacheDir;enabled;providerFingerprint;transportFingerprint;maxBatchSize;capable=!1;ready=!1;providerErrorReason=null;embedder=null;cache=null;warmPromise=null;warmGeneration=0;cacheInitChain=Promise.resolve();embedChain=Promise.resolve();queuedDocs=null;dimsDriftResets=0;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``,this.transportFingerprint=e.transportFingerprint??``,this.maxBatchSize=e.maxBatchSize??96}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,providerError:this.providerErrorReason!==null,providerErrorReason:this.providerErrorReason,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){let t=e.providerFingerprint!==this.providerFingerprint,n=e.transportFingerprint!==this.transportFingerprint;this.providerFingerprint=e.providerFingerprint,this.transportFingerprint=e.transportFingerprint,this.maxBatchSize=e.maxBatchSize,t?(this.dimsDriftResets=0,this.resetWarm(`provider`)):n&&this.resetWarm(`transport`),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||this.resetWarm(`disabled`))}resetWarm(e){let t=this.cache?.embeddedCount??0,n=e===`transport`||e===`credential`||e===`retry`;this.warmGeneration+=1,this.warmPromise=null,this.ready=!1,this.capable=!1,this.providerErrorReason=null,this.embedder=null,e===`disabled`&&this.cache?.clearMemory(),e===`dimensions`&&this.cache?.discard(),n||(this.cache=null),o3.info({reason:e,retainedInMemoryDocumentCount:n?t:0,unloadedInMemoryDocumentCount:n?0:t},`[embeddings] resetting embedder`)}reloadCredential(){this.resetWarm(`credential`)}reportPhaseFailure(e){this.providerErrorReason!==`dimensions`&&this.providerErrorReason!==`configured_dimensions`&&(this.providerErrorReason=e)}recoverFromDimsDrift(e,t,n){if(this.cache===e){if(e.identityDims!==`auto`){o3.error({expected:t.expected,got:t.got,phase:n,recovery:`configured_mismatch`},`[embeddings] provider ignored the configured vector size — check search.semantic.dimensions`),this.capable=!1,this.providerErrorReason=`configured_dimensions`,e.clearMemory();return}if(this.dimsDriftResets>=2){o3.error({expected:t.expected,got:t.got,phase:n,recovery:`drift_exhausted`,unloadedInMemoryDocumentCount:e.embeddedCount},`[embeddings] provider vector length keeps changing — disabling semantic search until restart`),this.capable=!1,this.providerErrorReason=`dimensions`,e.clearMemory();return}this.dimsDriftResets+=1,o3.warn({expected:t.expected,got:t.got,phase:n,recovery:`recovered`},`[embeddings] provider vector length changed — discarding cached vectors and re-embedding`),this.resetWarm(`dimensions`)}}async ensureWarm(){for(;this.enabled&&!this.ready;)this.warmPromise||=this.warm(this.warmGeneration),await this.warmPromise}async warm(e){try{let t=await this.loadEmbedder();if(e!==this.warmGeneration||!this.enabled)return;if(!t){this.capable=!1,this.ready=!0,o3.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}let n=t.dims??`auto`,r={cacheDir:this.cacheDir,providerId:t.providerId,modelId:t.modelId,identityDims:n,chunkConfigId:`c8000-o400-m80`},i=this.cache;if(!i?.matchesIdentity(r)){i=new Dot(r);let t=i,n=this.cacheInitChain.then(async()=>{e!==this.warmGeneration||!this.enabled||await t.init()});this.cacheInitChain=n.catch(()=>{}),await n}if(e!==this.warmGeneration||!this.enabled)return;i.dims!==null&&t.pinDims?.(i.dims),this.embedder=t,this.cache=i,this.capable=!0,this.ready=!0}catch(t){if(e!==this.warmGeneration||!this.enabled)return;this.capable=!1,this.ready=!0,this.reportPhaseFailure(`warm`),o3.warn({err:t},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.providerErrorReason===`warm`&&this.ready&&!this.capable&&this.resetWarm(`retry`),this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){this.reportPhaseFailure(`corpus`),o3.warn({err:e},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){for(;this.enabled&&!this.ready;)await this.ensureWarm();if(!this.enabled||!this.capable||!this.embedder||!this.cache)return;let t=this.cache,n=this.embedder,r=this.maxBatchSize,i=e.filter(e=>e.kind===`page`),a=new Set(i.map(e=>e.id)),o=[];for(let e of i){if(!this.enabled)return;let n=e.modifiedTs;if(t.isFresh(e.id,n))continue;let r=wot(e.content);t.link(e.id,r,n)||o.push({doc:e,contentHash:r,chunks:Sot(e.content)})}let s=0,c=0,l=0,u=!1,d=(e,n)=>{let r=n[0]?.length;r!==void 0&&t.pinDims(r),t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,n),c+=1},f=async e=>{let t=e.flatMap(e=>e.chunks);try{let r=t.length?await n.embed(t,{role:`document`}):[],i=0;for(let t of e)d(t,r.slice(i,i+t.chunks.length)),i+=t.chunks.length;return s=0,!0}catch(t){if(t instanceof J4)throw new s3(t);if(l+=1,e.length===1)return o3.warn({docId:e[0].doc.id,err:Oot(t)},`[embeddings] failed to embed document`),s+=1,s<5;for(let t of e){if(!this.enabled)return!1;try{let e=t.chunks.length?await n.embed(t.chunks,{role:`document`}):[];d(t,e),s=0}catch(e){if(e instanceof J4)throw new s3(e);if(l+=1,o3.warn({docId:t.doc.id,err:Oot(e)},`[embeddings] failed to embed document`),s+=1,s>=5)return!1}}return!0}},p=[],m=0;try{for(let e of o){if(!this.enabled)break;if(p.push(e),m+=Math.max(1,e.chunks.length),m>=r){let e=await f(p);if(p=[],m=0,!e){u=!0;break}}}p.length>0&&this.enabled&&(u=!await f(p))}catch(e){if(!(e instanceof s3))throw e;this.recoverFromDimsDrift(t,e.cause,`corpus`);return}if(!this.enabled||this.cache!==t){o3.info({reason:this.enabled?`cache-replaced`:`disabled`,completedDocumentCount:c,scheduledDocumentCount:o.length,corpusDocumentCount:a.size},`[embeddings] abandoning embed pass before persistence`);return}t.retain(a),await t.persist(),u||c===0&&l>=2?this.reportPhaseFailure(`corpus`):this.providerErrorReason===`corpus`&&(this.providerErrorReason=null)}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready)return null;let n=this.cache,r=this.embedder;if(!r||!n||n.embeddedCount===0)return null;let i=e.trim();if(!i)return null;let a;try{[a]=await r.embed([i],{role:`query`}),this.providerErrorReason===`query`&&(this.providerErrorReason=null)}catch(e){return e instanceof J4?this.recoverFromDimsDrift(n,e,`query`):(this.reportPhaseFailure(`query`),o3.warn({err:e,reason:e instanceof q4?e.reason:void 0},`[embeddings] query embed failed — degrading to lexical`)),null}if(!a)return null;let o=new Map;for(let e of t){let t=n.getVectors(e.id);if(!t||t.length===0)continue;let r=-1/0;for(let e of t){if(e.length!==a.length)continue;let t=oot(a,e);t>r&&(r=t)}r>-1/0&&o.set(e.id,r)}return o}};const Aot=/^[A-Za-z0-9-]{8,64}$/;let c3=null;function jot(e){return V(e??Bs(),`.ok`,mte)}function l3(e){if(e===void 0&&c3!==null)return c3;let t=jot(e),n=null;try{let e=G(t,`utf-8`).trim();Aot.test(e)&&(n=e)}catch{}if(n===null){n=ic();try{Ds(B(t),{recursive:!0}),Ls(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){K(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(c3=n),n}const u3=K(`process-lock`);var d3=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`OpenKnowledge ${n} already running at ${e.url??`port ${e.port}`} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function f3(e,t){return U(e,`${t}.lock`)}const p3=new Map;function Mot(e){p3.set(e,(p3.get(e)??0)+1)}function Not(e){let t=p3.get(e);return t===void 0||t<=1?(p3.delete(e),!0):(p3.set(e,t-1),!1)}function m3(e){return typeof e.machineId==`string`?e.machineId===l3():e.hostname===Vs()}const h3=new Set;let Pot=!1;function Fot(e){h3.add(e),!Pot&&(Pot=!0,process.on(`exit`,()=>{for(let e of h3)try{let t=JSON.parse(G(e,`utf-8`));if(t?.pid!==process.pid||typeof t.machineId==`string`&&t.machineId!==l3()||t.machineId===void 0&&typeof t.hostname==`string`&&t.hostname!==Vs())continue;Is(e)}catch{}}))}function Iot(e,t){try{let n=JSON.parse(G(e,`utf-8`));return n&&typeof n==`object`&&uW(n.pid)?n:(u3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return u3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null}}function Lot(e){try{return Dr()}catch(t){u3.warn({err:t},`${e} Not recording a channel: ${t instanceof Error?t.message:String(t)}`);return}}function Rot(e){return typeof e==`string`&&e.length>0?e:void 0}function zot(e){let{lockName:t,lockDir:n,metadata:r}=e,i=`[${t}-lock]`;Ds(n,{recursive:!0});let a=f3(n,t),o={pid:process.pid,hostname:Vs(),port:r.port,...r.url!==void 0&&{url:r.url},startedAt:new Date().toISOString(),worktreeRoot:r.worktreeRoot,machineId:l3(),...r.kind!==void 0&&{kind:r.kind},...r.parentPid!==void 0&&{parentPid:r.parentPid},...r.capabilities!==void 0&&{capabilities:r.capabilities},protocolVersion:r.protocolVersion??2,runtimeVersion:r.runtimeVersion??fQ,channel:Lot(i)},s=JSON.stringify(o,null,2);for(let e=0;e<3;e++){if(!W(a))try{let e=ks(a,`wx`,384);try{Rs(e,s)}finally{Ss(e)}return Mot(a),Fot(a),Bot({lockName:t,lockDir:n,lockPath:a})}catch(e){if(xG(e)!==`EEXIST`)throw e}let e=Iot(a,i);if(e){if(m3(e)&&e.pid===process.pid)return Ls(a,s,{encoding:`utf-8`,mode:384}),Mot(a),Fot(a),Bot({lockName:t,lockDir:n,lockPath:a});if(lW(e.pid))throw new d3(e,a,t);u3.warn({pid:e.pid,host:e.hostname},`${i} Stale lock detected (pid=${e.pid}, host=${e.hostname}) — replacing`)}try{Is(a)}catch{}}throw Error(`${i} Failed to acquire ${a} after 3 attempts (concurrent acquire contention).`)}function Bot(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>y3({lockName:t,lockDir:n}),updatePort:(e,r)=>_3({lockName:t,lockDir:n,port:e,url:r})}}function Vot(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function g3(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=Vot(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}function _3(e){let{lockName:t,lockDir:n,port:r,url:i}=e,a=`[${t}-lock]`,o=f3(n,t);if(!W(o)){u3.warn({lockPath:o},`${a} Lock file missing at ${o} during port update — skipping`);return}let s;try{let e=JSON.parse(G(o,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid)){u3.warn({lockPath:o},`${a} Corrupt lock at ${o} during port update — skipping`);return}s=e}catch{u3.warn({lockPath:o},`${a} Unreadable lock at ${o} during port update — skipping`);return}if(s.pid===process.pid&&m3(s)){s.port=r,i===void 0?delete s.url:s.url=i;try{Ls(o,JSON.stringify(s,null,2),{encoding:`utf-8`,mode:384})}catch(e){u3.warn({lockPath:o,err:e},`${a} Failed to update port in ${o}: ${e instanceof Error?e.message:String(e)}`)}}}function Hot(e){let{lockName:t,lockDir:n}=e,r=`[${t}-lock]`,i=f3(n,t);if((p3.get(i)??0)>1)return;let a;try{let e=JSON.parse(G(i,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid)){u3.warn({lockPath:i},`${r} Corrupt lock at ${i} during draining mark — skipping`);return}a=e}catch(e){xG(e)!==`ENOENT`&&u3.warn({lockPath:i,err:e},`${r} Unreadable lock at ${i} during draining mark — skipping: ${e instanceof Error?e.message:String(e)}`);return}if(a.pid===process.pid&&m3(a)&&a.draining!==!0){a.draining=!0;try{Ls(i,JSON.stringify(a,null,2),{encoding:`utf-8`,mode:384})}catch(e){u3.warn({lockPath:i,err:e},`${r} Failed to mark ${i} draining: ${e instanceof Error?e.message:String(e)}`)}}}function v3(e){let{lockName:t,lockDir:n}=e,r=f3(n,t);if(!W(r))return null;let i;try{let e=JSON.parse(G(r,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid))return null;i={...e,channel:Rot(e.channel)}}catch{return null}if(!m3(i))return null;if(!lW(i.pid)){try{Is(r)}catch{}return null}return i}function Uot(e){let{lockName:t,lockDir:n}=e,r=f3(n,t);if(!W(r))return{status:`absent`};let i;try{i=JSON.parse(G(r,`utf-8`))}catch{return{status:`incompatible`,reason:`corrupt`,raw:void 0}}if(!i||typeof i!=`object`)return{status:`incompatible`,reason:`corrupt`,raw:i};let a=i;if(!uW(a.pid)||typeof a.hostname!=`string`||typeof a.port!=`number`||typeof a.startedAt!=`string`||typeof a.worktreeRoot!=`string`)return{status:`incompatible`,reason:`corrupt`,raw:i};let o={pid:a.pid,hostname:a.hostname,port:a.port,url:typeof a.url==`string`?a.url:void 0,startedAt:a.startedAt,worktreeRoot:a.worktreeRoot,machineId:typeof a.machineId==`string`?a.machineId:void 0,draining:a.draining===!0||void 0,capabilities:Array.isArray(a.capabilities)&&a.capabilities.every(e=>typeof e==`string`)?a.capabilities:void 0,protocolVersion:typeof a.protocolVersion==`number`?a.protocolVersion:void 0,runtimeVersion:typeof a.runtimeVersion==`string`?a.runtimeVersion:void 0,channel:Rot(a.channel)};if(!m3(o))return{status:`stale`,lock:o};if(!lW(o.pid)){try{Is(r)}catch{}return{status:`stale`,lock:o}}return o.protocolVersion===void 0||o.runtimeVersion===void 0?{status:`incompatible`,reason:`missing-fields`,raw:i}:{status:`live`,lock:o}}async function Wot(e){let{lockName:t,lockDir:n}=e,r=e.timeoutMs??1e4,i=e.pollIntervalMs??100,a=e.readLock??(()=>v3({lockName:t,lockDir:n})),o=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a();if(s===null||s.draining!==!0)return`no-drain`;let c=Date.now()+r;for(;Date.now()<c;){await o(i);let e=a();if(e===null)return`released`;if(e.draining!==!0)return`no-drain`}return`timeout`}function y3(e){let{lockName:t,lockDir:n,deferUnlinkToExit:r=!1}=e,i=`[${t}-lock]`,a=f3(n,t);if(Not(a)){if(r){Hot({lockName:t,lockDir:n});return}if(W(a))try{let e=JSON.parse(G(a,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||!m3(e))return;Is(a),h3.delete(a)}catch(e){u3.warn({lockPath:a,err:e},`${i} Failed to release ${a}: ${e instanceof Error?e.message:String(e)}`)}}}var Got=jb({ServerLockCollisionError:()=>b3,acquireServerLock:()=>x3,lockAdvertisesUi:()=>C3,markServerLockDraining:()=>T3,readServerLock:()=>S3,releaseServerLock:()=>w3,updateServerLockPort:()=>Kot,waitForServerLockDrain:()=>qot}),b3=class extends d3{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function x3(e,t){try{return zot({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof d3&&e.lockName===`server`?new b3(e.existing,e.lockPath):e}}function Kot(e,t,n){_3({lockName:`server`,lockDir:e,port:t,url:n})}function S3(e){return v3({lockName:`server`,lockDir:e})}function C3(e){return!Array.isArray(e.capabilities)||e.capabilities.includes(`ui`)}function w3(e,t){y3({lockName:`server`,lockDir:e,...t})}function T3(e){Hot({lockName:`server`,lockDir:e})}function qot(e,t){return Wot({lockName:`server`,lockDir:e,...t})}function Jot(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,ready:a,serverInstanceId:o,getDiskAckSVs:s,getCollabClientCount:c,getConfigDiagnostics:l,acpRegistry:u,loadAcpCustomAgents:d,acpHarnessAvailability:f,isRoutePeerAdmitted:p,isAllowedWorkspaceHostHeader:m,checkLocalOpSecurity:h,getPrincipal:g,semanticSearch:_,readSemanticProviderConfig:v,embeddingsSecretsFile:y,getFileIndex:x,shadowRef:S,getCurrentBranch:C,getReportedBranch:w,installedAgentsCache:T}=e,E=X(_r,async(e,t)=>{try{a&&await a.catch(e=>{i.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=w?.()??void 0,n=s?.(),r=Bat(),l=c?.();Z(t,200,bte,{serverInstanceId:o,...e===void 0?{}:{currentBranch:e},...n===void 0?{}:{currentDiskAckSVs:n},...r===void 0?{}:{boot:r},...l===void 0?{}:{collabClients:l}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),D=I({id:b(),name:b(),version:b(),description:b().optional(),license:b().optional(),iconUrl:b().optional(),website:b().optional(),source:ra([`registry`,`custom`]),supported:ka(),featured:ka(),harness:I({cli:ra([`claude`,`codex`,`cursor`,`gemini`,`opencode`,`pi`]),availability:ra([`present`,`not-found`,`unknown`]),credentials:ra([`present`,`unknown`])}).optional()}),O=I({agents:R(D),stale:ka(),maxThreads:Er()}),k=I({agentId:b(),reason:b().nullable(),candidates:R(I({value:b(),label:b(),description:b().nullable(),group:b().nullable(),contextChoices:R(Er()),context:I({effectiveTokens:Er(),origin:b()}).nullable(),selectability:b(),setPhase:b()}))}),A=X(_r,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`agent`)??``,r=e=>Z(t,200,k,{agentId:n,candidates:[],reason:e});if(n===``){Y(t,400,`urn:ok:error:invalid-request`,`An agent id is required.`,{handler:`acp-models`});return}if(n!==`codex-acp`){r(`unsupported`);return}if((await f()).codex?.availability!==`present`){r(`unavailable`);return}let a=kQ(),o=await Iat(`codex`,a);if(o.outcome===`not-found`){let e=await TQ(i)();e!==null&&(o=await Iat(`codex`,PQ(a,e)))}if(o.outcome!==`ok`){i.warn({agentId:n,outcome:o.outcome},`[acp-models] codex catalog probe failed`),r(`unavailable`);return}let s=o.models;if(s.length===0){r(`unavailable`);return}Z(t,200,k,{agentId:n,reason:null,candidates:Mat(s,{harness:`codex`,cliVersion:null,adapterVersion:null,endpoint:null,account:null},Date.now()).map(e=>({value:e.value,label:e.label,description:e.description,group:e.group,contextChoices:[...e.contextChoices],context:e.context,selectability:e.selectability,setPhase:e.setPhase}))})},{handler:`acp-models`}),j=X(_r,async(e,t)=>{if(u===void 0){Y(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=sH(),{agents:n,stale:r}=await u.getCatalog(),i=await d?.()??[],a=await f(),o=[...n.map(t=>{let n=S9e[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:rH.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]?.availability??`unknown`,credentials:a[n]?.credentials??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))];Z(t,200,O,{agents:o,stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function ee(e,t){if(!p(e.socket.remoteAddress)){Y(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!m(e.headers.host)){Y(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=g?.()??null;if(!n){Y(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}Z(t,200,cre,n,{handler:`principal`})}async function M(e,t){if(!p(e.socket.remoteAddress)){Y(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!m(e.headers.host)){Y(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=X5e.read();Z(t,200,Cie,{entries:n,count:n.length,detection:n7e(n[0])},{handler:`embed-detect`})}async function N(e,n){if(!p(e.socket.remoteAddress)){Y(n,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!m(e.headers.host)){Y(n,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){Y(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let r=U(t),a=r,o=!0;try{a=js(r)}catch(e){let t=xG(e);if(t===`ENOENT`)i.warn({path:r},`[workspace] contentDir does not exist; returning unresolved path`),o=!1;else{i.warn({path:r,err:e},`[workspace] realpath failed for contentDir`),Y(n,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:t??void 0,cause:e});return}}Z(n,200,jt,{contentDir:a,pathSeparator:gs,symlinkResolved:o},{handler:`workspace`})}async function P(e,t){if(h(e,t,{handler:`installed-agents`}))try{await W9e(e,t,T.probeAll)}catch(n){t.headersSent||(i.error({err:n,requestId:Kq(e)},`[installed-agents] route wrapper failed`),Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let te=n?aJ(n):null;async function ne(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Vat(e.headers),previewUrl:null,port:te?S3(te)?.port??0:0,singleFile:r};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}Z(t,200,ane,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function re(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=l?.()??{diagnostics:[]};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}Z(t,200,ye,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let ie=X(_r,async(e,r)=>{try{let e=!1,i=!1,a=!1,o=!1,s=null,c=0;if(_){let t=_.getStatus();e=t.enabled,i=t.ready,a=t.capable,o=t.providerError,s=t.providerErrorReason,c=t.embeddedCount}let l=v?.()?.baseUrl??`https://api.openai.com/v1`,u=await $4(new i3(y),n??t,l),d=u.apiKey!==null,f=!d&&u.keyless,p=d?u.source:null,m=u.apiKey&&u.apiKey.length>=8?u.apiKey.slice(-4):null,h=0;for(let[e]of x())!sG(e)&&!cG(e)&&!Lee(e)&&(h+=1);Z(r,200,Cn,{enabled:e,keyPresent:d,keyNotRequired:f,keySource:p,keyHint:m,ready:i,capable:a,providerError:o,providerErrorReason:s,embedded:c,total:h},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),ae=(e,t)=>{let n=B(e);for(;n!==t&&n.startsWith(`${t}${gs}`);){try{vU(n)}catch(e){i.debug({err:e},`[rescue] empty-directory prune stopped (non-critical)`);return}n=B(n)}},oe={"/api/config":ne,"/api/config/diagnostics":re,"/api/server-info":E,"/api/principal":ee,"/api/workspace":N,"/api/semantic-status":ie,"/api/acp/catalog":j,"/api/acp/models":A,"/api/installed-agents":P,"/api/__embed-detect":M,"/api/rescue":X(_r,async(e,t)=>{try{if(!S?.current){Z(t,200,_re,[],{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}});return}let e=Date.now(),n=[],r=U(S.current.gitDir,`rescue`);if(W(r))try{let t=As(r,{encoding:`utf-8`,recursive:!0}).map(e=>e.replaceAll(gs,`/`)).filter(e=>KW(e)),a=js(r);for(let o of t){let t=U(r,o),s;try{s=js(t)}catch(e){i.warn({file:o,err:e},`[rescue] skipping unresolvable rescue entry`);continue}if(!yG(s,a)){i.warn({file:o,canonical:s},`[rescue] skipping rescue entry resolving outside the rescue directory`);continue}try{let t=Fs(s);if(!t.isFile())continue;if(e-t.mtimeMs>864e5){try{mU(s),ae(s,a)}catch(e){i.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:YW(o),timestamp:t.mtime.toISOString(),size:t.size,source:`flat`})}catch(e){i.warn({file:o,err:e},`[rescue] skipping uninspectable rescue entry`)}}}catch(e){i.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=C?.()??`main`,t=await BW(S.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){i.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}Z(t,200,_re,n,{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0})};return{paths:Object.keys(oe),table:{resolve(e){let t=oe[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const Yot=K(`asset-references`),Xot=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function Zot(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function Qot(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),n=t.indexOf(`#`),r=n>=0?t.slice(0,n):t,i=r.indexOf(`?`);return i>=0?r.slice(0,i):r}function $ot(e){let t=Qot(e.href);if(!t||Zot(t))return!1;let n=e.literal?t:Iie(t);return cr.has(fs(n).slice(1).toLowerCase())}function est(e){return e?ost(e).filter($ot).map(e=>`${e.literal?`w`:`m`}\0${e.href}`).sort().join(``):``}function tst(e,t){return est(e)!==est(t)}function nst(e){let t=fs(e).slice(1).toLowerCase();return Ir(t)}function rst(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function ist(e,t){let n=(e,n)=>{let r=`${n?`w`:`m`} ${e}`;t.has(r)||t.set(r,{href:e,literal:n})};for(let t of O$e(e,{nestedBracketLabels:!0}))t.href&&n(t.href,!1);for(let t of D$e(e))n(t.target,!0);for(let t of e.matchAll(Xot)){let e=t[1]??t[2]??t[3]??t[4];e&&n(e,!1)}}function ast(e,t){let n=e,r=``;for(;n.length>0;){if(t.inComment){let e=n.indexOf(`-->`);if(e===-1)return r;n=n.slice(e+3),t.inComment=!1;continue}let e=n.indexOf(`<!--`);if(e===-1)return r+n;r+=n.slice(0,e),n=n.slice(e+4),t.inComment=!0}return r}function ost(e){let t=new Map,n=Ai(),r={inComment:!1};for(let i of e.replaceAll(`\r
1112
+ `,t));r>o+Math.floor(n/2)&&(t=r)}let i=e.slice(o,t).trim();if(i&&a.push(i),t>=e.length)break;let s=t-r;o=s>o?s:t}return a}const a3=K(`embeddings`);function Cot(e,t){return e.identityDims===void 0?t===`auto`?`auto`:e.dims:e.identityDims}function wot(e){return rc(`sha256`).update(e,`utf-8`).digest(`hex`)}function Tot(e){let t=0;for(let n of e)t+=n.length;let n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Eot(e,t){let n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=new Float32Array(n);if(r.length%t!==0)throw Error(`vector blob length ${r.length} is not a multiple of dims ${t}`);let i=[];for(let e=0;e<r.length;e+=t)i.push(r.slice(e,e+t));return i}var Dot=class{cacheDir;vecDir;manifestPath;providerId;modelId;identityDims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;pinnedDims;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?V(e.cacheDir,`vec`):null,this.manifestPath=e.cacheDir?V(e.cacheDir,`manifest.json`):null,this.providerId=e.providerId,this.modelId=e.modelId,this.identityDims=e.identityDims,this.pinnedDims=e.identityDims===`auto`?null:e.identityDims,this.chunkConfigId=e.chunkConfigId}get dims(){return this.pinnedDims}matchesIdentity(e){return e.providerId===this.providerId&&e.modelId===this.modelId&&e.identityDims===this.identityDims&&e.chunkConfigId===this.chunkConfigId}pinDims(e){this.pinnedDims??=e}discard(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.wipeDisk(),this.dirty=!1}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{W(this.manifestPath)&&(e=JSON.parse(await Js(this.manifestPath,`utf-8`)))}catch(t){a3.warn({err:t},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===1&&this.matchesIdentity({providerId:e.providerId,modelId:e.modelId,identityDims:Cot(e,this.identityDims),chunkConfigId:e.chunkConfigId}))){e!==null&&a3.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(!e)return;if(this.pinnedDims===null){if(!Number.isInteger(e.dims)||e.dims<=0)return;this.pinnedDims=e.dims}let t=this.pinnedDims;for(let[n,r]of Object.entries(e.entries))if(r?.contentHash&&(this.entries.set(n,{contentHash:r.contentHash,mtimeMs:r.mtimeMs??0}),!this.vectorsByHash.has(r.contentHash)))try{let e=V(this.vecDir,`${r.contentHash}.bin`);if(W(e)){let n=await Js(e);this.vectorsByHash.set(r.contentHash,Eot(n,t)),this.persistedHashes.add(r.contentHash)}}catch(e){a3.warn({hash:r.contentHash,err:e},`[embeddings] corrupt vector blob — will re-embed`)}}isFresh(e,t){let n=this.entries.get(e);return n!==void 0&&n.mtimeMs===t&&this.vectorsByHash.has(n.contentHash)}link(e,t,n){if(!this.vectorsByHash.has(t))return!1;let r=this.entries.get(e);return(!r||r.contentHash!==t||r.mtimeMs!==n)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:n}),!0}store(e,t,n,r){this.vectorsByHash.set(t,r),this.entries.set(e,{contentHash:t,mtimeMs:n}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let n=this.vectorsByHash.get(t.contentHash);n&&n.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!this.cacheDir||!this.manifestPath||!this.vecDir||!this.dirty)return;let e=this.pinnedDims;if(e!==null)try{await cU(this.vecDir,{recursive:!0});let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of t){if(this.persistedHashes.has(e))continue;let t=this.vectorsByHash.get(e);t&&(await iU(V(this.vecDir,`${e}.bin`),Tot(t)),this.persistedHashes.add(e))}let n={schemaVersion:1,providerId:this.providerId,modelId:this.modelId,dims:e,identityDims:this.identityDims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},r=`${this.manifestPath}.tmp`;await iU(r,JSON.stringify(n)),await sU(r,this.manifestPath);for(let e of As(this.vecDir)){if(!e.endsWith(`.bin`))continue;let n=e.slice(0,-4);t.has(n)||(mU(V(this.vecDir,e)),this.persistedHashes.delete(n))}this.dirty=!1}catch(e){a3.warn({err:e},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{_U(this.cacheDir,{recursive:!0,force:!0})}catch(e){a3.warn({err:e},`[embeddings] failed to wipe stale cache`)}}};const o3=K(`embeddings`);function Oot(e){return e instanceof Error?e.message:String(e)}var s3=class extends Error{name=`DimsMismatchSignal`;cause;constructor(e){super(e.message),this.cause=e}},kot=class{loadEmbedder;cacheDir;enabled;providerFingerprint;transportFingerprint;maxBatchSize;capable=!1;ready=!1;providerErrorReason=null;embedder=null;cache=null;warmPromise=null;warmGeneration=0;cacheInitChain=Promise.resolve();embedChain=Promise.resolve();queuedDocs=null;dimsDriftResets=0;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``,this.transportFingerprint=e.transportFingerprint??``,this.maxBatchSize=e.maxBatchSize??96}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,providerError:this.providerErrorReason!==null,providerErrorReason:this.providerErrorReason,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){let t=e.providerFingerprint!==this.providerFingerprint,n=e.transportFingerprint!==this.transportFingerprint;this.providerFingerprint=e.providerFingerprint,this.transportFingerprint=e.transportFingerprint,this.maxBatchSize=e.maxBatchSize,t?(this.dimsDriftResets=0,this.resetWarm(`provider`)):n&&this.resetWarm(`transport`),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||this.resetWarm(`disabled`))}resetWarm(e){let t=this.cache?.embeddedCount??0,n=e===`transport`||e===`credential`||e===`retry`;this.warmGeneration+=1,this.warmPromise=null,this.ready=!1,this.capable=!1,this.providerErrorReason=null,this.embedder=null,e===`disabled`&&this.cache?.clearMemory(),e===`dimensions`&&this.cache?.discard(),n||(this.cache=null),o3.info({reason:e,retainedInMemoryDocumentCount:n?t:0,unloadedInMemoryDocumentCount:n?0:t},`[embeddings] resetting embedder`)}reloadCredential(){this.resetWarm(`credential`)}reportPhaseFailure(e){this.providerErrorReason!==`dimensions`&&this.providerErrorReason!==`configured_dimensions`&&(this.providerErrorReason=e)}recoverFromDimsDrift(e,t,n){if(this.cache===e){if(e.identityDims!==`auto`){o3.error({expected:t.expected,got:t.got,phase:n,recovery:`configured_mismatch`},`[embeddings] provider ignored the configured vector size — check search.semantic.dimensions`),this.capable=!1,this.providerErrorReason=`configured_dimensions`,e.clearMemory();return}if(this.dimsDriftResets>=2){o3.error({expected:t.expected,got:t.got,phase:n,recovery:`drift_exhausted`,unloadedInMemoryDocumentCount:e.embeddedCount},`[embeddings] provider vector length keeps changing — disabling semantic search until restart`),this.capable=!1,this.providerErrorReason=`dimensions`,e.clearMemory();return}this.dimsDriftResets+=1,o3.warn({expected:t.expected,got:t.got,phase:n,recovery:`recovered`},`[embeddings] provider vector length changed — discarding cached vectors and re-embedding`),this.resetWarm(`dimensions`)}}async ensureWarm(){for(;this.enabled&&!this.ready;)this.warmPromise||=this.warm(this.warmGeneration),await this.warmPromise}async warm(e){try{let t=await this.loadEmbedder();if(e!==this.warmGeneration||!this.enabled)return;if(!t){this.capable=!1,this.ready=!0,o3.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}let n=t.dims??`auto`,r={cacheDir:this.cacheDir,providerId:t.providerId,modelId:t.modelId,identityDims:n,chunkConfigId:`c8000-o400-m80`},i=this.cache;if(!i?.matchesIdentity(r)){i=new Dot(r);let t=i,n=this.cacheInitChain.then(async()=>{e!==this.warmGeneration||!this.enabled||await t.init()});this.cacheInitChain=n.catch(()=>{}),await n}if(e!==this.warmGeneration||!this.enabled)return;i.dims!==null&&t.pinDims?.(i.dims),this.embedder=t,this.cache=i,this.capable=!0,this.ready=!0}catch(t){if(e!==this.warmGeneration||!this.enabled)return;this.capable=!1,this.ready=!0,this.reportPhaseFailure(`warm`),o3.warn({err:t},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.providerErrorReason===`warm`&&this.ready&&!this.capable&&this.resetWarm(`retry`),this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){this.reportPhaseFailure(`corpus`),o3.warn({err:e},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){for(;this.enabled&&!this.ready;)await this.ensureWarm();if(!this.enabled||!this.capable||!this.embedder||!this.cache)return;let t=this.cache,n=this.embedder,r=this.maxBatchSize,i=e.filter(e=>e.kind===`page`),a=new Set(i.map(e=>e.id)),o=[];for(let e of i){if(!this.enabled)return;let n=e.modifiedTs;if(t.isFresh(e.id,n))continue;let r=wot(e.content);t.link(e.id,r,n)||o.push({doc:e,contentHash:r,chunks:Sot(e.content)})}let s=0,c=0,l=0,u=!1,d=(e,n)=>{let r=n[0]?.length;r!==void 0&&t.pinDims(r),t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,n),c+=1},f=async e=>{let t=e.flatMap(e=>e.chunks);try{let r=t.length?await n.embed(t,{role:`document`}):[],i=0;for(let t of e)d(t,r.slice(i,i+t.chunks.length)),i+=t.chunks.length;return s=0,!0}catch(t){if(t instanceof J4)throw new s3(t);if(l+=1,e.length===1)return o3.warn({docId:e[0].doc.id,err:Oot(t)},`[embeddings] failed to embed document`),s+=1,s<5;for(let t of e){if(!this.enabled)return!1;try{let e=t.chunks.length?await n.embed(t.chunks,{role:`document`}):[];d(t,e),s=0}catch(e){if(e instanceof J4)throw new s3(e);if(l+=1,o3.warn({docId:t.doc.id,err:Oot(e)},`[embeddings] failed to embed document`),s+=1,s>=5)return!1}}return!0}},p=[],m=0;try{for(let e of o){if(!this.enabled)break;if(p.push(e),m+=Math.max(1,e.chunks.length),m>=r){let e=await f(p);if(p=[],m=0,!e){u=!0;break}}}p.length>0&&this.enabled&&(u=!await f(p))}catch(e){if(!(e instanceof s3))throw e;this.recoverFromDimsDrift(t,e.cause,`corpus`);return}if(!this.enabled||this.cache!==t){o3.info({reason:this.enabled?`cache-replaced`:`disabled`,completedDocumentCount:c,scheduledDocumentCount:o.length,corpusDocumentCount:a.size},`[embeddings] abandoning embed pass before persistence`);return}t.retain(a),await t.persist(),u||c===0&&l>=2?this.reportPhaseFailure(`corpus`):this.providerErrorReason===`corpus`&&(this.providerErrorReason=null)}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready)return null;let n=this.cache,r=this.embedder;if(!r||!n||n.embeddedCount===0)return null;let i=e.trim();if(!i)return null;let a;try{[a]=await r.embed([i],{role:`query`}),this.providerErrorReason===`query`&&(this.providerErrorReason=null)}catch(e){return e instanceof J4?this.recoverFromDimsDrift(n,e,`query`):(this.reportPhaseFailure(`query`),o3.warn({err:e,reason:e instanceof q4?e.reason:void 0},`[embeddings] query embed failed — degrading to lexical`)),null}if(!a)return null;let o=new Map;for(let e of t){let t=n.getVectors(e.id);if(!t||t.length===0)continue;let r=-1/0;for(let e of t){if(e.length!==a.length)continue;let t=oot(a,e);t>r&&(r=t)}r>-1/0&&o.set(e.id,r)}return o}};const Aot=/^[A-Za-z0-9-]{8,64}$/;let c3=null;function jot(e){return V(e??Bs(),`.ok`,mte)}function l3(e){if(e===void 0&&c3!==null)return c3;let t=jot(e),n=null;try{let e=G(t,`utf-8`).trim();Aot.test(e)&&(n=e)}catch{}if(n===null){n=ic();try{Ds(B(t),{recursive:!0}),Ls(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){K(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(c3=n),n}const u3=K(`process-lock`);var d3=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`OpenKnowledge ${n} already running at ${e.url??`port ${e.port}`} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function f3(e,t){return U(e,`${t}.lock`)}const p3=new Map;function Mot(e){p3.set(e,(p3.get(e)??0)+1)}function Not(e){let t=p3.get(e);return t===void 0||t<=1?(p3.delete(e),!0):(p3.set(e,t-1),!1)}function m3(e){return typeof e.machineId==`string`?e.machineId===l3():e.hostname===Vs()}const h3=new Set;let Pot=!1;function Fot(e){h3.add(e),!Pot&&(Pot=!0,process.on(`exit`,()=>{for(let e of h3)try{let t=JSON.parse(G(e,`utf-8`));if(t?.pid!==process.pid||typeof t.machineId==`string`&&t.machineId!==l3()||t.machineId===void 0&&typeof t.hostname==`string`&&t.hostname!==Vs())continue;Is(e)}catch{}}))}function Iot(e,t){try{let n=JSON.parse(G(e,`utf-8`));return n&&typeof n==`object`&&uW(n.pid)?n:(u3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return u3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null}}function Lot(e){try{return Dr()}catch(t){u3.warn({err:t},`${e} Not recording a channel: ${t instanceof Error?t.message:String(t)}`);return}}function Rot(e){return typeof e==`string`&&e.length>0?e:void 0}function zot(e){let{lockName:t,lockDir:n,metadata:r}=e,i=`[${t}-lock]`;Ds(n,{recursive:!0});let a=f3(n,t),o={pid:process.pid,hostname:Vs(),port:r.port,...r.url!==void 0&&{url:r.url},startedAt:new Date().toISOString(),worktreeRoot:r.worktreeRoot,machineId:l3(),...r.kind!==void 0&&{kind:r.kind},...r.parentPid!==void 0&&{parentPid:r.parentPid},...r.capabilities!==void 0&&{capabilities:r.capabilities},protocolVersion:r.protocolVersion??2,runtimeVersion:r.runtimeVersion??fQ,channel:Lot(i)},s=JSON.stringify(o,null,2);for(let e=0;e<3;e++){if(!W(a))try{let e=ks(a,`wx`,384);try{Rs(e,s)}finally{Ss(e)}return Mot(a),Fot(a),Bot({lockName:t,lockDir:n,lockPath:a})}catch(e){if(xG(e)!==`EEXIST`)throw e}let e=Iot(a,i);if(e){if(m3(e)&&e.pid===process.pid)return Ls(a,s,{encoding:`utf-8`,mode:384}),Mot(a),Fot(a),Bot({lockName:t,lockDir:n,lockPath:a});if(lW(e.pid))throw new d3(e,a,t);u3.warn({pid:e.pid,host:e.hostname},`${i} Stale lock detected (pid=${e.pid}, host=${e.hostname}) — replacing`)}try{Is(a)}catch{}}throw Error(`${i} Failed to acquire ${a} after 3 attempts (concurrent acquire contention).`)}function Bot(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>y3({lockName:t,lockDir:n}),updatePort:(e,r)=>_3({lockName:t,lockDir:n,port:e,url:r})}}function Vot(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function g3(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=Vot(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}function _3(e){let{lockName:t,lockDir:n,port:r,url:i}=e,a=`[${t}-lock]`,o=f3(n,t);if(!W(o)){u3.warn({lockPath:o},`${a} Lock file missing at ${o} during port update — skipping`);return}let s;try{let e=JSON.parse(G(o,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid)){u3.warn({lockPath:o},`${a} Corrupt lock at ${o} during port update — skipping`);return}s=e}catch{u3.warn({lockPath:o},`${a} Unreadable lock at ${o} during port update — skipping`);return}if(s.pid===process.pid&&m3(s)){s.port=r,i===void 0?delete s.url:s.url=i;try{Ls(o,JSON.stringify(s,null,2),{encoding:`utf-8`,mode:384})}catch(e){u3.warn({lockPath:o,err:e},`${a} Failed to update port in ${o}: ${e instanceof Error?e.message:String(e)}`)}}}function Hot(e){let{lockName:t,lockDir:n}=e,r=`[${t}-lock]`,i=f3(n,t);if((p3.get(i)??0)>1)return;let a;try{let e=JSON.parse(G(i,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid)){u3.warn({lockPath:i},`${r} Corrupt lock at ${i} during draining mark — skipping`);return}a=e}catch(e){xG(e)!==`ENOENT`&&u3.warn({lockPath:i,err:e},`${r} Unreadable lock at ${i} during draining mark — skipping: ${e instanceof Error?e.message:String(e)}`);return}if(a.pid===process.pid&&m3(a)&&a.draining!==!0){a.draining=!0;try{Ls(i,JSON.stringify(a,null,2),{encoding:`utf-8`,mode:384})}catch(e){u3.warn({lockPath:i,err:e},`${r} Failed to mark ${i} draining: ${e instanceof Error?e.message:String(e)}`)}}}function v3(e){let{lockName:t,lockDir:n}=e,r=f3(n,t);if(!W(r))return null;let i;try{let e=JSON.parse(G(r,`utf-8`));if(!e||typeof e!=`object`||!uW(e.pid))return null;i={...e,channel:Rot(e.channel)}}catch{return null}if(!m3(i))return null;if(!lW(i.pid)){try{Is(r)}catch{}return null}return i}function Uot(e){let{lockName:t,lockDir:n}=e,r=f3(n,t);if(!W(r))return{status:`absent`};let i;try{i=JSON.parse(G(r,`utf-8`))}catch{return{status:`incompatible`,reason:`corrupt`,raw:void 0}}if(!i||typeof i!=`object`)return{status:`incompatible`,reason:`corrupt`,raw:i};let a=i;if(!uW(a.pid)||typeof a.hostname!=`string`||typeof a.port!=`number`||typeof a.startedAt!=`string`||typeof a.worktreeRoot!=`string`)return{status:`incompatible`,reason:`corrupt`,raw:i};let o={pid:a.pid,hostname:a.hostname,port:a.port,url:typeof a.url==`string`?a.url:void 0,startedAt:a.startedAt,worktreeRoot:a.worktreeRoot,machineId:typeof a.machineId==`string`?a.machineId:void 0,draining:a.draining===!0||void 0,capabilities:Array.isArray(a.capabilities)&&a.capabilities.every(e=>typeof e==`string`)?a.capabilities:void 0,protocolVersion:typeof a.protocolVersion==`number`?a.protocolVersion:void 0,runtimeVersion:typeof a.runtimeVersion==`string`?a.runtimeVersion:void 0,channel:Rot(a.channel)};if(!m3(o))return{status:`stale`,lock:o};if(!lW(o.pid)){try{Is(r)}catch{}return{status:`stale`,lock:o}}return o.protocolVersion===void 0||o.runtimeVersion===void 0?{status:`incompatible`,reason:`missing-fields`,raw:i}:{status:`live`,lock:o}}async function Wot(e){let{lockName:t,lockDir:n}=e,r=e.timeoutMs??1e4,i=e.pollIntervalMs??100,a=e.readLock??(()=>v3({lockName:t,lockDir:n})),o=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a();if(s===null||s.draining!==!0)return`no-drain`;let c=Date.now()+r;for(;Date.now()<c;){await o(i);let e=a();if(e===null)return`released`;if(e.draining!==!0)return`no-drain`}return`timeout`}function y3(e){let{lockName:t,lockDir:n,deferUnlinkToExit:r=!1}=e,i=`[${t}-lock]`,a=f3(n,t);if(Not(a)){if(r){Hot({lockName:t,lockDir:n});return}if(W(a))try{let e=JSON.parse(G(a,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||!m3(e))return;Is(a),h3.delete(a)}catch(e){u3.warn({lockPath:a,err:e},`${i} Failed to release ${a}: ${e instanceof Error?e.message:String(e)}`)}}}var Got=jb({ServerLockCollisionError:()=>b3,acquireServerLock:()=>x3,lockAdvertisesUi:()=>C3,markServerLockDraining:()=>T3,readServerLock:()=>S3,releaseServerLock:()=>w3,updateServerLockPort:()=>Kot,waitForServerLockDrain:()=>qot}),b3=class extends d3{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function x3(e,t){try{return zot({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof d3&&e.lockName===`server`?new b3(e.existing,e.lockPath):e}}function Kot(e,t,n){_3({lockName:`server`,lockDir:e,port:t,url:n})}function S3(e){return v3({lockName:`server`,lockDir:e})}function C3(e){return!Array.isArray(e.capabilities)||e.capabilities.includes(`ui`)}function w3(e,t){y3({lockName:`server`,lockDir:e,...t})}function T3(e){Hot({lockName:`server`,lockDir:e})}function qot(e,t){return Wot({lockName:`server`,lockDir:e,...t})}function Jot(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,ready:a,serverInstanceId:o,getDiskAckSVs:s,getCollabClientCount:c,getConfigDiagnostics:l,acpRegistry:u,loadAcpCustomAgents:d,acpHarnessAvailability:f,isRoutePeerAdmitted:p,isAllowedWorkspaceHostHeader:m,checkLocalOpSecurity:h,getPrincipal:g,semanticSearch:_,readSemanticProviderConfig:v,embeddingsSecretsFile:y,getFileIndex:x,shadowRef:S,getCurrentBranch:C,getReportedBranch:w,installedAgentsCache:T}=e,E=X(_r,async(e,t)=>{try{a&&await a.catch(e=>{i.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=w?.()??void 0,n=s?.(),r=Bat(),l=c?.();Z(t,200,bte,{serverInstanceId:o,...e===void 0?{}:{currentBranch:e},...n===void 0?{}:{currentDiskAckSVs:n},...r===void 0?{}:{boot:r},...l===void 0?{}:{collabClients:l},runtimeVersion:fQ,protocolVersion:2},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),D=I({id:b(),name:b(),version:b(),description:b().optional(),license:b().optional(),iconUrl:b().optional(),website:b().optional(),source:ra([`registry`,`custom`]),supported:ka(),featured:ka(),harness:I({cli:ra([`claude`,`codex`,`cursor`,`gemini`,`opencode`,`pi`]),availability:ra([`present`,`not-found`,`unknown`]),credentials:ra([`present`,`unknown`])}).optional()}),O=I({agents:R(D),stale:ka(),maxThreads:Er()}),k=I({agentId:b(),reason:b().nullable(),candidates:R(I({value:b(),label:b(),description:b().nullable(),group:b().nullable(),contextChoices:R(Er()),context:I({effectiveTokens:Er(),origin:b()}).nullable(),selectability:b(),setPhase:b()}))}),A=X(_r,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`agent`)??``,r=e=>Z(t,200,k,{agentId:n,candidates:[],reason:e});if(n===``){Y(t,400,`urn:ok:error:invalid-request`,`An agent id is required.`,{handler:`acp-models`});return}if(n!==`codex-acp`){r(`unsupported`);return}if((await f()).codex?.availability!==`present`){r(`unavailable`);return}let a=kQ(),o=await Iat(`codex`,a);if(o.outcome===`not-found`){let e=await TQ(i)();e!==null&&(o=await Iat(`codex`,PQ(a,e)))}if(o.outcome!==`ok`){i.warn({agentId:n,outcome:o.outcome},`[acp-models] codex catalog probe failed`),r(`unavailable`);return}let s=o.models;if(s.length===0){r(`unavailable`);return}Z(t,200,k,{agentId:n,reason:null,candidates:Mat(s,{harness:`codex`,cliVersion:null,adapterVersion:null,endpoint:null,account:null},Date.now()).map(e=>({value:e.value,label:e.label,description:e.description,group:e.group,contextChoices:[...e.contextChoices],context:e.context,selectability:e.selectability,setPhase:e.setPhase}))})},{handler:`acp-models`}),j=X(_r,async(e,t)=>{if(u===void 0){Y(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=sH(),{agents:n,stale:r}=await u.getCatalog(),i=await d?.()??[],a=await f(),o=[...n.map(t=>{let n=S9e[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:rH.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]?.availability??`unknown`,credentials:a[n]?.credentials??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))];Z(t,200,O,{agents:o,stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function ee(e,t){if(!p(e.socket.remoteAddress)){Y(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!m(e.headers.host)){Y(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=g?.()??null;if(!n){Y(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}Z(t,200,cre,n,{handler:`principal`})}async function M(e,t){if(!p(e.socket.remoteAddress)){Y(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!m(e.headers.host)){Y(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=X5e.read();Z(t,200,Cie,{entries:n,count:n.length,detection:n7e(n[0])},{handler:`embed-detect`})}async function N(e,n){if(!p(e.socket.remoteAddress)){Y(n,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!m(e.headers.host)){Y(n,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){Y(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let r=U(t),a=r,o=!0;try{a=js(r)}catch(e){let t=xG(e);if(t===`ENOENT`)i.warn({path:r},`[workspace] contentDir does not exist; returning unresolved path`),o=!1;else{i.warn({path:r,err:e},`[workspace] realpath failed for contentDir`),Y(n,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:t??void 0,cause:e});return}}Z(n,200,jt,{contentDir:a,pathSeparator:gs,symlinkResolved:o},{handler:`workspace`})}async function P(e,t){if(h(e,t,{handler:`installed-agents`}))try{await W9e(e,t,T.probeAll)}catch(n){t.headersSent||(i.error({err:n,requestId:Kq(e)},`[installed-agents] route wrapper failed`),Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let te=n?aJ(n):null;async function ne(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Vat(e.headers),previewUrl:null,port:te?S3(te)?.port??0:0,singleFile:r};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}Z(t,200,ane,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function re(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=l?.()??{diagnostics:[]};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}Z(t,200,ye,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}Y(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let ie=X(_r,async(e,r)=>{try{let e=!1,i=!1,a=!1,o=!1,s=null,c=0;if(_){let t=_.getStatus();e=t.enabled,i=t.ready,a=t.capable,o=t.providerError,s=t.providerErrorReason,c=t.embeddedCount}let l=v?.()?.baseUrl??`https://api.openai.com/v1`,u=await $4(new i3(y),n??t,l),d=u.apiKey!==null,f=!d&&u.keyless,p=d?u.source:null,m=u.apiKey&&u.apiKey.length>=8?u.apiKey.slice(-4):null,h=0;for(let[e]of x())!sG(e)&&!cG(e)&&!Lee(e)&&(h+=1);Z(r,200,Cn,{enabled:e,keyPresent:d,keyNotRequired:f,keySource:p,keyHint:m,ready:i,capable:a,providerError:o,providerErrorReason:s,embedded:c,total:h},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),ae=(e,t)=>{let n=B(e);for(;n!==t&&n.startsWith(`${t}${gs}`);){try{vU(n)}catch(e){i.debug({err:e},`[rescue] empty-directory prune stopped (non-critical)`);return}n=B(n)}},oe={"/api/config":ne,"/api/config/diagnostics":re,"/api/server-info":E,"/api/principal":ee,"/api/workspace":N,"/api/semantic-status":ie,"/api/acp/catalog":j,"/api/acp/models":A,"/api/installed-agents":P,"/api/__embed-detect":M,"/api/rescue":X(_r,async(e,t)=>{try{if(!S?.current){Z(t,200,_re,[],{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}});return}let e=Date.now(),n=[],r=U(S.current.gitDir,`rescue`);if(W(r))try{let t=As(r,{encoding:`utf-8`,recursive:!0}).map(e=>e.replaceAll(gs,`/`)).filter(e=>KW(e)),a=js(r);for(let o of t){let t=U(r,o),s;try{s=js(t)}catch(e){i.warn({file:o,err:e},`[rescue] skipping unresolvable rescue entry`);continue}if(!yG(s,a)){i.warn({file:o,canonical:s},`[rescue] skipping rescue entry resolving outside the rescue directory`);continue}try{let t=Fs(s);if(!t.isFile())continue;if(e-t.mtimeMs>864e5){try{mU(s),ae(s,a)}catch(e){i.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:YW(o),timestamp:t.mtime.toISOString(),size:t.size,source:`flat`})}catch(e){i.warn({file:o,err:e},`[rescue] skipping uninspectable rescue entry`)}}}catch(e){i.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=C?.()??`main`,t=await BW(S.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){i.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}Z(t,200,_re,n,{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){Y(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0})};return{paths:Object.keys(oe),table:{resolve(e){let t=oe[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const Yot=K(`asset-references`),Xot=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function Zot(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function Qot(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),n=t.indexOf(`#`),r=n>=0?t.slice(0,n):t,i=r.indexOf(`?`);return i>=0?r.slice(0,i):r}function $ot(e){let t=Qot(e.href);if(!t||Zot(t))return!1;let n=e.literal?t:Iie(t);return cr.has(fs(n).slice(1).toLowerCase())}function est(e){return e?ost(e).filter($ot).map(e=>`${e.literal?`w`:`m`}\0${e.href}`).sort().join(``):``}function tst(e,t){return est(e)!==est(t)}function nst(e){let t=fs(e).slice(1).toLowerCase();return Ir(t)}function rst(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function ist(e,t){let n=(e,n)=>{let r=`${n?`w`:`m`} ${e}`;t.has(r)||t.set(r,{href:e,literal:n})};for(let t of O$e(e,{nestedBracketLabels:!0}))t.href&&n(t.href,!1);for(let t of D$e(e))n(t.target,!0);for(let t of e.matchAll(Xot)){let e=t[1]??t[2]??t[3]??t[4];e&&n(e,!1)}}function ast(e,t){let n=e,r=``;for(;n.length>0;){if(t.inComment){let e=n.indexOf(`-->`);if(e===-1)return r;n=n.slice(e+3),t.inComment=!1;continue}let e=n.indexOf(`<!--`);if(e===-1)return r+n;r+=n.slice(0,e),n=n.slice(e+4),t.inComment=!0}return r}function ost(e){let t=new Map,n=Ai(),r={inComment:!1};for(let i of e.replaceAll(`\r
1113
1113
  `,`
1114
1114
  `).replaceAll(`\r`,`
1115
1115
  `).split(`
package/dist/index.d.mts CHANGED
@@ -11860,6 +11860,7 @@ interface LanguageMetadata {
11860
11860
  }
11861
11861
  //#endregion
11862
11862
  //#region src/diagnose/os-termination-evidence.d.ts
11863
+ type OsTerminationSource = 'macos-jetsam' | 'linux-journal' | 'windows-event-log';
11863
11864
  interface CommandResult {
11864
11865
  status: number | null;
11865
11866
  stdout: string;
@@ -11875,6 +11876,37 @@ interface OsTerminationEvidenceDeps {
11875
11876
  systemRoot?: string;
11876
11877
  runCommand?: RunCommand;
11877
11878
  }
11879
+ interface ProcessTerminationQuery {
11880
+ pid: number;
11881
+ fromMs: number;
11882
+ toMs: number;
11883
+ }
11884
+ type ProcessTerminationLookup = {
11885
+ outcome: 'killed';
11886
+ source: Extract<OsTerminationSource, 'macos-jetsam'>;
11887
+ at: string | null;
11888
+ killReason: string;
11889
+ victimChosenByPriority: boolean;
11890
+ largestProcessOwned: boolean | null;
11891
+ residentBytes: number | null;
11892
+ reportsRead: number;
11893
+ } | {
11894
+ outcome: 'not-killed';
11895
+ reportsRead: number;
11896
+ unreadable: 0;
11897
+ unparseable: 0;
11898
+ skippedNewerOverCap: 0;
11899
+ } | {
11900
+ outcome: 'inconclusive';
11901
+ reportsRead: number;
11902
+ unreadable: number;
11903
+ unparseable: number;
11904
+ skippedNewerOverCap: number;
11905
+ } | {
11906
+ outcome: 'unavailable';
11907
+ unavailableReason: string;
11908
+ };
11909
+ declare function findJetsamKillSync(query: ProcessTerminationQuery, dir?: string): ProcessTerminationLookup;
11878
11910
  //#endregion
11879
11911
  //#region src/diagnose/bundle.d.ts
11880
11912
  interface DesktopMetadata {
@@ -12415,5 +12447,5 @@ interface ReportBundleResult {
12415
12447
  }
12416
12448
  declare function collectReportBundle(opts: CollectReportBundleOptions): Promise<ReportBundleResult>;
12417
12449
  //#endregion
12418
- export { ALL_EDITOR_IDS, type BundleExtraFile, type BundleLogger, type CliProbeContext, type CollectReportBundleOptions, EDITOR_LABELS, EDITOR_TARGETS, type EditorId, type EditorMcpResult, type EditorMcpTarget, type EnsurePiBridgeResult, type ExcludeWriteResult, type ExpectedShareRepo, type GhAccount, type GhDetectResult, HOSTS_WITH_USER_SKILL_DIR, type IntegrationWriteOutcome, LAUNCH_CONFIG_NAME, type LanguageMetadata, type LoadConfigResult, type McpConfigDeclineEvent, type McpConfigDeclineScope, type McpConfigMigrateEvent, type McpConfigMigrateScope, type McpDeclineReason, type McpEntryClassification, type McpInstallOptions, type McpRemoveOutcome, type OwnManagedMcpEntryHit, PATH_SHIM_BEGIN, PATH_SHIM_BLOCK_RE, PATH_SHIM_END, type ParsedGitHubBlobUrl, type ParsedGitHubShareTarget, type ParsedGitHubTreeUrl, type PathDiscovery, type PathInstallConsent, type PathInstallMarker, type PiBridgeFileState, type PiBridgeState, type PiBridgeWriteAction, type PiTrustState, type PiTrustWriteAction, type PreviewResult, type ProjectAiIntegrationsResult, ProjectPathSafetyError, type ProjectSkillRemoveResult, type ProjectSkillResult, type ReportBundleLevel, type ReportBundleResult, type ReportBundleSummary, type ResolveProjectRootOptions, type ResolveProjectRootResult, type ShareFolderValidationResult, type SharingMode, type SkillBundleTarget, type TokenStore, type TrackedRefusal, type UserMcpConfigsOptions, type UserSkillWriteResult, addOkPathsToGitExclude, assertProjectPathSafe, buildManagedServerEntry, buildMcpConfigDeclineEvent, buildMcpConfigMigrateEvent, classifyExistingMcpEntry, collectReportBundle, createCliProbeResolver, createTokenStore, defaultBugReportZipPath, detectGh, detectGhAccounts, detectInstalledEditors, droppedManagedKeys, editorConfigPathDisplay, editorEntryLocator, ensurePiBridge, formatTrackedRemediation, getExcludedOkPaths, getInstalledSkillProjectionPaths, getNativeTomlMcpEditor, getOkArtifactPaths, isEntryUpToDate, isOwnManagedEntry, loadConfig, makeLazyProbeTokenStore, okBugReportsDir, parseGitHubBlobUrl, parseGitHubShareUrl, parseGitHubTreeUrl, parseGitUrl, pathInstallMarkerPath, previewContent, probeOwnManagedEditorMcpEntry, probePiBridgeState, probeTrackedOkPaths, readExistingMcpEntry, readSharingMode, redactSecrets as redactContent, removeOkPathsFromGitExclude, removeOwnMcpEntry, removeProjectSkill, removeUserGlobalSkillBundle, removeUserSkill, resolveProjectRoot, runStop, truncatePriorEntry, userGlobalSkillBundleTargets, userSkillPresentAnywhere, validateLocalFolderForShare, writeEditorMcpConfig, writeProjectAiIntegrations, writeProjectSkill, writeUserMcpConfigs, writeUserSkill };
12450
+ export { ALL_EDITOR_IDS, type BundleExtraFile, type BundleLogger, type CliProbeContext, type CollectReportBundleOptions, EDITOR_LABELS, EDITOR_TARGETS, type EditorId, type EditorMcpResult, type EditorMcpTarget, type EnsurePiBridgeResult, type ExcludeWriteResult, type ExpectedShareRepo, type GhAccount, type GhDetectResult, HOSTS_WITH_USER_SKILL_DIR, type IntegrationWriteOutcome, LAUNCH_CONFIG_NAME, type LanguageMetadata, type LoadConfigResult, type McpConfigDeclineEvent, type McpConfigDeclineScope, type McpConfigMigrateEvent, type McpConfigMigrateScope, type McpDeclineReason, type McpEntryClassification, type McpInstallOptions, type McpRemoveOutcome, type OwnManagedMcpEntryHit, PATH_SHIM_BEGIN, PATH_SHIM_BLOCK_RE, PATH_SHIM_END, type ParsedGitHubBlobUrl, type ParsedGitHubShareTarget, type ParsedGitHubTreeUrl, type PathDiscovery, type PathInstallConsent, type PathInstallMarker, type PiBridgeFileState, type PiBridgeState, type PiBridgeWriteAction, type PiTrustState, type PiTrustWriteAction, type PreviewResult, type ProcessTerminationLookup, type ProcessTerminationQuery, type ProjectAiIntegrationsResult, ProjectPathSafetyError, type ProjectSkillRemoveResult, type ProjectSkillResult, type ReportBundleLevel, type ReportBundleResult, type ReportBundleSummary, type ResolveProjectRootOptions, type ResolveProjectRootResult, type ShareFolderValidationResult, type SharingMode, type SkillBundleTarget, type TokenStore, type TrackedRefusal, type UserMcpConfigsOptions, type UserSkillWriteResult, addOkPathsToGitExclude, assertProjectPathSafe, buildManagedServerEntry, buildMcpConfigDeclineEvent, buildMcpConfigMigrateEvent, classifyExistingMcpEntry, collectReportBundle, createCliProbeResolver, createTokenStore, defaultBugReportZipPath, detectGh, detectGhAccounts, detectInstalledEditors, droppedManagedKeys, editorConfigPathDisplay, editorEntryLocator, ensurePiBridge, findJetsamKillSync, formatTrackedRemediation, getExcludedOkPaths, getInstalledSkillProjectionPaths, getNativeTomlMcpEditor, getOkArtifactPaths, isEntryUpToDate, isOwnManagedEntry, loadConfig, makeLazyProbeTokenStore, okBugReportsDir, parseGitHubBlobUrl, parseGitHubShareUrl, parseGitHubTreeUrl, parseGitUrl, pathInstallMarkerPath, previewContent, probeOwnManagedEditorMcpEntry, probePiBridgeState, probeTrackedOkPaths, readExistingMcpEntry, readSharingMode, redactSecrets as redactContent, removeOkPathsFromGitExclude, removeOwnMcpEntry, removeProjectSkill, removeUserGlobalSkillBundle, removeUserSkill, resolveProjectRoot, runStop, truncatePriorEntry, userGlobalSkillBundleTargets, userSkillPresentAnywhere, validateLocalFolderForShare, writeEditorMcpConfig, writeProjectAiIntegrations, writeProjectSkill, writeUserMcpConfigs, writeUserSkill };
12419
12451
  //# sourceMappingURL=index.d.mts.map