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

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 (169) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-wrtiu3he.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.mjs +2 -2
  6. package/dist/init-BTikLoyL.mjs +1 -0
  7. package/dist/{init-iH-arA2G.mjs → init-Dq3WfDbj.mjs} +2 -2
  8. package/dist/{launch-json-removal-7EPfW1gR.mjs → launch-json-removal-qX8-XJPK.mjs} +1 -1
  9. package/dist/loader-D0q-s32o.mjs +1 -0
  10. package/dist/{loader-BPBqgr-2.mjs → loader-DUOg-rWT.mjs} +1 -1
  11. package/dist/{md-manager-BGnqyqi1-dBGkA2rR.mjs → md-manager-BGnqyqi1-CDSS__qm.mjs} +1 -1
  12. package/dist/{open-browser-BA4x7USG.mjs → open-browser-sLXj2Tjq.mjs} +1 -1
  13. package/dist/parse-worker.mjs +1 -1
  14. package/dist/preview-CBXCl1RF.mjs +1 -0
  15. package/dist/{preview-C8nGyFNQ.mjs → preview-lpcBYGW-.mjs} +1 -1
  16. package/dist/public/assets/{AccountSection-uEZl_mju.js → AccountSection-B-sg093H.js} +1 -1
  17. package/dist/public/assets/{ActivityModeContent-D6bm4kJT.js → ActivityModeContent-pMLiHbJ4.js} +1 -1
  18. package/dist/public/assets/{AddPropertiesButton-BbxqMedS.js → AddPropertiesButton-DAPZDZBf.js} +2 -2
  19. package/dist/public/assets/{AgentConnectionsSection-C4Y6AXkF.js → AgentConnectionsSection-BOlCjbB0.js} +1 -1
  20. package/dist/public/assets/{AgentDiffPane-DxqfS7to.js → AgentDiffPane-DNFvvXMS.js} +1 -1
  21. package/dist/public/assets/{AttachmentsSection-D4gD9K5F.js → AttachmentsSection-Bj2bn44o.js} +1 -1
  22. package/dist/public/assets/{AuthModal-SudaNBin.js → AuthModal-7ZC-1yVV.js} +1 -1
  23. package/dist/public/assets/{CodeMirrorPropInput-Buv5WUqJ.js → CodeMirrorPropInput-CvlzTFmP.js} +1 -1
  24. package/dist/public/assets/{ContentRulesSection-Br-l422Z.js → ContentRulesSection-D3VIuQW5.js} +1 -1
  25. package/dist/public/assets/{DiffViewBoundary-BEZkhnbH.js → DiffViewBoundary-Cue9UIPe.js} +1 -1
  26. package/dist/public/assets/{DocumentContext-CorZvYgo.js → DocumentContext-DC-7lORz.js} +28 -28
  27. package/dist/public/assets/{EditorModeToggle-CRzHwk_c.js → EditorModeToggle-CdPwhTIj.js} +1 -1
  28. package/dist/public/assets/{ExcalidrawDocEditor-EQVCkgpX.js → ExcalidrawDocEditor-CWvkhkI8.js} +1 -1
  29. package/dist/public/assets/FeedbackForm-Dpz_C_dG.js +1 -0
  30. package/dist/public/assets/{GraphPanel-fkRF4Ymc.js → GraphPanel-BmqiikMo.js} +1 -1
  31. package/dist/public/assets/{ImportSkillDialog-DuG9JEye.js → ImportSkillDialog-B41UQeNU.js} +1 -1
  32. package/dist/public/assets/{LinkPreviewsSection--PnKeBLD.js → LinkPreviewsSection-lDpKe_uM.js} +1 -1
  33. package/dist/public/assets/{LintConfigEditor-jcGxgQwc.js → LintConfigEditor-DBcSvcSj.js} +1 -1
  34. package/dist/public/assets/{LintingSection-Dvgj5Ttf.js → LintingSection-CLgNu_RF.js} +1 -1
  35. package/dist/public/assets/ManagedArtifactProperties-BCWOlZHH.js +1 -0
  36. package/dist/public/assets/{ManagedArtifactProperties-Bsvat-ju.js → ManagedArtifactProperties-BUR3J-fy.js} +1 -1
  37. package/dist/public/assets/{MermaidDocEditor-VR7GsjSm.js → MermaidDocEditor-BATUGASI.js} +1 -1
  38. package/dist/public/assets/{NetworkAccessSection-D43WDwx9.js → NetworkAccessSection-Cl9Ez7zC.js} +1 -1
  39. package/dist/public/assets/{ProjectTemplatesSection-B-AUPC6m.js → ProjectTemplatesSection-oiahzFKw.js} +1 -1
  40. package/dist/public/assets/{PropertyDisplayRow-CWrQAKBl.js → PropertyDisplayRow-DeM-qyex.js} +1 -1
  41. package/dist/public/assets/PublishToGitHubDialog-BcTZdODW.js +1 -0
  42. package/dist/public/assets/{RegisteredAgentIcon-DjlAkIlP.js → RegisteredAgentIcon-DKZ8eOKZ.js} +1 -1
  43. package/dist/public/assets/{SchemaConfigEditor-CGaJB0xn.js → SchemaConfigEditor-BfpRk4Uo.js} +1 -1
  44. package/dist/public/assets/{SearchSection-a8lszdwH.js → SearchSection-DMvWlkQa.js} +1 -1
  45. package/dist/public/assets/{SessionsHost-BjkYqOzo.js → SessionsHost-B-miajUh.js} +2 -2
  46. package/dist/public/assets/{SettingsDialogBody-Cg5j6OJH.js → SettingsDialogBody-B9vT68l0.js} +2 -2
  47. package/dist/public/assets/{ShareReceiveMissDialog-DRGvyccq.js → ShareReceiveMissDialog-CZX-95Jt.js} +1 -1
  48. package/dist/public/assets/{SkillCostValue-CzBUsuYu.js → SkillCostValue-DPX8ruMM.js} +1 -1
  49. package/dist/public/assets/{SkillForkDialog-QqHr4a1o.js → SkillForkDialog-BB_XS1nP.js} +1 -1
  50. package/dist/public/assets/{SkillInstallMenu-BQHSpQsX.js → SkillInstallMenu-CAjgsxCn.js} +1 -1
  51. package/dist/public/assets/{SkillOriginInline-DzV3iN2B.js → SkillOriginInline-D1tWqOqr.js} +1 -1
  52. package/dist/public/assets/{SkillToolbarControls-uJO_ykPP.js → SkillToolbarControls-D2HDArnM.js} +1 -1
  53. package/dist/public/assets/{SkillsManagerSection-DJfOBpFG.js → SkillsManagerSection-B0OJHWNm.js} +1 -1
  54. package/dist/public/assets/{SlidesPluginSection-Dc5MqsXL.js → SlidesPluginSection-Bi8J2lVH.js} +1 -1
  55. package/dist/public/assets/{SlidesToolbarControls-BpcUGXo9.js → SlidesToolbarControls-CqXBuf70.js} +1 -1
  56. package/dist/public/assets/{SourceEditor-D0RSGDUt.js → SourceEditor-JMQvF10s.js} +1 -1
  57. package/dist/public/assets/{SpellingSettings-DUJM89JE.js → SpellingSettings-Dkdy9B2q.js} +1 -1
  58. package/dist/public/assets/{SyncSection-CRG2LkSG.js → SyncSection-DhDmLVAd.js} +1 -1
  59. package/dist/public/assets/{SyncStatusBadge-DoYJzvIT.js → SyncStatusBadge-DvzQHe2r.js} +1 -1
  60. package/dist/public/assets/{TemplateRow-xwZoU5JB.js → TemplateRow-DoNZxhIJ.js} +1 -1
  61. package/dist/public/assets/{TerminalLaunchContext-CJTkwtCs.js → TerminalLaunchContext-Cwrrh5Ck.js} +1 -1
  62. package/dist/public/assets/{TerminalPanel-Ch3gwsVs.js → TerminalPanel-C5LSq4fA.js} +1 -1
  63. package/dist/public/assets/{TerminalSection-6ExXD5z5.js → TerminalSection-CnDoHJjb.js} +1 -1
  64. package/dist/public/assets/{TerminalWindowApp-B2mnEA0Z.js → TerminalWindowApp-BYY1ZBqZ.js} +1 -1
  65. package/dist/public/assets/{TextDocEditor-CzwNYI5Q.js → TextDocEditor-BCj5KFCT.js} +1 -1
  66. package/dist/public/assets/{ThemePluginSection-CizNpiAG.js → ThemePluginSection-BT1NQe1R.js} +1 -1
  67. package/dist/public/assets/{ThreadView-CAfBkY-n.js → ThreadView-BSxFKhGS.js} +5 -5
  68. package/dist/public/assets/{TimelineDiffPane-Oj5zOvzN.js → TimelineDiffPane-D6rzpzG-.js} +1 -1
  69. package/dist/public/assets/_envelope-g8Le8UBe-6j_3zVcA.js +1 -0
  70. package/dist/public/assets/{agent-connections-D2w6claM.js → agent-connections-CykO_Ezy.js} +1 -1
  71. package/dist/public/assets/{agent-registry-B4dxoiaL.js → agent-registry-pREadnY_.js} +1 -1
  72. package/dist/public/assets/{bridge-DsUUjTsy.js → bridge-D8Oy74FE.js} +1 -1
  73. package/dist/public/assets/{card-DdkXkyr5.js → card-DJoKetZ9.js} +1 -1
  74. package/dist/public/assets/{catalog-Bdh906tM.js → catalog-CJ_rs_wb.js} +1 -1
  75. package/dist/public/assets/{comment-chips-DNwQbxLO.js → comment-chips-DPeaMDJc.js} +2 -2
  76. package/dist/public/assets/{config-provider-2W1hFFiT.js → config-provider-Lqk8ioh6.js} +1 -1
  77. package/dist/public/assets/config-schema-Dh_H8E-u.js +1 -0
  78. package/dist/public/assets/{css-color-to-hex-D-oM_f97.js → css-color-to-hex-Cjxd2Xbp.js} +1 -1
  79. package/dist/public/assets/{doc-undo-manager-1o5q5gwi.js → doc-undo-manager-DeFaVIhm.js} +1 -1
  80. package/dist/public/assets/field-controls-C6S4B1Im.js +1 -0
  81. package/dist/public/assets/{field-controls-BLwJrin4.js → field-controls-DSwLWrMh.js} +1 -1
  82. package/dist/public/assets/{frontmatter-tags-DIPhIb6q.js → frontmatter-tags-CoOxl3mC.js} +1 -1
  83. package/dist/public/assets/{handoff-ClTYrgLm.js → handoff-pwpLEUcJ.js} +1 -1
  84. package/dist/public/assets/index-CrA6lcEJ.js +2205 -0
  85. package/dist/public/assets/{lint-config-client-DhP_RDHH.js → lint-config-client-DDZrpVHz.js} +1 -1
  86. package/dist/public/assets/{lint-plugins-BTxsaGaY.js → lint-plugins-C0gXWWZ4.js} +1 -1
  87. package/dist/public/assets/{markdown-lint-BmjyI9ZU.js → markdown-lint-DeZBsw3J.js} +1 -1
  88. package/dist/public/assets/{markdownlint-rule-browser-BADH1Lka.js → markdownlint-rule-browser-60Esn3tM.js} +1 -1
  89. package/dist/public/assets/messages-78IX_mb6.js +1 -0
  90. package/dist/public/assets/messages-B6BYNmqo.js +1 -0
  91. package/dist/public/assets/messages-B8EWK_89.js +1 -0
  92. package/dist/public/assets/messages-BBf4KTqG.js +1 -0
  93. package/dist/public/assets/messages-Bwl4NQMF.js +1 -0
  94. package/dist/public/assets/messages-D8vS5v1Q.js +1 -0
  95. package/dist/public/assets/messages-DE1vIF6g.js +1 -0
  96. package/dist/public/assets/messages-DMLet84f.js +1 -0
  97. package/dist/public/assets/messages-DTOPrMXM.js +1 -0
  98. package/dist/public/assets/messages-DZEtkTdx.js +1 -0
  99. package/dist/public/assets/messages-DaxVzGDb.js +1 -0
  100. package/dist/public/assets/messages-GFEtxKER.js +1 -0
  101. package/dist/public/assets/messages-TMbZtDXU.js +1 -0
  102. package/dist/public/assets/{pending-receive-nav-store-CsnZS_Ro.js → pending-receive-nav-store-D4laa5dZ.js} +1 -1
  103. package/dist/public/assets/{preferred-session-events-DhdzT8Vr.js → preferred-session-events-DsiWPBIO.js} +1 -1
  104. package/dist/public/assets/{progress-CLlmYVN5.js → progress-DN2Oudrp.js} +1 -1
  105. package/dist/public/assets/{saved-themes-client-CSjCi4YD.js → saved-themes-client-ByYw6oZt.js} +1 -1
  106. package/dist/public/assets/{schema-section-H3icVnyE.js → schema-section-C8DGjvNX.js} +1 -1
  107. package/dist/public/assets/{schemas-api-BbYGQuTW.js → schemas-api-CQHNNDP6.js} +1 -1
  108. package/dist/public/assets/{selection-context-BiUjqAKb.js → selection-context-CwNOeaoR.js} +1 -1
  109. package/dist/public/assets/{skills-api-DronAhV9.js → skills-api-B7NWq2mZ.js} +1 -1
  110. package/dist/public/assets/{src-DGY0VXnv.js → src-CsC2tmDo.js} +1 -1
  111. package/dist/public/assets/storage-scope-lp6Y3sn1.js +1 -0
  112. package/dist/public/assets/{tag-pill-input-etcmLbrt.js → tag-pill-input-C9tJ_ebG.js} +1 -1
  113. package/dist/public/assets/terminal-cli-display-Bn8rI2FY.js +1 -0
  114. package/dist/public/assets/{terminal-command-events-DylLB9_L.js → terminal-command-events-DYVYsw0p.js} +1 -1
  115. package/dist/public/assets/{terminal-launch-events-BCKO9apj.js → terminal-launch-events-C1I24zal.js} +1 -1
  116. package/dist/public/assets/{typing-burst-detector-BvJppmhO.js → typing-burst-detector-aPxMRU8C.js} +3 -3
  117. package/dist/public/assets/{uninstall-Bo2t4rIS.js → uninstall-Dg977zNF.js} +1 -1
  118. package/dist/public/assets/{use-activity-panel-vwUB_0Q4.js → use-activity-panel-BdGyV72n.js} +1 -1
  119. package/dist/public/assets/{use-apply-config-color-theme-DiRXrQH-.js → use-apply-config-color-theme-B9f6n0Cd.js} +1 -1
  120. package/dist/public/assets/{use-apply-config-language-D-iaXzSu.js → use-apply-config-language-CdocdaSu.js} +2 -2
  121. package/dist/public/assets/{use-conflicts-E9tj1NHs.js → use-conflicts-BJFBAg9M.js} +1 -1
  122. package/dist/public/assets/{use-live-xterm-theme-DnTcPzv0.js → use-live-xterm-theme-CMmPbV7u.js} +1 -1
  123. package/dist/public/assets/{use-open-skill-D0ybF2gq.js → use-open-skill-CzCqi5yc.js} +1 -1
  124. package/dist/public/assets/{use-semantic-search-status-Bq4BpHMI.js → use-semantic-search-status-Cqw3SIgk.js} +1 -1
  125. package/dist/public/assets/{use-skill-origin-BnTpq9XZ.js → use-skill-origin-f6iU7bK5.js} +1 -1
  126. package/dist/public/assets/{use-skill-targets-DcxmfKVk.js → use-skill-targets-CcZTp1aJ.js} +1 -1
  127. package/dist/public/assets/{use-skills-D9Qpt2AT.js → use-skills-D4I9tjyB.js} +1 -1
  128. package/dist/public/assets/{use-terminal-enabled-BAfmRgEk.js → use-terminal-enabled-C2NWQnj5.js} +1 -1
  129. package/dist/public/assets/{use-timeline-entry-diff-CFyLJSDJ.js → use-timeline-entry-diff-Be_f_psH.js} +1 -1
  130. package/dist/public/assets/{use-workspace-Dyz_XHeI.js → use-workspace-CF2-WOaH.js} +1 -1
  131. package/dist/public/index.html +51 -51
  132. package/dist/public/uninstall.html +3 -3
  133. package/dist/{registry-probes-CM3GVnGY.mjs → registry-probes-DVlbg9fU.mjs} +1 -1
  134. package/dist/{removal-file-path-oz6iBHDK.mjs → removal-file-path-g2whvROV.mjs} +1 -1
  135. package/dist/{repair-launch-json-DNSuSUsH.mjs → repair-launch-json-BoM_oJot.mjs} +1 -1
  136. package/dist/{repair-mcp-configs-Bahn7_bp.mjs → repair-mcp-configs-Dj1r0_M_.mjs} +1 -1
  137. package/dist/{src-BqzHUD_W.mjs → src-CEYk-9sD.mjs} +1 -1
  138. package/dist/src-D6JjXaXI.mjs +1 -0
  139. package/dist/start-B57g27Ca.mjs +1 -0
  140. package/dist/{start-CEEWMHcQ.mjs → start-BJLoX9Jn.mjs} +3 -3
  141. package/package.json +4 -4
  142. package/dist/constants-D5w683OR.mjs +0 -1
  143. package/dist/init-CzUtIxs8.mjs +0 -1
  144. package/dist/loader-C15d7cmm.mjs +0 -1
  145. package/dist/preview-CVz9i5jg.mjs +0 -1
  146. package/dist/public/assets/FeedbackForm-B3LCnaN-.js +0 -1
  147. package/dist/public/assets/ManagedArtifactProperties-DQGljSd5.js +0 -1
  148. package/dist/public/assets/PublishToGitHubDialog-C3wLeehy.js +0 -1
  149. package/dist/public/assets/_envelope-Dwl6i2K9-DPqJ_Q4W.js +0 -1
  150. package/dist/public/assets/config-schema-DSj91SAu.js +0 -1
  151. package/dist/public/assets/field-controls-BxZbpvVJ.js +0 -1
  152. package/dist/public/assets/index-ClMapCCf.js +0 -2205
  153. package/dist/public/assets/messages-BT33WTY4.js +0 -1
  154. package/dist/public/assets/messages-B_gBh8es.js +0 -1
  155. package/dist/public/assets/messages-BkJsr6GH.js +0 -1
  156. package/dist/public/assets/messages-CUhRQF6Z.js +0 -1
  157. package/dist/public/assets/messages-CfM_V0is.js +0 -1
  158. package/dist/public/assets/messages-Cilh2EEK.js +0 -1
  159. package/dist/public/assets/messages-CoC6kH02.js +0 -1
  160. package/dist/public/assets/messages-D8jal7DN.js +0 -1
  161. package/dist/public/assets/messages-DHbSVEtI.js +0 -1
  162. package/dist/public/assets/messages-DlgKcLpa.js +0 -1
  163. package/dist/public/assets/messages-Dot6gpGm.js +0 -1
  164. package/dist/public/assets/messages-Dy_NuDHm.js +0 -1
  165. package/dist/public/assets/messages-Zy-8a3Uz.js +0 -1
  166. package/dist/public/assets/storage-scope-DSPgNqch.js +0 -1
  167. package/dist/public/assets/terminal-cli-display-BbrhD8t2.js +0 -1
  168. package/dist/src-DKF_fAWB.mjs +0 -1
  169. 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.mjs CHANGED
@@ -189,7 +189,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
189
189
  `)].join(`
190
190
  `);case`REMOVED_KEY`:{let t=e.path.join(`.`),n=[`${e.source?`Removed key at ${e.source.file}:${e.source.line}:${e.source.column}`:`Removed key in configuration`}: ${t}`,e.redirect];if(e.source?.snippet&&e.source.snippet.length>0)for(let t of e.source.snippet.split(`
191
191
  `))n.push(` ${t}`);return n.join(`
192
- `)}case`NOT_SYNCED`:return`Settings are still loading. Try again in a moment.`;case`WRITE_ERROR`:return`Failed to write config file: ${e.detail}`;case`OKIGNORE_INVALID`:return e.lineNumber===void 0?`.okignore: ${e.detail}`:`.okignore line ${e.lineNumber}: ${e.detail}`;case`UNKNOWN`:return e.message??`Unknown error.`}}function xie(e,t,n){return $d([e,t,n],[])}function $d(e,t){if(t.length>0){let n=hu(fu,t);if(n?.scope===`user`)return e[0];if(n?.scope===`project`)return e[1]??e[0];if(n?.scope===`project-local`)return e[2]??e[0]}let n=Sie(e);if(n===void 0)return;if(n===null)return null;if(Array.isArray(n)||typeof n!=`object`)return n;let r=e.map(e=>Cie(e)?e:void 0),i=new Set;for(let e of r)if(e!==void 0)for(let t of Object.keys(e))i.add(t);let a={};for(let e of i)a[e]=$d(r.map(t=>t===void 0?void 0:t[e]),[...t,e]);return a}function Sie(e){for(let t=e.length-1;t>=0;t--)if(e[t]!==void 0)return e[t]}function Cie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const wie=Object.freeze([`__config__/project`,`__local__/project`,`__user__/config.yml`,`__config__/okignore`]),ef=[`project`,`global`];function Tie(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)||e.startsWith(`__extskill__/`)}const tf=[`.mdx`,`.md`],nf={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},Eie=rt.stable.mcpServerName,Die=[`exec`,`search`,`history`,`links`,`skills`,`config`,`palette`,`preview_url`,`share_link`,`lint`,`audit`,`write`,`edit`,`delete`,`move`,`install`,`import`,`checkpoint`,`restore_version`];function Oie(e){if(e.length===0)return{ok:!1,reason:`docName must not be empty`};if(e.trim().length===0)return{ok:!1,reason:`docName must not be blank (whitespace only)`};if(e!==e.trim())return{ok:!1,reason:`docName must not have leading or trailing whitespace`};for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return{ok:!1,reason:`docName must not contain control characters`}}if(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\\`))return{ok:!1,reason:`docName must not contain "..", a leading "/", or a backslash`};for(let t of e.split(`/`)){if(t.length===0)return{ok:!1,reason:`docName must not contain empty path segments (no leading, trailing, or doubled "/")`};if(t.startsWith(`.`))return{ok:!1,reason:`docName path segments must not start with "." (hidden files are not addressable)`}}return{ok:!0}}const rf=B(I().min(1)).max(50),kie=U([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),Aie=V({label:I().min(1),webUrl:Ii().nullable(),transport:U([`https`,`http`,`ssh`,`git`]).optional()}).loose(),jie=pa(`checkStatus`,[V({checkStatus:W(`allowed`)}).loose(),V({checkStatus:W(`denied`),deniedReason:U([`no-collaborator`,`private-no-access`,`repo-not-found`,`not-authenticated`]),resolvedLogin:I().optional(),declaredLogin:I().optional(),declaredSource:I().optional()}).loose(),V({checkStatus:W(`unknown`),unknownError:U([`network`,`timeout`,`rate-limit`,`token-invalid`,`malformed-response`,`ssh-unverified`]).optional()}).loose()]),af=U([`auth-403`,`auth-401`,`auth-scope-mismatch`,`auth-no-credential`,`auth-not-found-as-identity`,`semantic-protected-branch`]),Mie=U(vc),Nie=U([`succeeded`,`up-to-date`,`conflict`,`refused`,`error`]);V({state:kie,lastSyncUtc:I().nullable(),lastRunUtc:I().nullable().optional(),lastPullOkUtc:I().nullable().optional(),lastPushOkUtc:I().nullable().optional(),lastFetchUtc:I().nullable(),lastPushedSha:I().nullable(),ahead:L().int().min(0),behind:L().int().min(0),consecutiveFailures:L().int().min(0),consecutivePushFailures:L().int().min(0).optional(),conflictCount:L().int().min(0),hasRemote:R(),syncEnabled:R(),identityUnresolved:R(),remote:Aie.nullable().optional(),pushError:I().optional(),pushErrorCode:af.optional(),pullError:I().optional(),pullErrorCode:af.optional(),pausedReason:I().optional(),blockingPaths:B(I().min(1)).optional(),refusedSymlinkPaths:rf.optional(),pushPermission:jie.optional(),syncMode:Mie.optional(),lastPullUtc:I().nullable().optional(),lastPullOutcome:Nie.nullable().optional()}).loose(),V({action:U([`commit`]),paths:B(I().min(1)),commitSha:I().optional()}).loose(),V({action:U([`commit`])}).loose(),V({op:U([`sync`,`push`,`pull`,`fetch`]).optional()}).loose(),V({op:U([`sync`,`push`,`pull`,`fetch`])}).loose();const of=U([`merge-native`,`working-tree`,`reconcile`]),sf=U([`merged-with-markers`,`refused-conflict-markers`,`refused-no-base`,`refused-too-large`,`disk-markers`,`stale-external-write`]),Pie=U([`mine`,`theirs`,`content`,`delete`]);V({conflicts:B(V({file:I().min(1),detectedAt:I().min(1),conflict:of,reason:sf.optional().catch(void 0),conflictKind:U([`git`,`stale-external-write`]).optional(),docName:I().nullable(),theirsSha:I().optional(),baseSha:I().optional()}).loose())}).loose(),V({file:I().min(1),strategy:U([`mine`,`theirs`,`content`,`delete`]),content:I().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content must be provided when strategy is 'content' (an empty string keeps an empty file)`,path:[`content`]}),V({}).loose(),V({file:I().min(1),base:I(),ours:I(),theirs:I(),kind:U([`both-modified`,`delete-modify`,`modify-delete`]),conflict:of,reason:sf.optional().catch(void 0),conflictKind:U([`git`,`stale-external-write`]).optional(),resolutionOptions:B(Pie)}).loose(),V({plan:Ea(e=>e!==void 0,{message:`plan is required`})}).loose(),V({plan:Ea(e=>e!==void 0,{message:`plan is required`})}).loose(),V({result:Ea(e=>e!==void 0,{message:`result is required`})}).loose(),V({packId:I().min(1)}).strict(),V({installedHosts:B(I()),skills:B(V({name:I().min(1),created:R()}).strict())}).strict();const Fie=V({path:I().min(1),summary:I().min(1)}).loose(),Iie=V({files:L().int().nonnegative(),folders:L().int().nonnegative()}).loose();V({packs:B(V({id:I().min(1),name:I().min(1),description:I().min(1),defaultSubfolder:I().optional(),folders:B(Fie),entryCounts:Iie}).loose())}).loose(),V({noOpen:R().optional(),out:I().min(1).optional()}).loose();const Lie=V({reason:U([`unsupported-platform`,`spawn-error`]),message:I()}).loose();pa(`status`,[V({status:W(`installed`),outputPath:I(),size:L().int().nonnegative(),sha256:I(),skillVersion:I()}).loose(),V({status:W(`built`),outputPath:I(),size:L().int().nonnegative(),sha256:I(),skillVersion:I(),handoffError:Lie.optional()}).loose(),V({status:W(`failed`),buildError:I()}).loose(),V({status:W(`skip-current`),skillVersion:I(),recordedAt:I().optional()}).loose()]),pa(`kind`,[V({kind:W(`doc`),docPath:I().min(1)}).loose(),V({kind:W(`folder`),folderPath:I()}).loose()]);const cf=U([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`unsupported-share-url`]),lf=U([`current`,`stale`,`absent`,`empty`]);pa(`ok`,[V({ok:W(!0),shareUrl:I().min(1),sharedUrl:I().min(1),branch:I().min(1),freshness:lf.optional().catch(void 0)}).loose(),V({ok:W(!1),error:cf,branch:I().min(1).optional()}).loose()]);const Rie=U([`user`,`org`]),zie=V({login:I().min(1),kind:Rie,avatarUrl:I().optional()}).loose(),uf=U([`auth-required`,`network`]);pa(`ok`,[V({ok:W(!0),owners:B(zie)}).loose(),V({ok:W(!1),error:uf}).loose()]),pa(`ok`,[V({ok:W(!0),available:R()}).loose(),V({ok:W(!1),error:uf}).loose()]);const Bie=U([`public`,`private`]);V({owner:I().min(1),name:I().min(1),visibility:Bie,description:I().optional()}).loose();const Vie=U([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);pa(`ok`,[V({ok:W(!0),ownerLogin:I().min(1),repoName:I().min(1),cloneUrl:I().min(1),defaultBranch:I().min(1)}).loose(),V({ok:W(!1),error:Vie}).loose()]);function df(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const ff=e=>e.refine(df,`invalid branch name`),pf={shareTargetExists:R(),dirtyConflicts:V({conflicts:R(),files:B(I().min(1))}).loose(),branchIsLocal:R(),shareTargetOnOriginBranch:R().optional()};pa(`detached`,[V({detached:W(!1),currentBranch:I().min(1).nullable(),currentHeadSha:ra(),...pf}).loose(),V({detached:W(!0),currentBranch:ra(),currentHeadSha:I().min(1),...pf}).loose()]),V({branch:ff(I().min(1)),principalId:I().optional(),fastForward:R().optional()}).loose();const Hie=U([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`,`branch-in-other-worktree`,`ff-diverged`,`unsafe-symlinks`,`symlink-check-failed`]);pa(`ok`,[V({ok:W(!0)}).loose(),V({ok:W(!1),reason:Hie,files:B(I().min(1)).optional(),otherWorktreePath:I().min(1).optional(),refusedSymlinkPaths:rf.optional()}).loose()]),U([`on-origin`,`renamed`,`deleted`,`never-on-branch`,`changed-locally`,`unknown`]),V({branch:ff(I().min(1)),path:I(),kind:U([`doc`,`folder`]),contentRootDepth:L().int().min(1).max(65535).optional()}).loose(),pa(`verdict`,[V({verdict:W(`on-origin`)}).loose(),V({verdict:W(`renamed`),renamedTo:I().min(1)}).loose(),V({verdict:W(`deleted`)}).loose(),V({verdict:W(`never-on-branch`)}).loose(),V({verdict:W(`changed-locally`)}).loose(),V({verdict:W(`unknown`)}).loose()]).catch({verdict:`unknown`});function mf(e,t){let n=Oie(e);n.ok||t.addIssue({code:`custom`,message:n.reason})}const hf=I().superRefine(mf).optional(),Uie=I().superRefine(mf),gf={agentId:I().optional(),agentName:I().optional(),colorSeed:I().optional(),clientName:I().optional(),clientVersion:I().optional(),label:I().optional()},_f=I().optional(),Wie=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Gie=V({startedAt:I().min(1),httpListenMs:L().nonnegative().optional(),seedWalkMs:L().nonnegative().optional(),indexesMs:L().nonnegative().optional(),readyMs:L().nonnegative().optional(),fileCount:L().nonnegative().optional()});V({serverInstanceId:I().min(1),currentBranch:I().min(1).optional(),currentDiskAckSVs:H(I().min(1),I().min(1)).optional(),boot:Gie.optional(),collabClients:L().int().nonnegative().optional()}).loose(),V({id:I().min(1),display_name:I().min(1),display_email:I(),source:U([`git-config`,`synthesized`]),created_at:I().min(1)}).loose(),V({collabUrl:I().nullable(),previewUrl:I().nullable(),port:L(),singleFile:R().default(!1)}).loose();const vf=U(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:symlink-refused.urn:ok:error:links-not-permitted.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:unsupported-media-type.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:derived-index-unavailable.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:frontmatter-malformed.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:disk-divergence.urn:ok:error:stale-external-write.urn:ok:error:store-refused.urn:ok:error:doc-removed.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:non-github-origin.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:concurrent-overwrite-refused.urn:ok:error:unresolved-conflict-markers.urn:ok:error:no-conflict-tracked.urn:ok:error:no-blocking-changes.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:single-file-mode.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed.urn:ok:error:registry-unreachable.urn:ok:error:config-not-writable.urn:ok:error:audit-superseded.urn:ok:error:theme-name-taken.urn:ok:error:theme-name-invalid`.split(`.`)),Kie=V({type:vf,title:I().min(1),status:L().int().min(400).max(599),instance:I().regex(Wie,`instance must be urn:uuid:<uuid>`).optional(),detail:I().optional()}).loose();V({parentDocName:I().min(1),placement:U([`configured-attachments`,`parent-dir`]).default(`configured-attachments`),agentId:I().min(1).optional(),agentName:I().min(1).optional()}).loose(),V({src:I().min(1),path:I().min(1).optional(),deduped:R().optional()}).loose(),V({url:I().min(1),dir:I().min(1),branch:I().min(1).refine(df,`invalid branch name`).optional()}).loose(),V({type:W(`error`),problem:Kie}).loose(),V({docName:hf,summary:_f,content:I().optional(),...gf}).loose(),V({docName:hf,summary:_f,markdown:I(),position:U([`append`,`prepend`,`replace`]).optional(),extension:U(tf).optional(),...gf}).loose(),V({docName:hf,summary:_f,find:I().min(1),replace:I(),offset:L().int().nonnegative().optional(),...gf}).loose(),V({docName:hf,connectionId:I().min(1),scope:U([`last`,`session`,`file`,`count`]).optional(),count:L().int().positive().optional(),...gf}).loose().refine(e=>e.scope!==`count`||e.count!==void 0,{message:`count is required when scope is 'count'`,path:[`count`]});const yf=V({value:I(),truncatedFrom:L().int().nonnegative().optional(),hint:I().optional()}).loose(),qie=pa(`kind`,[V({kind:W(`inline`),content:I()}),V({kind:W(`truncated`),byteLength:L().int().nonnegative(),hint:I()})]),bf=V({kind:W(`content-divergence`),intendedBytes:L().int().nonnegative(),actualBytes:L().int().nonnegative(),byteDelta:L().int(),divergenceType:I().optional(),currentState:qie.optional(),hint:I().optional()}).loose(),Jie=V({type:W(`orphan`),parentCandidates:B(I()),message:I()}).loose(),xf=V({kind:W(`disk-edit-reconciled`),intendedBytes:L().int().nonnegative(),actualBytes:L().int().nonnegative(),byteDelta:L().int(),mergeOutcome:I().optional(),hint:I().optional()}).loose();pa(`kind`,[bf,xf]);const Yie=Object.keys({"content-divergence":!0,"disk-edit-reconciled":!0}),Xie=V({kind:W(`mermaid-parse-error`),fenceIndex:L().int().positive(),fenceFirstLine:I(),message:I(),line:L().int().positive().optional()}).loose(),Sf=V({href:I(),targetKind:I(),role:I(),sourceForm:I(),resolvedTarget:I().nullable(),reason:I(),resolutionMethod:I(),fallbackTarget:I().nullable().optional(),definition:V({line:L().int().nonnegative(),label:I()}).loose().optional()}).loose(),Cf=pa(`kind`,[bf,xf,Xie,V({kind:W(`lint-violation`),source:I(),code:I(),message:I(),severity:U([`error`,`warning`,`info`,`hint`]),line:L().int().positive(),column:L().int().positive(),linkTarget:I().optional(),localTarget:Sf.optional()}).loose(),V({kind:W(`link-check-deferred`),message:I()}).loose()]),wf=B(Cf).min(1),Tf=V({href:I(),resolvedTo:I().nullable(),reason:U([`no-such-doc`,`no-such-file`,`unresolvable`,`excluded`]),localTarget:Sf.optional()}).loose(),Ef=B(Tf),Df=V({reason:I().min(1),count:L().int().positive()}).loose();V({timestamp:I().min(1),summary:yf.optional(),warnings:wf.optional()}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),hints:B(Jie).optional(),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({docName:I().min(1),scope:U([`last`,`session`,`count`]),undone:R()}).loose(),V({docs:B(V({docName:Uie,markdown:I(),position:U([`append`,`prepend`,`replace`]).optional(),extension:U(tf).optional(),summary:_f}).loose()).min(1).max(100),...gf}).loose();const Zie=V({type:vf,title:I(),detail:I().optional()}).loose(),Qie=pa(`status`,[V({status:W(`written`),docName:I().min(1),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({status:W(`error`),docName:I().min(1),error:Zie}).loose()]);V({timestamp:I().min(1),results:B(Qie),written:L().int().nonnegative(),failed:L().int().nonnegative()}).loose(),V({docName:hf,patch:H(I(),fa([bo,ra()])),types:H(I(),U(vo)).optional(),summary:_f,...gf}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),appliedKeys:B(I()),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose();function Of(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}const kf=Rf(/[A-Za-z]/),Af=Rf(/[\dA-Za-z]/),$ie=Rf(/[#-'*+\--9=?A-Z^-~]/);function jf(e){return e!==null&&(e<32||e===127)}const Mf=Rf(/\d/),eae=Rf(/[\dA-Fa-f]/),tae=Rf(/[!-/:-@[-`{-~]/);function Nf(e){return e!==null&&e<-2}function Pf(e){return e!==null&&(e<0||e===32)}function Ff(e){return e===-2||e===-1||e===32}const If=Rf(/\p{P}|\p{S}/u),Lf=Rf(/\s/);function Rf(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function zf(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}const Bf=(function(e,t,n,r,i){let a=Vf(t);if(n!=null&&(typeof n!=`number`||n<0||n===1/0))throw Error(`Expected positive finite index`);if(r!=null&&(!Bf(r)||!r.children))throw Error(`Expected parent node`);if(r==null!=(n==null))throw Error(`Expected both parent and index`);return Uf(e)?a.call(i,e,n,r):!1}),Vf=(function(e){if(e==null)return aae;if(typeof e==`function`)return Hf(e);if(typeof e==`object`)return Array.isArray(e)?nae(e):rae(e);if(typeof e==`string`)return iae(e);throw Error(`Expected function, string, or object as test`)});function nae(e){let t=[],n=-1;for(;++n<e.length;)t[n]=Vf(e[n]);return Hf(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function rae(e){let t=e;return Hf(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function iae(e){return Hf(t);function t(t){return t&&t.type===e}}function Hf(e){return t;function t(t,n,r){return!!(Uf(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function aae(){return!0}function Uf(e){return typeof e==`object`&&!!e&&`type`in e}function oae(e){return`\x1B[33m`+e+`\x1B[39m`}const Wf=[],Gf=`skip`;function Kf(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=Vf(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,"name",{value:`node (`+oae(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=Wf,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=sae(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function sae(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?Wf:[e]}function cae(e,t,n){let r=Vf((n||{}).ignore||[]),i=lae(t),a=-1;for(;++a<i.length;)Kf(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function lae(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([uae(e[0]),dae(e[1])])}return t}function uae(e){return typeof e==`string`?new RegExp(zf(e),`g`):e}function dae(e){return typeof e==`function`?e:function(){return e}}const qf=`phrasing`,Jf=[`autolink`,`link`,`image`,`label`];function fae(){return{transforms:[yae],enter:{literalAutolink:mae,literalAutolinkEmail:Yf,literalAutolinkHttp:Yf,literalAutolinkWww:Yf},exit:{literalAutolink:vae,literalAutolinkEmail:_ae,literalAutolinkHttp:hae,literalAutolinkWww:gae}}}function pae(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:qf,notInConstruct:Jf},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:qf,notInConstruct:Jf},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:qf,notInConstruct:Jf}]}}function mae(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function Yf(e){this.config.enter.autolinkProtocol.call(this,e)}function hae(e){this.config.exit.autolinkProtocol.call(this,e)}function gae(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function _ae(e){this.config.exit.autolinkEmail.call(this,e)}function vae(e){this.exit(e)}function yae(e){cae(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bae],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,xae]],{ignore:[`link`,`linkReference`]})}function bae(e,t,n,r,i){let a=``;if(!Xf(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!Sae(n)))return!1;let o=Cae(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function xae(e,t,n,r){return!Xf(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function Sae(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Cae(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=Of(e,`(`),a=Of(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function Xf(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||Lf(n)||If(n))&&(!t||n!==47)}function Zf(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}Qf.peek=Mae;function wae(){this.buffer()}function Tae(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Eae(){this.buffer()}function Dae(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Oae(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Zf(this.sliceSerialize(e)).toLowerCase(),n.label=t}function kae(e){this.exit(e)}function Aae(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Zf(this.sliceSerialize(e)).toLowerCase(),n.label=t}function jae(e){this.exit(e)}function Mae(){return`[`}function Qf(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function Nae(){return{enter:{gfmFootnoteCallString:wae,gfmFootnoteCall:Tae,gfmFootnoteDefinitionLabelString:Eae,gfmFootnoteDefinition:Dae},exit:{gfmFootnoteCallString:Oae,gfmFootnoteCall:kae,gfmFootnoteDefinitionLabelString:Aae,gfmFootnoteDefinition:jae}}}function Pae(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Qf},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
192
+ `)}case`NOT_SYNCED`:return`Settings are still loading. Try again in a moment.`;case`WRITE_ERROR`:return`Failed to write config file: ${e.detail}`;case`OKIGNORE_INVALID`:return e.lineNumber===void 0?`.okignore: ${e.detail}`:`.okignore line ${e.lineNumber}: ${e.detail}`;case`UNKNOWN`:return e.message??`Unknown error.`}}function xie(e,t,n){return $d([e,t,n],[])}function $d(e,t){if(t.length>0){let n=hu(fu,t);if(n?.scope===`user`)return e[0];if(n?.scope===`project`)return e[1]??e[0];if(n?.scope===`project-local`)return e[2]??e[0]}let n=Sie(e);if(n===void 0)return;if(n===null)return null;if(Array.isArray(n)||typeof n!=`object`)return n;let r=e.map(e=>Cie(e)?e:void 0),i=new Set;for(let e of r)if(e!==void 0)for(let t of Object.keys(e))i.add(t);let a={};for(let e of i)a[e]=$d(r.map(t=>t===void 0?void 0:t[e]),[...t,e]);return a}function Sie(e){for(let t=e.length-1;t>=0;t--)if(e[t]!==void 0)return e[t]}function Cie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const wie=Object.freeze([`__config__/project`,`__local__/project`,`__user__/config.yml`,`__config__/okignore`]),ef=[`project`,`global`];function Tie(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)||e.startsWith(`__extskill__/`)}const tf=[`.mdx`,`.md`],nf={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},Eie=rt.stable.mcpServerName,Die=[`exec`,`search`,`history`,`links`,`skills`,`config`,`palette`,`preview_url`,`share_link`,`lint`,`audit`,`write`,`edit`,`delete`,`move`,`install`,`import`,`checkpoint`,`restore_version`];function Oie(e){if(e.length===0)return{ok:!1,reason:`docName must not be empty`};if(e.trim().length===0)return{ok:!1,reason:`docName must not be blank (whitespace only)`};if(e!==e.trim())return{ok:!1,reason:`docName must not have leading or trailing whitespace`};for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return{ok:!1,reason:`docName must not contain control characters`}}if(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\\`))return{ok:!1,reason:`docName must not contain "..", a leading "/", or a backslash`};for(let t of e.split(`/`)){if(t.length===0)return{ok:!1,reason:`docName must not contain empty path segments (no leading, trailing, or doubled "/")`};if(t.startsWith(`.`))return{ok:!1,reason:`docName path segments must not start with "." (hidden files are not addressable)`}}return{ok:!0}}const rf=B(I().min(1)).max(50),kie=U([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),Aie=V({label:I().min(1),webUrl:Ii().nullable(),transport:U([`https`,`http`,`ssh`,`git`]).optional()}).loose(),jie=pa(`checkStatus`,[V({checkStatus:W(`allowed`)}).loose(),V({checkStatus:W(`denied`),deniedReason:U([`no-collaborator`,`private-no-access`,`repo-not-found`,`not-authenticated`]),resolvedLogin:I().optional(),declaredLogin:I().optional(),declaredSource:I().optional()}).loose(),V({checkStatus:W(`unknown`),unknownError:U([`network`,`timeout`,`rate-limit`,`token-invalid`,`malformed-response`,`ssh-unverified`]).optional()}).loose()]),af=U([`auth-403`,`auth-401`,`auth-scope-mismatch`,`auth-no-credential`,`auth-not-found-as-identity`,`semantic-protected-branch`]),Mie=U(vc),Nie=U([`succeeded`,`up-to-date`,`conflict`,`refused`,`error`]);V({state:kie,lastSyncUtc:I().nullable(),lastRunUtc:I().nullable().optional(),lastPullOkUtc:I().nullable().optional(),lastPushOkUtc:I().nullable().optional(),lastFetchUtc:I().nullable(),lastPushedSha:I().nullable(),ahead:L().int().min(0),behind:L().int().min(0),consecutiveFailures:L().int().min(0),consecutivePushFailures:L().int().min(0).optional(),conflictCount:L().int().min(0),hasRemote:R(),syncEnabled:R(),identityUnresolved:R(),remote:Aie.nullable().optional(),pushError:I().optional(),pushErrorCode:af.optional(),pullError:I().optional(),pullErrorCode:af.optional(),pausedReason:I().optional(),blockingPaths:B(I().min(1)).optional(),refusedSymlinkPaths:rf.optional(),pushPermission:jie.optional(),syncMode:Mie.optional(),lastPullUtc:I().nullable().optional(),lastPullOutcome:Nie.nullable().optional()}).loose(),V({action:U([`commit`]),paths:B(I().min(1)),commitSha:I().optional()}).loose(),V({action:U([`commit`])}).loose(),V({op:U([`sync`,`push`,`pull`,`fetch`]).optional()}).loose(),V({op:U([`sync`,`push`,`pull`,`fetch`])}).loose();const of=U([`merge-native`,`working-tree`,`reconcile`]),sf=U([`merged-with-markers`,`refused-conflict-markers`,`refused-no-base`,`refused-too-large`,`disk-markers`,`stale-external-write`]),Pie=U([`mine`,`theirs`,`content`,`delete`]);V({conflicts:B(V({file:I().min(1),detectedAt:I().min(1),conflict:of,reason:sf.optional().catch(void 0),conflictKind:U([`git`,`stale-external-write`]).optional(),docName:I().nullable(),theirsSha:I().optional(),baseSha:I().optional()}).loose())}).loose(),V({file:I().min(1),strategy:U([`mine`,`theirs`,`content`,`delete`]),content:I().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content must be provided when strategy is 'content' (an empty string keeps an empty file)`,path:[`content`]}),V({}).loose(),V({file:I().min(1),base:I(),ours:I(),theirs:I(),kind:U([`both-modified`,`delete-modify`,`modify-delete`]),conflict:of,reason:sf.optional().catch(void 0),conflictKind:U([`git`,`stale-external-write`]).optional(),resolutionOptions:B(Pie)}).loose(),V({plan:Ea(e=>e!==void 0,{message:`plan is required`})}).loose(),V({plan:Ea(e=>e!==void 0,{message:`plan is required`})}).loose(),V({result:Ea(e=>e!==void 0,{message:`result is required`})}).loose(),V({packId:I().min(1)}).strict(),V({installedHosts:B(I()),skills:B(V({name:I().min(1),created:R()}).strict())}).strict();const Fie=V({path:I().min(1),summary:I().min(1)}).loose(),Iie=V({files:L().int().nonnegative(),folders:L().int().nonnegative()}).loose();V({packs:B(V({id:I().min(1),name:I().min(1),description:I().min(1),defaultSubfolder:I().optional(),folders:B(Fie),entryCounts:Iie}).loose())}).loose(),V({noOpen:R().optional(),out:I().min(1).optional()}).loose();const Lie=V({reason:U([`unsupported-platform`,`spawn-error`]),message:I()}).loose();pa(`status`,[V({status:W(`installed`),outputPath:I(),size:L().int().nonnegative(),sha256:I(),skillVersion:I()}).loose(),V({status:W(`built`),outputPath:I(),size:L().int().nonnegative(),sha256:I(),skillVersion:I(),handoffError:Lie.optional()}).loose(),V({status:W(`failed`),buildError:I()}).loose(),V({status:W(`skip-current`),skillVersion:I(),recordedAt:I().optional()}).loose()]),pa(`kind`,[V({kind:W(`doc`),docPath:I().min(1)}).loose(),V({kind:W(`folder`),folderPath:I()}).loose()]);const cf=U([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`unsupported-share-url`]),lf=U([`current`,`stale`,`absent`,`empty`]);pa(`ok`,[V({ok:W(!0),shareUrl:I().min(1),sharedUrl:I().min(1),branch:I().min(1),freshness:lf.optional().catch(void 0)}).loose(),V({ok:W(!1),error:cf,branch:I().min(1).optional()}).loose()]);const Rie=U([`user`,`org`]),zie=V({login:I().min(1),kind:Rie,avatarUrl:I().optional()}).loose(),uf=U([`auth-required`,`network`]);pa(`ok`,[V({ok:W(!0),owners:B(zie)}).loose(),V({ok:W(!1),error:uf}).loose()]),pa(`ok`,[V({ok:W(!0),available:R()}).loose(),V({ok:W(!1),error:uf}).loose()]);const Bie=U([`public`,`private`]);V({owner:I().min(1),name:I().min(1),visibility:Bie,description:I().optional()}).loose();const Vie=U([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);pa(`ok`,[V({ok:W(!0),ownerLogin:I().min(1),repoName:I().min(1),cloneUrl:I().min(1),defaultBranch:I().min(1)}).loose(),V({ok:W(!1),error:Vie}).loose()]);function df(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const ff=e=>e.refine(df,`invalid branch name`),pf={shareTargetExists:R(),dirtyConflicts:V({conflicts:R(),files:B(I().min(1))}).loose(),branchIsLocal:R(),shareTargetOnOriginBranch:R().optional()};pa(`detached`,[V({detached:W(!1),currentBranch:I().min(1).nullable(),currentHeadSha:ra(),...pf}).loose(),V({detached:W(!0),currentBranch:ra(),currentHeadSha:I().min(1),...pf}).loose()]),V({branch:ff(I().min(1)),principalId:I().optional(),fastForward:R().optional()}).loose();const Hie=U([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`,`branch-in-other-worktree`,`ff-diverged`,`unsafe-symlinks`,`symlink-check-failed`]);pa(`ok`,[V({ok:W(!0)}).loose(),V({ok:W(!1),reason:Hie,files:B(I().min(1)).optional(),otherWorktreePath:I().min(1).optional(),refusedSymlinkPaths:rf.optional()}).loose()]),U([`on-origin`,`renamed`,`deleted`,`never-on-branch`,`changed-locally`,`unknown`]),V({branch:ff(I().min(1)),path:I(),kind:U([`doc`,`folder`]),contentRootDepth:L().int().min(1).max(65535).optional()}).loose(),pa(`verdict`,[V({verdict:W(`on-origin`)}).loose(),V({verdict:W(`renamed`),renamedTo:I().min(1)}).loose(),V({verdict:W(`deleted`)}).loose(),V({verdict:W(`never-on-branch`)}).loose(),V({verdict:W(`changed-locally`)}).loose(),V({verdict:W(`unknown`)}).loose()]).catch({verdict:`unknown`});function mf(e,t){let n=Oie(e);n.ok||t.addIssue({code:`custom`,message:n.reason})}const hf=I().superRefine(mf).optional(),Uie=I().superRefine(mf),gf={agentId:I().optional(),agentName:I().optional(),colorSeed:I().optional(),clientName:I().optional(),clientVersion:I().optional(),label:I().optional()},_f=I().optional(),Wie=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Gie=V({startedAt:I().min(1),httpListenMs:L().nonnegative().optional(),seedWalkMs:L().nonnegative().optional(),indexesMs:L().nonnegative().optional(),readyMs:L().nonnegative().optional(),fileCount:L().nonnegative().optional()});V({serverInstanceId:I().min(1),currentBranch:I().min(1).optional(),currentDiskAckSVs:H(I().min(1),I().min(1)).optional(),boot:Gie.optional(),collabClients:L().int().nonnegative().optional(),runtimeVersion:I().min(1).optional(),protocolVersion:L().int().positive().optional()}).loose(),V({id:I().min(1),display_name:I().min(1),display_email:I(),source:U([`git-config`,`synthesized`]),created_at:I().min(1)}).loose(),V({collabUrl:I().nullable(),previewUrl:I().nullable(),port:L(),singleFile:R().default(!1)}).loose();const vf=U(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:symlink-refused.urn:ok:error:links-not-permitted.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:unsupported-media-type.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:derived-index-unavailable.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:frontmatter-malformed.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:disk-divergence.urn:ok:error:stale-external-write.urn:ok:error:store-refused.urn:ok:error:doc-removed.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:non-github-origin.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:concurrent-overwrite-refused.urn:ok:error:unresolved-conflict-markers.urn:ok:error:no-conflict-tracked.urn:ok:error:no-blocking-changes.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:single-file-mode.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed.urn:ok:error:registry-unreachable.urn:ok:error:config-not-writable.urn:ok:error:audit-superseded.urn:ok:error:theme-name-taken.urn:ok:error:theme-name-invalid`.split(`.`)),Kie=V({type:vf,title:I().min(1),status:L().int().min(400).max(599),instance:I().regex(Wie,`instance must be urn:uuid:<uuid>`).optional(),detail:I().optional()}).loose();V({parentDocName:I().min(1),placement:U([`configured-attachments`,`parent-dir`]).default(`configured-attachments`),agentId:I().min(1).optional(),agentName:I().min(1).optional()}).loose(),V({src:I().min(1),path:I().min(1).optional(),deduped:R().optional()}).loose(),V({url:I().min(1),dir:I().min(1),branch:I().min(1).refine(df,`invalid branch name`).optional()}).loose(),V({type:W(`error`),problem:Kie}).loose(),V({docName:hf,summary:_f,content:I().optional(),...gf}).loose(),V({docName:hf,summary:_f,markdown:I(),position:U([`append`,`prepend`,`replace`]).optional(),extension:U(tf).optional(),...gf}).loose(),V({docName:hf,summary:_f,find:I().min(1),replace:I(),offset:L().int().nonnegative().optional(),...gf}).loose(),V({docName:hf,connectionId:I().min(1),scope:U([`last`,`session`,`file`,`count`]).optional(),count:L().int().positive().optional(),...gf}).loose().refine(e=>e.scope!==`count`||e.count!==void 0,{message:`count is required when scope is 'count'`,path:[`count`]});const yf=V({value:I(),truncatedFrom:L().int().nonnegative().optional(),hint:I().optional()}).loose(),qie=pa(`kind`,[V({kind:W(`inline`),content:I()}),V({kind:W(`truncated`),byteLength:L().int().nonnegative(),hint:I()})]),bf=V({kind:W(`content-divergence`),intendedBytes:L().int().nonnegative(),actualBytes:L().int().nonnegative(),byteDelta:L().int(),divergenceType:I().optional(),currentState:qie.optional(),hint:I().optional()}).loose(),Jie=V({type:W(`orphan`),parentCandidates:B(I()),message:I()}).loose(),xf=V({kind:W(`disk-edit-reconciled`),intendedBytes:L().int().nonnegative(),actualBytes:L().int().nonnegative(),byteDelta:L().int(),mergeOutcome:I().optional(),hint:I().optional()}).loose();pa(`kind`,[bf,xf]);const Yie=Object.keys({"content-divergence":!0,"disk-edit-reconciled":!0}),Xie=V({kind:W(`mermaid-parse-error`),fenceIndex:L().int().positive(),fenceFirstLine:I(),message:I(),line:L().int().positive().optional()}).loose(),Sf=V({href:I(),targetKind:I(),role:I(),sourceForm:I(),resolvedTarget:I().nullable(),reason:I(),resolutionMethod:I(),fallbackTarget:I().nullable().optional(),definition:V({line:L().int().nonnegative(),label:I()}).loose().optional()}).loose(),Cf=pa(`kind`,[bf,xf,Xie,V({kind:W(`lint-violation`),source:I(),code:I(),message:I(),severity:U([`error`,`warning`,`info`,`hint`]),line:L().int().positive(),column:L().int().positive(),linkTarget:I().optional(),localTarget:Sf.optional()}).loose(),V({kind:W(`link-check-deferred`),message:I()}).loose()]),wf=B(Cf).min(1),Tf=V({href:I(),resolvedTo:I().nullable(),reason:U([`no-such-doc`,`no-such-file`,`unresolvable`,`excluded`]),localTarget:Sf.optional()}).loose(),Ef=B(Tf),Df=V({reason:I().min(1),count:L().int().positive()}).loose();V({timestamp:I().min(1),summary:yf.optional(),warnings:wf.optional()}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),hints:B(Jie).optional(),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({docName:I().min(1),scope:U([`last`,`session`,`count`]),undone:R()}).loose(),V({docs:B(V({docName:Uie,markdown:I(),position:U([`append`,`prepend`,`replace`]).optional(),extension:U(tf).optional(),summary:_f}).loose()).min(1).max(100),...gf}).loose();const Zie=V({type:vf,title:I(),detail:I().optional()}).loose(),Qie=pa(`status`,[V({status:W(`written`),docName:I().min(1),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose(),V({status:W(`error`),docName:I().min(1),error:Zie}).loose()]);V({timestamp:I().min(1),results:B(Qie),written:L().int().nonnegative(),failed:L().int().nonnegative()}).loose(),V({docName:hf,patch:H(I(),fa([bo,ra()])),types:H(I(),U(vo)).optional(),summary:_f,...gf}).loose(),V({timestamp:I().min(1),subscriberCount:L().int().nonnegative(),systemSubscriberCount:L().int().nonnegative(),appliedKeys:B(I()),summary:yf.optional(),warnings:wf.optional(),brokenLinks:Ef,brokenLinkSuppression:Df.optional()}).loose();function Of(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}const kf=Rf(/[A-Za-z]/),Af=Rf(/[\dA-Za-z]/),$ie=Rf(/[#-'*+\--9=?A-Z^-~]/);function jf(e){return e!==null&&(e<32||e===127)}const Mf=Rf(/\d/),eae=Rf(/[\dA-Fa-f]/),tae=Rf(/[!-/:-@[-`{-~]/);function Nf(e){return e!==null&&e<-2}function Pf(e){return e!==null&&(e<0||e===32)}function Ff(e){return e===-2||e===-1||e===32}const If=Rf(/\p{P}|\p{S}/u),Lf=Rf(/\s/);function Rf(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function zf(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}const Bf=(function(e,t,n,r,i){let a=Vf(t);if(n!=null&&(typeof n!=`number`||n<0||n===1/0))throw Error(`Expected positive finite index`);if(r!=null&&(!Bf(r)||!r.children))throw Error(`Expected parent node`);if(r==null!=(n==null))throw Error(`Expected both parent and index`);return Uf(e)?a.call(i,e,n,r):!1}),Vf=(function(e){if(e==null)return aae;if(typeof e==`function`)return Hf(e);if(typeof e==`object`)return Array.isArray(e)?nae(e):rae(e);if(typeof e==`string`)return iae(e);throw Error(`Expected function, string, or object as test`)});function nae(e){let t=[],n=-1;for(;++n<e.length;)t[n]=Vf(e[n]);return Hf(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function rae(e){let t=e;return Hf(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function iae(e){return Hf(t);function t(t){return t&&t.type===e}}function Hf(e){return t;function t(t,n,r){return!!(Uf(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function aae(){return!0}function Uf(e){return typeof e==`object`&&!!e&&`type`in e}function oae(e){return`\x1B[33m`+e+`\x1B[39m`}const Wf=[],Gf=`skip`;function Kf(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=Vf(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,"name",{value:`node (`+oae(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=Wf,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=sae(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function sae(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?Wf:[e]}function cae(e,t,n){let r=Vf((n||{}).ignore||[]),i=lae(t),a=-1;for(;++a<i.length;)Kf(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function lae(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([uae(e[0]),dae(e[1])])}return t}function uae(e){return typeof e==`string`?new RegExp(zf(e),`g`):e}function dae(e){return typeof e==`function`?e:function(){return e}}const qf=`phrasing`,Jf=[`autolink`,`link`,`image`,`label`];function fae(){return{transforms:[yae],enter:{literalAutolink:mae,literalAutolinkEmail:Yf,literalAutolinkHttp:Yf,literalAutolinkWww:Yf},exit:{literalAutolink:vae,literalAutolinkEmail:_ae,literalAutolinkHttp:hae,literalAutolinkWww:gae}}}function pae(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:qf,notInConstruct:Jf},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:qf,notInConstruct:Jf},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:qf,notInConstruct:Jf}]}}function mae(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function Yf(e){this.config.enter.autolinkProtocol.call(this,e)}function hae(e){this.config.exit.autolinkProtocol.call(this,e)}function gae(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function _ae(e){this.config.exit.autolinkEmail.call(this,e)}function vae(e){this.exit(e)}function yae(e){cae(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bae],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,xae]],{ignore:[`link`,`linkReference`]})}function bae(e,t,n,r,i){let a=``;if(!Xf(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!Sae(n)))return!1;let o=Cae(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function xae(e,t,n,r){return!Xf(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function Sae(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Cae(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=Of(e,`(`),a=Of(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function Xf(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||Lf(n)||If(n))&&(!t||n!==47)}function Zf(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}Qf.peek=Mae;function wae(){this.buffer()}function Tae(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Eae(){this.buffer()}function Dae(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Oae(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Zf(this.sliceSerialize(e)).toLowerCase(),n.label=t}function kae(e){this.exit(e)}function Aae(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Zf(this.sliceSerialize(e)).toLowerCase(),n.label=t}function jae(e){this.exit(e)}function Mae(){return`[`}function Qf(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function Nae(){return{enter:{gfmFootnoteCallString:wae,gfmFootnoteCall:Tae,gfmFootnoteDefinitionLabelString:Eae,gfmFootnoteDefinition:Dae},exit:{gfmFootnoteCallString:Oae,gfmFootnoteCall:kae,gfmFootnoteDefinitionLabelString:Aae,gfmFootnoteDefinition:jae}}}function Pae(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Qf},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
193
193
  `:` `)+r.indentLines(r.containerFlow(e,a.current()),t?$f:Fae))),s(),o}}function Fae(e,t,n){return t===0?e:$f(e,t,n)}function $f(e,t,n){return(n?``:` `)+e}const Iae=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];ep.peek=Vae;function Lae(){return{canContainEols:[`delete`],enter:{strikethrough:zae},exit:{strikethrough:Bae}}}function Rae(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:Iae}],handlers:{delete:ep}}}function zae(e){this.enter({type:`delete`,children:[]},e)}function Bae(e){this.exit(e)}function ep(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function Vae(){return`~`}function Hae(e){return e.length}function Uae(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||Hae,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=Wae(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=tp(r[d]);else{let e=tp(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&(n.alignDelimiters!==!1||i!==``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
194
194
  `)}function Wae(e){return e==null?``:String(e)}function tp(e){let t=typeof e==`string`?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}const np={}.hasOwnProperty;function rp(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&np.call(t,e)){let n=String(t[e]);i=np.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}const Gae={}.hasOwnProperty;function ip(e,t){let n=-1,r;if(t.extensions)for(;++n<t.extensions.length;)ip(e,t.extensions[n]);for(r in t)if(Gae.call(t,r))switch(r){case`extensions`:break;case`unsafe`:ap(e[r],t[r]);break;case`join`:ap(e[r],t[r]);break;case`handlers`:Kae(e[r],t[r]);break;default:e.options[r]=t[r]}return e}function ap(e,t){t&&e.push(...t)}function Kae(e,t){t&&Object.assign(e,t)}function qae(e,t,n,r){let i=n.enter(`blockquote`),a=n.createTracker(r);a.move(`> `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),Jae);return i(),o}function Jae(e,t,n){return`>`+(n?``:` `)+e}function op(e,t){return sp(e,t.inConstruct,!0)&&!sp(e,t.notInConstruct,!1)}function sp(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function cp(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
195
195
  `&&op(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?``:` `;return`\\
@@ -1542,6 +1542,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
1542
1542
  `);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
1543
1543
  `)?`
1544
1544
  `:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const kNe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function ANe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const jNe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function MNe(e){let t={contentDirSpellings:O9(e.contentDir)};for(let n of jNe)for(let r of P9(j(e.stagingDir,n)))ANe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(j(e.stagingDir,`state`))){let e=ae(n);n.endsWith(`.jsonl`)?j9(n,t):kNe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function NNe(e){return j(e,...I9,z9)}function PNe(e){return j(e,...I9,B9)}function FNe(e){return j(e,...L9,V9)}function INe(e){return j(e,...L9,H9)}function LNe(e){return j(e,...R9,U9)}function RNe(e){return j(e,...R9,W9)}const G9=1e3;async function zNe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function BNe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function VNe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function HNe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1545
- `)}\n`:null}catch{return null}}function UNe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],g8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function WNe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],g8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function GNe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function KNe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,Ms.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function qNe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return qNe(e.maxBytes)}function JNe(e){let t=J9(rY(`project`,e)),n=J9(rY(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function YNe(e){return Me(`sha256`).update(e).digest(`hex`)}function XNe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const ZNe=[`"doc.name"`,`"docName"`];function QNe(e){let t=S(e,`utf-8`),n=0;for(let e of ZNe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,a7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const $Ne=new Set([`.jsonl`]);function ePe(e){let t=e.lastIndexOf(`.`);return t!==-1&&$Ne.has(e.slice(t))}const tPe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function nPe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&tPe.has(e.slice(t))}function rPe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!nPe(r))continue;let{redacted:i,patterns:a,lineCount:o}=DP(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function iPe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??zNe,a=r.fetchAgentEffects??BNe,o=r.fetchWatcherRecent??VNe,s=r.readShadowHead??UNe,c=r.readCheckpointRefs??WNe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.85.0-beta.4`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??GNe,h=r.isOtlpPushEnabled??KNe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(NNe(n),j(_,`telemetry`,z9)),Z9(PNe(n),j(_,`telemetry`,B9)),Z9(FNe(n),j(_,`logs`,V9)),Z9(INe(n),j(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,LJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=HNe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(LNe(n),j(_,`state`,U9)),Z9(RNe(n),j(_,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,Pd),j(_,`state`,Pd)),Z9(j(b,Fd),j(_,`state`,Fd)),Z9(j(b,Nd),j(_,`state`,Nd));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
1545
+ `)}\n`:null}catch{return null}}function UNe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],g8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function WNe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],g8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function GNe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function KNe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,Ms.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function qNe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return qNe(e.maxBytes)}function JNe(e){let t=J9(rY(`project`,e)),n=J9(rY(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function YNe(e){return Me(`sha256`).update(e).digest(`hex`)}function XNe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const ZNe=[`"doc.name"`,`"docName"`];function QNe(e){let t=S(e,`utf-8`),n=0;for(let e of ZNe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,a7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const $Ne=new Set([`.jsonl`]);function ePe(e){let t=e.lastIndexOf(`.`);return t!==-1&&$Ne.has(e.slice(t))}const tPe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function nPe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&tPe.has(e.slice(t))}function rPe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!nPe(r))continue;let{redacted:i,patterns:a,lineCount:o}=DP(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function iPe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??zNe,a=r.fetchAgentEffects??BNe,o=r.fetchWatcherRecent??VNe,s=r.readShadowHead??UNe,c=r.readCheckpointRefs??WNe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.85.0-beta.5`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??GNe,h=r.isOtlpPushEnabled??KNe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(NNe(n),j(_,`telemetry`,z9)),Z9(PNe(n),j(_,`telemetry`,B9)),Z9(FNe(n),j(_,`logs`,V9)),Z9(INe(n),j(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,LJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=HNe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(LNe(n),j(_,`state`,U9)),Z9(RNe(n),j(_,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,Pd),j(_,`state`,Pd)),Z9(j(b,Fd),j(_,`state`,Fd)),Z9(j(b,Nd),j(_,`state`,Nd));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
1546
1546
  `:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:i7(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,c7),S7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&MNe({stagingDir:_,contentDir:t}),e.note&&re(j(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=rPe(_));for(let t of e.extraFiles??[]){let e=t.zipName??ae(t.sourcePath);if(!Z9(t.sourcePath,j(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=w7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=JNe(n),N=Q9(_),le=[],ue=0,de=0;for(let e of N){let t=$9(_,e),n=te(e).size,r=ePe(t)?XNe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=QNe(e))}let fe={applied:se};ce!==null&&(fe.secretScrub=ce);let P={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:YNe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:le};re(j(_,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=O9(t),me=N.some(e=>{try{let t=S(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:_,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function aPe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new FEe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function oPe(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,Ms.parse)(S(n,`utf-8`)),r=CY(t)?t.content:void 0,i=CY(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return N(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return N(e)}async function sPe(e,t,n,r,i,a){let o=T7(t,e.logger),s=await iPe({contentDir:oPe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...gMe(o,e.userLogsDir??j(XJ(),`logs`)),...D7(e.cachesDir??j(_e(),`Library`,`Caches`))],userStateFiles:O7(e.bugReportsDir??C7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(k(e.outputPath),{recursive:!0}),await aPe({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function cPe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??D9,i=()=>qje(e.diagnosticReportsDir??j(_e(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return sPe(e,t,n,r,i(),await x7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await xMe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:D7(e.cachesDir??j(_e(),`Library`,`Caches`)),bugReportLedgerFiles:O7(e.bugReportsDir??C7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await x7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{AY as ALL_EDITOR_IDS,jY as EDITOR_LABELS,sX as EDITOR_TARGETS,Hye as HOSTS_WITH_USER_SKILL_DIR,Fje as LAUNCH_CONFIG_NAME,dNe as PATH_SHIM_BEGIN,pNe as PATH_SHIM_BLOCK_RE,fNe as PATH_SHIM_END,v5 as ProjectPathSafetyError,pje as addOkPathsToGitExclude,y5 as assertProjectPathSafe,UY as buildManagedServerEntry,eNe as buildMcpConfigDeclineEvent,tNe as buildMcpConfigMigrateEvent,t7 as classifyExistingMcpEntry,cPe as collectReportBundle,vNe as createCliProbeResolver,lY as createTokenStore,pMe as defaultBugReportZipPath,Ke as detectGh,Ye as detectGhAccounts,zje as detectInstalledEditors,QY as droppedManagedKeys,lbe as editorConfigPathDisplay,cbe as editorEntryLocator,UMe as ensurePiBridge,N5 as formatTrackedRemediation,gje as getExcludedOkPaths,j5 as getInstalledSkillProjectionPaths,Vye as getNativeTomlMcpEditor,A5 as getOkArtifactPaths,VY as isEntryUpToDate,WY as isOwnManagedEntry,cNe as loadConfig,pye as makeLazyProbeTokenStore,C7 as okBugReportsDir,y9 as parseGitHubBlobUrl,lNe as parseGitHubShareUrl,b9 as parseGitHubTreeUrl,v9 as parseGitUrl,mNe as pathInstallMarkerPath,QAe as previewContent,Bje as probeOwnManagedEditorMcpEntry,VMe as probePiBridgeState,M5 as probeTrackedOkPaths,$5 as readExistingMcpEntry,hje as readSharingMode,DP as redactContent,mje as removeOkPathsFromGitExclude,XMe as removeOwnMcpEntry,lje as removeProjectSkill,bNe as removeUserGlobalSkillBundle,ENe as removeUserSkill,rje as resolveProjectRoot,aNe as runStop,m9 as truncatePriorEntry,T9 as userGlobalSkillBundleTargets,TNe as userSkillPresentAnywhere,uNe as validateLocalFolderForShare,Q5 as writeEditorMcpConfig,CNe as writeProjectAiIntegrations,T5 as writeProjectSkill,Rje as writeUserMcpConfigs,wNe as writeUserSkill};
1547
1547
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ import"./dist-Bkpf6l5f.mjs";import{_ as e}from"./init-Dq3WfDbj.mjs";export{e as runInit};