@inkeep/open-knowledge 0.86.15 → 0.86.16

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 (103) hide show
  1. package/dist/assets/skills/project/references/media-and-assets.md +1 -1
  2. package/dist/cli.mjs +6 -6
  3. package/dist/config-schema.json +1 -1
  4. package/dist/config.project.schema.json +1 -1
  5. package/dist/constants-CqNABsZB.mjs +1 -0
  6. package/dist/{dist-fzYMjYEW.mjs → dist-BNPpubXf.mjs} +1 -1
  7. package/dist/{dist-CerHybyM.mjs → dist-CvZCvtXe.mjs} +4 -4
  8. package/dist/index.mjs +2 -2
  9. package/dist/init-C99xOULP.mjs +1 -0
  10. package/dist/{init-D_Mnfn9S.mjs → init-RmBoT2PK.mjs} +2 -2
  11. package/dist/{launch-json-removal-DF78Zb2V.mjs → launch-json-removal-CctovJFV.mjs} +1 -1
  12. package/dist/loader-BVSrV694.mjs +1 -0
  13. package/dist/{loader-EPi5ZErh.mjs → loader-CPblhk01.mjs} +1 -1
  14. package/dist/{md-manager-BGnqyqi1-B6Vk34FK.mjs → md-manager-BGnqyqi1-DRBNLmLZ.mjs} +1 -1
  15. package/dist/{open-browser-BL65djdM.mjs → open-browser-DU_gU7KC.mjs} +1 -1
  16. package/dist/parse-worker.mjs +1 -1
  17. package/dist/preview-DkSS1KD_.mjs +1 -0
  18. package/dist/{preview-D9iu9mhV.mjs → preview-rK0HPHCM.mjs} +1 -1
  19. package/dist/public/assets/{AccountSection-BG0_TO2e.js → AccountSection-CQ3MoAiu.js} +1 -1
  20. package/dist/public/assets/{ActivityModeContent-DX7qnelJ.js → ActivityModeContent-7yA_LDxD.js} +1 -1
  21. package/dist/public/assets/{AddPropertiesButton-ISpK9Zho.js → AddPropertiesButton-bukgzoDX.js} +1 -1
  22. package/dist/public/assets/{AgentDiffPane-BUMpUwLF.js → AgentDiffPane-stzSbdBy.js} +1 -1
  23. package/dist/public/assets/{AttachmentsSection-CN5du-Ku.js → AttachmentsSection-8I8Nxe0M.js} +1 -1
  24. package/dist/public/assets/{CodeMirrorPropInput-Bbv8fSFU.js → CodeMirrorPropInput-CezfVY4H.js} +1 -1
  25. package/dist/public/assets/{ContentRulesSection-C9IeMwCS.js → ContentRulesSection-Ci2czTjF.js} +1 -1
  26. package/dist/public/assets/{DocumentContext-Di4xaMwl.js → DocumentContext-BB0nKfep.js} +1 -1
  27. package/dist/public/assets/{EditorModeToggle-AVuI8ebZ.js → EditorModeToggle-DYuuX6dO.js} +1 -1
  28. package/dist/public/assets/{ExcalidrawDocEditor-Ce86s-v8.js → ExcalidrawDocEditor-4yYSBe14.js} +1 -1
  29. package/dist/public/assets/FeedbackForm-Cfrx5H9R.js +1 -0
  30. package/dist/public/assets/{ImportSkillDialog-YCivM6Y8.js → ImportSkillDialog-CbVOxKm9.js} +1 -1
  31. package/dist/public/assets/{LinkPreviewsSection-DgK68AAA.js → LinkPreviewsSection-eJeiL-G6.js} +1 -1
  32. package/dist/public/assets/{LintConfigEditor-CEnWskLc.js → LintConfigEditor-B08bIlPA.js} +1 -1
  33. package/dist/public/assets/{LintingSection-DfdRWFJl.js → LintingSection-CgdZ2qC8.js} +1 -1
  34. package/dist/public/assets/{ManagedArtifactProperties-GW5LIoca.js → ManagedArtifactProperties-CHNAj6L4.js} +1 -1
  35. package/dist/public/assets/ManagedArtifactProperties-sRiQX_v3.js +1 -0
  36. package/dist/public/assets/{MermaidDocEditor-pBnfScXw.js → MermaidDocEditor-BfwKbHcc.js} +1 -1
  37. package/dist/public/assets/{NetworkAccessSection-COAzJ4e0.js → NetworkAccessSection-B_pi2Qal.js} +1 -1
  38. package/dist/public/assets/{PropertyDisplayRow-DoYx80d4.js → PropertyDisplayRow-Ch2yOLBv.js} +1 -1
  39. package/dist/public/assets/{PublishToGitHubDialog-J-VGefwl.js → PublishToGitHubDialog-Buo-KPJx.js} +1 -1
  40. package/dist/public/assets/{SchemaConfigEditor-BXEY5Lpc.js → SchemaConfigEditor-iDGqAzG4.js} +1 -1
  41. package/dist/public/assets/{SearchSection-DfIFmawW.js → SearchSection-C1RHTjy5.js} +1 -1
  42. package/dist/public/assets/{SessionsHost-DaPpTHog.js → SessionsHost-BQ-iaohc.js} +2 -2
  43. package/dist/public/assets/{SettingsDialogBody-CYvW19u7.js → SettingsDialogBody-DoYZUwsg.js} +2 -2
  44. package/dist/public/assets/{ShareReceiveMissDialog-Cw9ITE2h.js → ShareReceiveMissDialog-DzZbDaXI.js} +1 -1
  45. package/dist/public/assets/{SkillToolbarControls-CuTnMhoM.js → SkillToolbarControls-ChlOZJXQ.js} +1 -1
  46. package/dist/public/assets/{SourceEditor-DzijW0O3.js → SourceEditor-CofwPhEl.js} +1 -1
  47. package/dist/public/assets/{SpellingSettings-DH0T6Q-0.js → SpellingSettings-D6u6jJWL.js} +1 -1
  48. package/dist/public/assets/{SyncSection-D-yuvsEP.js → SyncSection-DLhKIpvC.js} +1 -1
  49. package/dist/public/assets/{SyncStatusBadge-DDXV7fc_.js → SyncStatusBadge-wVSPKrjz.js} +1 -1
  50. package/dist/public/assets/{TerminalSection-B35_ovK-.js → TerminalSection-xlIDaFSJ.js} +1 -1
  51. package/dist/public/assets/{TerminalWindowApp-DVlYGRoh.js → TerminalWindowApp-CHxli66i.js} +1 -1
  52. package/dist/public/assets/{TextDocEditor-D9oE75zl.js → TextDocEditor-DBbmicjx.js} +1 -1
  53. package/dist/public/assets/{ThemePluginSection-1CRBX5E8.js → ThemePluginSection-08z6uhJY.js} +1 -1
  54. package/dist/public/assets/{ThreadView-BQnQfd0I.js → ThreadView-DdYuP5Fq.js} +1 -1
  55. package/dist/public/assets/{TimelineDiffPane-Dri7SUVQ.js → TimelineDiffPane-BIGIL6Fc.js} +1 -1
  56. package/dist/public/assets/{client-version-BYVa8AIr.js → client-version-nR7-m4d2.js} +1 -1
  57. package/dist/public/assets/{comment-chips-EHSRiXz3.js → comment-chips-CwpaKWgF.js} +1 -1
  58. package/dist/public/assets/{config-provider-kLYQhPYp.js → config-provider-maC-s8nJ.js} +1 -1
  59. package/dist/public/assets/config-schema-BranunPO.js +1 -0
  60. package/dist/public/assets/{doc-undo-manager-HTjJCKce.js → doc-undo-manager-CMNnHa17.js} +1 -1
  61. package/dist/public/assets/{field-controls-e2mA3LBp.js → field-controls-7M8rxNa1.js} +1 -1
  62. package/dist/public/assets/field-controls-B4v3SIzn.js +1 -0
  63. package/dist/public/assets/{index-9UmK6oDx.js → index-1J1mB1rq.js} +8 -8
  64. package/dist/public/assets/{lint-config-client-Wa2rYzej.js → lint-config-client-BXxJgiMj.js} +1 -1
  65. package/dist/public/assets/{lint-plugins-B9OFl9DC.js → lint-plugins-IzY40E-g.js} +1 -1
  66. package/dist/public/assets/{markdown-lint-BgDulTY0.js → markdown-lint-CnxqlpxD.js} +1 -1
  67. package/dist/public/assets/{markdownlint-rule-browser-a9COyrB0.js → markdownlint-rule-browser-Ca0LiFxs.js} +1 -1
  68. package/dist/public/assets/{pending-receive-nav-store-DRuzqurs.js → pending-receive-nav-store-CtyTO1zl.js} +1 -1
  69. package/dist/public/assets/{preferred-session-events-Cwvz3DYB.js → preferred-session-events-BEFdeskN.js} +1 -1
  70. package/dist/public/assets/{progress-DJDyKmOT.js → progress-CjLBpKVA.js} +1 -1
  71. package/dist/public/assets/saved-themes-client-L2ZZOn0Z.js +1 -0
  72. package/dist/public/assets/{schema-section-D0TwA1wk.js → schema-section-BCQI08Fz.js} +1 -1
  73. package/dist/public/assets/{selection-context-BiltXMSS.js → selection-context-QohlVBby.js} +1 -1
  74. package/dist/public/assets/{src-CpVL1MXA.js → src-eD2YcFLO.js} +1 -1
  75. package/dist/public/assets/{telemetry-impl-tfAX1CTp.js → telemetry-impl-DbEbLICB.js} +1 -1
  76. package/dist/public/assets/{telemetry-startup-Kz3A4OMo.js → telemetry-startup-Bklp1VJg.js} +1 -1
  77. package/dist/public/assets/{typing-burst-detector-DCLWi61a.js → typing-burst-detector-l0s7Bvng.js} +1 -1
  78. package/dist/public/assets/{use-activity-panel-Betx0VB5.js → use-activity-panel-MWNz0jP2.js} +1 -1
  79. package/dist/public/assets/{use-open-skill-Qib9eMlk.js → use-open-skill-w9Yc1dgu.js} +1 -1
  80. package/dist/public/assets/{use-terminal-enabled-CVVMal6F.js → use-terminal-enabled-D4Z_JsJ9.js} +1 -1
  81. package/dist/public/assets/{use-timeline-entry-diff-C2kQsAEV.js → use-timeline-entry-diff-CgmegStH.js} +1 -1
  82. package/dist/public/index.html +21 -21
  83. package/dist/{registry-probes-xhAfEfyJ.mjs → registry-probes-CQJWD_N1.mjs} +1 -1
  84. package/dist/{removal-file-path-Cck6aRSq.mjs → removal-file-path-FZgRZJMq.mjs} +1 -1
  85. package/dist/{repair-launch-json-CwNpvI1_.mjs → repair-launch-json-YXWJ7404.mjs} +1 -1
  86. package/dist/{repair-mcp-configs-BJuIMxPX.mjs → repair-mcp-configs-qFDKov51.mjs} +1 -1
  87. package/dist/schemas/v0/config.project.schema.json +1 -1
  88. package/dist/{src-P3X9-4mK.mjs → src-B4Ppfouc.mjs} +1 -1
  89. package/dist/src-BgQTBEn_.mjs +1 -0
  90. package/dist/start-BBEHhUC8.mjs +1 -0
  91. package/dist/{start-W6HfLGEn.mjs → start-BOXkkd5Z.mjs} +3 -3
  92. package/package.json +4 -4
  93. package/dist/constants-Big4uVC4.mjs +0 -1
  94. package/dist/init-DpWQMxOd.mjs +0 -1
  95. package/dist/loader-D5rR-ONY.mjs +0 -1
  96. package/dist/preview-ClW6A8dv.mjs +0 -1
  97. package/dist/public/assets/FeedbackForm-BZSwiBHE.js +0 -1
  98. package/dist/public/assets/ManagedArtifactProperties-CPP8NsrT.js +0 -1
  99. package/dist/public/assets/config-schema-B4_7xb9l.js +0 -1
  100. package/dist/public/assets/field-controls-B1UqOPPr.js +0 -1
  101. package/dist/public/assets/saved-themes-client-CdTWCmn6.js +0 -1
  102. package/dist/src-DkA3OkNb.mjs +0 -1
  103. package/dist/start-Bqg3TrSD.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,$i as u,$l as d,$n as f,$o as p,$r as m,$s as h,$t as g,$u as _,A as v,Aa as y,Ac as b,Ad as x,Ai as S,Al as C,An as w,Ao as T,Ar as E,As as D,At as O,Au as ee,B as k,Ba as A,Bc as te,Bd as j,Bi as M,Bl as ne,Bn as re,Bo as ie,Br as ae,Bs as N,Bt as oe,Bu as se,Ca as ce,Cc as le,Cd as ue,Cf as de,Ci as fe,Cl as pe,Cn as me,Co as he,Cr as ge,Cs as _e,Ct as ve,Cu as ye,D as be,Da as xe,Dc as Se,Dd as Ce,Di as we,Dl as Te,Dn as Ee,Do as De,Dr as Oe,Ds as ke,Dt as Ae,Du as je,E as Me,Ea as Ne,Ec as Pe,Ed as P,Ei as Fe,El as Ie,En as Le,Eo as Re,Er as ze,Es as Be,Et as Ve,Eu as He,Fa as Ue,Fc as We,Fd as F,Fi as Ge,Fn as Ke,Fo as qe,Fr as Je,Fs as Ye,Ft as Xe,Fu as Ze,Ga as Qe,Gc as $e,Gd as et,Gi as tt,Gl as nt,Gn as rt,Go as it,Gr as at,Gs as ot,Gt as st,Gu as ct,H as lt,Ha as ut,Hc as dt,Hi as ft,Hl as pt,Hn as mt,Ho as ht,Hr as gt,Hs as _t,Ht as vt,Hu as yt,Ia as bt,Ic as xt,Id as I,Ii as St,In as Ct,Io as wt,Ir as Tt,Is as Et,It as Dt,Iu as Ot,J as kt,Ja as At,Jc as jt,Jd as Mt,Ji as Nt,Jn as Pt,Jo as Ft,Jr as It,Js as Lt,Jt as Rt,Ju as zt,K as Bt,Ka as Vt,Kc as Ht,Kd as Ut,Ki as Wt,Kl as Gt,Kn as Kt,Ko as qt,Kr as Jt,Ks as Yt,Kt as Xt,Ku as Zt,L as Qt,La as $t,Lc as en,Ld as tn,Li as nn,Ll as rn,Ln as an,Lo as on,Lr as sn,Ls as cn,Lt as ln,Lu as un,M as dn,Ma as fn,Mc as pn,Md as L,Mi as mn,Ml as hn,Mn as gn,Mo as _n,Mr as vn,Ms as yn,Mt as bn,Mu as xn,Na as Sn,Nc as Cn,Nd as R,Ni as wn,Nl as Tn,Nn as En,No as Dn,Nr as On,Ns as kn,Nt as An,Nu as jn,O as Mn,Oa as Nn,Oc as Pn,Od as Fn,Of as In,Oi as Ln,Ol as Rn,On as zn,Oo as Bn,Or as Vn,Os as Hn,Ot as Un,Ou as Wn,P as Gn,Pa as Kn,Pc as qn,Pd as Jn,Pi as Yn,Pn as Xn,Po as Zn,Pr as Qn,Ps as $n,Pt as er,Pu as tr,Q as nr,Qa as rr,Qc as ir,Qd as ar,Qi as or,Qn as sr,Qo as eee,Qr as cr,Qs as lr,Qt as ur,Qu as dr,R as fr,Ra as pr,Rd as mr,Ri as tee,Rn as hr,Ro as gr,Rr as _r,Rs as vr,Rt as yr,Ru as br,Sa as xr,Sc as Sr,Sd as Cr,Si as wr,Sl as Tr,Sn as Er,So as Dr,Sr as Or,Ss as kr,St as Ar,Su as jr,T as Mr,Ta as Nr,Tc as Pr,Td as Fr,Ti as Ir,Tl as Lr,Tn as nee,To as Rr,Tr as ree,Ts as zr,Tt as Br,Tu as Vr,Ua as Hr,Uc as Ur,Ud as Wr,Ui as Gr,Ul as Kr,Un as qr,Uo as Jr,Ur as Yr,Us as Xr,Ut as Zr,Uu as Qr,V as $r,Va as ei,Vc as ti,Vd as ni,Vi as ri,Vl as ii,Vn as ai,Vo as oi,Vr as si,Vs as iee,Vt as aee,Vu as ci,Wa as li,Wc as oee,Wd as see,Wi as cee,Wl as ui,Wn as lee,Wo as uee,Wr as dee,Ws as fee,Wt as pee,Wu as mee,Xa as hee,Xd as gee,Xi as _ee,Xl as vee,Xn as yee,Xo as bee,Xr as xee,Xt as di,Xu as fi,Y as See,Ya as pi,Yd as Cee,Yi as wee,Yl as Tee,Yn as Eee,Yo as Dee,Yr as Oee,Ys as kee,Yt as mi,Yu as hi,Za as Aee,Zc as jee,Zd as Mee,Zi as gi,Zn as Nee,Zo as Pee,Zr as Fee,Zs as _i,Zt as vi,Zu as yi,_ as Iee,_a as bi,_c as xi,_d as Si,_i as Ci,_l as Lee,_n as Ree,_o as zee,_r as wi,_s as Bee,_t as Ti,_u as Ei,a as Vee,aa as Di,ac as Hee,ad as Uee,ai as Wee,al as Gee,an as Kee,ao as qee,ar as Jee,as as Oi,at as Yee,au as ki,b as Ai,bc as ji,bd as z,bf as Mi,bi as Xee,bl as Zee,bn as Qee,bo as $ee,br as Ni,bs as ete,bt as tte,bu as nte,c as rte,ca as ite,cd as ate,ci as ote,cl as ste,cn as Pi,co as Fi,cr as cte,cs as lte,ct as Ii,cu as ute,d as Li,da as dte,dc as Ri,di as fte,dl as pte,dn as mte,do as hte,dr as gte,ds as _te,dt as zi,du as Bi,ea as vte,ec as yte,ed as Vi,ef as Hi,ei as Ui,el as Wi,en as bte,eo as xte,er as Gi,es as Ki,et as Ste,eu as qi,fa as Cte,fc as Ji,fd as wte,fi as Tte,fl as Ete,fn as Dte,fo as Ote,fr as kte,fs as Ate,ft as Yi,fu as Xi,g as jte,ga as Mte,gd as Nte,gf as Pte,gi as Fte,gl as Zi,gn as Ite,go as Qi,gr as Lte,gs as Rte,gt as $i,gu as zte,h as Bte,ha as ea,hc as ta,hf as Vte,hi as Hte,hn as Ute,ho as na,hr as Wte,hs as Gte,ht as Kte,hu as ra,ia as qte,ic as Jte,id as Yte,if as ia,ii as Xte,il as Zte,in as Qte,io as $te,ir as ene,is as tne,it as aa,iu as nne,j as oa,ja as sa,jc as rne,jd as ine,ji as ane,jl as one,jn as sne,jo as ca,jr as cne,js as la,jt as lne,ju as ua,kd as B,ki as da,kl as fa,kn as une,ko as dne,kr as fne,ks as pne,kt as mne,ku as hne,la as pa,lc as ma,ld as gne,lf as _ne,li as vne,ll as ha,ln as yne,lo as bne,lr as xne,ls as Sne,lt as ga,lu as Cne,m as _a,ma as wne,mc as va,mf as Tne,mi as Ene,mn as Dne,mo as One,mr as kne,ms as Ane,mt as jne,mu as ya,n as ba,na as Mne,nc as Nne,nd as Pne,nf as Fne,ni as Ine,nl as Lne,nn as Rne,no as xa,nr as zne,ns as Bne,nt as Vne,nu as Hne,o as Une,oa as Wne,od as Gne,of as Sa,oi as Kne,ol as Ca,on as qne,oo as Jne,or as Yne,os as Xne,ot as wa,ou as Zne,pa as Qne,pc as $ne,pd as ere,pi as tre,pn as nre,po as rre,pr as Ta,ps as ire,pt as Ea,pu as are,qa as ore,qd as sre,qi as cre,ql as lre,qn as ure,qo as dre,qr as fre,qs as pre,qt as mre,qu as hre,ra as gre,rc as _re,rd as vre,ri as yre,rl as bre,rn as xre,ro as Sre,rr as Cre,rs as wre,rt as Tre,ru as Ere,s as Da,sa as Oa,sc as ka,sd as Dre,sf as Aa,si as ja,sl as Ma,sn as Ore,so as kre,sr as Are,ss as jre,st as Na,su as Pa,t as Fa,tc as Ia,td as Mre,tf as Nre,ti as La,tn as Pre,to as Fre,tr as Ire,ts as Ra,tu as Lre,ua as Rre,uc as za,ud as zre,uf as Ba,ui as Bre,ul as Va,un as Vre,uo as Hre,ur as Ure,us as Wre,ut as Ha,uu as Ua,v as Gre,va as Kre,vc as Wa,vd as Ga,vf as qre,vi as Jre,vn as Ka,vo as qa,vr as Ja,vs as Yre,vt as Ya,vu as Xre,w as Zre,wa as Xa,wc as Za,wd as Qa,wf as $a,wi as eo,wl as Qre,wn as $re,wo as to,wr as eie,ws as tie,wt as no,wu as nie,x as rie,xa as ro,xc as io,xd as ao,xf as iie,xi as aie,xl as oie,xn as sie,xo as cie,xr as lie,xs as uie,xt as oo,xu as so,y as die,yc as fie,yf as co,yi as lo,yl as pie,yn as uo,yo as mie,yr as hie,ys as gie,yt as fo,yu as _ie,za as po,zc as vie,zd as yie,zi as bie,zl as xie,zn as Sie,zo as mo,zr as Cie,zs as wie,zt as ho,zu as Tie}from"./md-manager-BGnqyqi1-B6Vk34FK.mjs";import{c as go,d as _o,h as Eie,i as vo,l as yo,n as bo,o as xo,p as So,t as Co}from"./esm-B3YyV3nD.mjs";import{t as Die}from"./libesm-DRoEqbAC.mjs";import{t as Oie}from"./yazl-BBz29IQN.mjs";import{t as wo}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as To,c as Eo,d as kie,f as Do,h as Aie,i as Oo,l as ko,m as Ao,n as jo,o as Mo,p as No,r as Po,s as Fo,t as Io,u as Lo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as Ro,B as zo,C as Bo,D as Vo,E as jie,F as Mie,H as Nie,I as Pie,L as Ho,M as Uo,N as Wo,O as Go,P as Ko,S as Fie,T as Iie,V as Lie,_ as Rie,a as qo,b as Jo,c as Yo,d as Xo,f as Zo,g as zie,h as Bie,i as Qo,j as $o,k as es,l as ts,m as Vie,n as Hie,o as ns,p as rs,r as is,s as as,t as Uie,u as os,v as ss,w as cs,x as ls,y as us,z as ds}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as fs,r as ps,t as ms}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as hs}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as gs}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as _s,t as vs}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as Wie,t as Gie}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as ys,r as bs,t as xs}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as Kie,t as Ss}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as Cs}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as ws}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as qie}from"./wrapper-BF8oRx3G.mjs";import{createRequire as Ts}from"node:module";import{execFile as Es,execFileSync as Ds,spawn as Os,spawnSync as ks}from"node:child_process";import*as As from"node:path";import{basename as js,delimiter as Ms,dirname as V,extname as Ns,isAbsolute as Ps,join as H,normalize as Fs,parse as Is,posix as Ls,relative as U,resolve as W,sep as Rs,win32 as zs}from"node:path";import{URLSearchParams as Jie,fileURLToPath as Bs,pathToFileURL as Vs}from"node:url";import*as Hs from"node:fs";import{accessSync as Yie,appendFileSync as Us,chmodSync as Ws,closeSync as Gs,constants as Ks,cpSync as Xie,createReadStream as qs,createWriteStream as Js,existsSync as G,fchmodSync as Zie,fstatSync as Qie,linkSync as $ie,lstatSync as Ys,mkdirSync as Xs,mkdtempSync as Zs,openSync as Qs,opendirSync as $s,readFile as eae,readFileSync as K,readSync as ec,readdirSync as tc,readlinkSync as tae,realpathSync as nc,renameSync as rc,rmSync as ic,rmdirSync as ac,statSync as oc,symlinkSync as nae,unlinkSync as sc,watch as rae,writeFileSync as cc,writeSync as lc}from"node:fs";import{arch as uc,availableParallelism as iae,homedir as dc,hostname as fc,platform as pc,tmpdir as mc,userInfo as aae}from"node:os";import{access as hc,appendFile as oae,chmod as sae,constants as cae,glob as lae,lstat as gc,mkdir as _c,readFile as vc,readdir as yc,readlink as uae,realpath as bc,rename as xc,rm as dae,stat as Sc,unlink as fae,writeFile as Cc}from"node:fs/promises";import{Readable as wc,Transform as pae,Writable as mae}from"node:stream";import hae from"crypto";import gae,{createHash as Tc,randomUUID as Ec,webcrypto as Dc}from"node:crypto";import{EventEmitter as _ae}from"node:events";import{Worker as vae}from"node:worker_threads";import*as yae from"zlib";import{Readable as Oc}from"stream";import{readdirSync as bae,statSync as xae}from"fs";import{spawn as Sae}from"child_process";import{promisify as kc,stripVTControlCharacters as Cae}from"node:util";import{DatabaseSync as Ac}from"node:sqlite";import{monitorEventLoopDelay as wae,performance as Tae}from"node:perf_hooks";import{createInterface as Eae}from"node:readline";import{setImmediate as Dae,setTimeout as Oae}from"node:timers/promises";import{AsyncLocalStorage as kae}from"node:async_hooks";import{pipeline as jc}from"node:stream/promises";import{request as Aae}from"node:http";import{Http2ServerRequest as Mc,constants as jae}from"node:http2";import{lookup as Mae}from"node:dns/promises";import{request as Nae}from"node:https";import{createBrotliDecompress as Pae,createGunzip as Fae,createInflate as Iae}from"node:zlib";import{join as Nc,resolve as Lae}from"path";import*as Rae from"node:querystring";import{Http2ServerRequest as Pc,constants as zae}from"http2";import{lookup as Bae}from"node:dns";import Vae from"node:tls";const Hae=2,Fc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},Uae={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},Wae={mcp:!0,"desktop-main":!0,cli:!0};function Gae(e){return Object.hasOwn(Uae,e)}function Kae(e){if(!(e===void 0||e.length===0||Object.hasOwn(Wae,e)))return Gae(e)?e:`unknown`}function qae({kind:e,runtimeVersion:t}){return{[Fc.protocol]:`2`,[Fc.runtime]:t,[Fc.kind]:e}}const Jae=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),Yae=/^={2,}/,Xae=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function Zae(e,t){return Xae.test(e.slice(t,t+512))}function Qae(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:Xae.exec(e.slice(n,t+1))?.[0].length===t+1-n}const $ae=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,eoe=/^!(?=\[)/,toe=/^\[\^/,noe=/^\]\[[^\]]*\]/,roe=/^\[\[[^\][|]*\|/,ioe=/^#[^\][|]*(?=\]\])/,aoe=/^\]\([^)]*\)/,ooe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,soe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,coe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function loe(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,$i as u,$l as d,$n as f,$o as p,$r as m,$s as h,$t as g,$u as _,A as v,Aa as y,Ac as b,Ad as x,Ai as S,Al as C,An as w,Ao as T,Ar as E,As as D,At as O,Au as ee,B as k,Ba as A,Bc as te,Bd as j,Bi as M,Bl as ne,Bn as re,Bo as ie,Br as ae,Bs as N,Bt as oe,Bu as se,Ca as ce,Cc as le,Cd as ue,Cf as de,Ci as fe,Cl as pe,Cn as me,Co as he,Cr as ge,Cs as _e,Ct as ve,Cu as ye,D as be,Da as xe,Dc as Se,Dd as Ce,Di as we,Dl as Te,Dn as Ee,Do as De,Dr as Oe,Ds as ke,Dt as Ae,Du as je,E as Me,Ea as Ne,Ec as Pe,Ed as P,Ei as Fe,El as Ie,En as Le,Eo as Re,Er as ze,Es as Be,Et as Ve,Eu as He,Fa as Ue,Fc as We,Fd as F,Fi as Ge,Fn as Ke,Fo as qe,Fr as Je,Fs as Ye,Ft as Xe,Fu as Ze,Ga as Qe,Gc as $e,Gd as et,Gi as tt,Gl as nt,Gn as rt,Go as it,Gr as at,Gs as ot,Gt as st,Gu as ct,H as lt,Ha as ut,Hc as dt,Hi as ft,Hl as pt,Hn as mt,Ho as ht,Hr as gt,Hs as _t,Ht as vt,Hu as yt,Ia as bt,Ic as xt,Id as I,Ii as St,In as Ct,Io as wt,Ir as Tt,Is as Et,It as Dt,Iu as Ot,J as kt,Ja as At,Jc as jt,Jd as Mt,Ji as Nt,Jn as Pt,Jo as Ft,Jr as It,Js as Lt,Jt as Rt,Ju as zt,K as Bt,Ka as Vt,Kc as Ht,Kd as Ut,Ki as Wt,Kl as Gt,Kn as Kt,Ko as qt,Kr as Jt,Ks as Yt,Kt as Xt,Ku as Zt,L as Qt,La as $t,Lc as en,Ld as tn,Li as nn,Ll as rn,Ln as an,Lo as on,Lr as sn,Ls as cn,Lt as ln,Lu as un,M as dn,Ma as fn,Mc as pn,Md as L,Mi as mn,Ml as hn,Mn as gn,Mo as _n,Mr as vn,Ms as yn,Mt as bn,Mu as xn,Na as Sn,Nc as Cn,Nd as R,Ni as wn,Nl as Tn,Nn as En,No as Dn,Nr as On,Ns as kn,Nt as An,Nu as jn,O as Mn,Oa as Nn,Oc as Pn,Od as Fn,Of as In,Oi as Ln,Ol as Rn,On as zn,Oo as Bn,Or as Vn,Os as Hn,Ot as Un,Ou as Wn,P as Gn,Pa as Kn,Pc as qn,Pd as Jn,Pi as Yn,Pn as Xn,Po as Zn,Pr as Qn,Ps as $n,Pt as er,Pu as tr,Q as nr,Qa as rr,Qc as ir,Qd as ar,Qi as or,Qn as sr,Qo as eee,Qr as cr,Qs as lr,Qt as ur,Qu as dr,R as fr,Ra as pr,Rd as mr,Ri as tee,Rn as hr,Ro as gr,Rr as _r,Rs as vr,Rt as yr,Ru as br,Sa as xr,Sc as Sr,Sd as Cr,Si as wr,Sl as Tr,Sn as Er,So as Dr,Sr as Or,Ss as kr,St as Ar,Su as jr,T as Mr,Ta as Nr,Tc as Pr,Td as Fr,Ti as Ir,Tl as Lr,Tn as nee,To as Rr,Tr as ree,Ts as zr,Tt as Br,Tu as Vr,Ua as Hr,Uc as Ur,Ud as Wr,Ui as Gr,Ul as Kr,Un as qr,Uo as Jr,Ur as Yr,Us as Xr,Ut as Zr,Uu as Qr,V as $r,Va as ei,Vc as ti,Vd as ni,Vi as ri,Vl as ii,Vn as ai,Vo as oi,Vr as si,Vs as iee,Vt as aee,Vu as ci,Wa as li,Wc as oee,Wd as see,Wi as cee,Wl as ui,Wn as lee,Wo as uee,Wr as dee,Ws as fee,Wt as pee,Wu as mee,Xa as hee,Xd as gee,Xi as _ee,Xl as vee,Xn as yee,Xo as bee,Xr as xee,Xt as di,Xu as fi,Y as See,Ya as pi,Yd as Cee,Yi as wee,Yl as Tee,Yn as Eee,Yo as Dee,Yr as Oee,Ys as kee,Yt as mi,Yu as hi,Za as Aee,Zc as jee,Zd as Mee,Zi as gi,Zn as Nee,Zo as Pee,Zr as Fee,Zs as _i,Zt as vi,Zu as yi,_ as Iee,_a as bi,_c as xi,_d as Si,_i as Ci,_l as Lee,_n as Ree,_o as zee,_r as wi,_s as Bee,_t as Ti,_u as Ei,a as Vee,aa as Di,ac as Hee,ad as Uee,ai as Wee,al as Gee,an as Kee,ao as qee,ar as Jee,as as Oi,at as Yee,au as ki,b as Ai,bc as ji,bd as z,bf as Mi,bi as Xee,bl as Zee,bn as Qee,bo as $ee,br as Ni,bs as ete,bt as tte,bu as nte,c as rte,ca as ite,cd as ate,ci as ote,cl as ste,cn as Pi,co as Fi,cr as cte,cs as lte,ct as Ii,cu as ute,d as Li,da as dte,dc as Ri,di as fte,dl as pte,dn as mte,do as hte,dr as gte,ds as _te,dt as zi,du as Bi,ea as vte,ec as yte,ed as Vi,ef as Hi,ei as Ui,el as Wi,en as bte,eo as xte,er as Gi,es as Ki,et as Ste,eu as qi,fa as Cte,fc as Ji,fd as wte,fi as Tte,fl as Ete,fn as Dte,fo as Ote,fr as kte,fs as Ate,ft as Yi,fu as Xi,g as jte,ga as Mte,gd as Nte,gf as Pte,gi as Fte,gl as Zi,gn as Ite,go as Qi,gr as Lte,gs as Rte,gt as $i,gu as zte,h as Bte,ha as ea,hc as ta,hf as Vte,hi as Hte,hn as Ute,ho as na,hr as Wte,hs as Gte,ht as Kte,hu as ra,ia as qte,ic as Jte,id as Yte,if as ia,ii as Xte,il as Zte,in as Qte,io as $te,ir as ene,is as tne,it as aa,iu as nne,j as oa,ja as sa,jc as rne,jd as ine,ji as ane,jl as one,jn as sne,jo as ca,jr as cne,js as la,jt as lne,ju as ua,kd as B,ki as da,kl as fa,kn as une,ko as dne,kr as fne,ks as pne,kt as mne,ku as hne,la as pa,lc as ma,ld as gne,lf as _ne,li as vne,ll as ha,ln as yne,lo as bne,lr as xne,ls as Sne,lt as ga,lu as Cne,m as _a,ma as wne,mc as va,mf as Tne,mi as Ene,mn as Dne,mo as One,mr as kne,ms as Ane,mt as jne,mu as ya,n as ba,na as Mne,nc as Nne,nd as Pne,nf as Fne,ni as Ine,nl as Lne,nn as Rne,no as xa,nr as zne,ns as Bne,nt as Vne,nu as Hne,o as Une,oa as Wne,od as Gne,of as Sa,oi as Kne,ol as Ca,on as qne,oo as Jne,or as Yne,os as Xne,ot as wa,ou as Zne,pa as Qne,pc as $ne,pd as ere,pi as tre,pn as nre,po as rre,pr as Ta,ps as ire,pt as Ea,pu as are,qa as ore,qd as sre,qi as cre,ql as lre,qn as ure,qo as dre,qr as fre,qs as pre,qt as mre,qu as hre,ra as gre,rc as _re,rd as vre,ri as yre,rl as bre,rn as xre,ro as Sre,rr as Cre,rs as wre,rt as Tre,ru as Ere,s as Da,sa as Oa,sc as ka,sd as Dre,sf as Aa,si as ja,sl as Ma,sn as Ore,so as kre,sr as Are,ss as jre,st as Na,su as Pa,t as Fa,tc as Ia,td as Mre,tf as Nre,ti as La,tn as Pre,to as Fre,tr as Ire,ts as Ra,tu as Lre,ua as Rre,uc as za,ud as zre,uf as Ba,ui as Bre,ul as Va,un as Vre,uo as Hre,ur as Ure,us as Wre,ut as Ha,uu as Ua,v as Gre,va as Kre,vc as Wa,vd as Ga,vf as qre,vi as Jre,vn as Ka,vo as qa,vr as Ja,vs as Yre,vt as Ya,vu as Xre,w as Zre,wa as Xa,wc as Za,wd as Qa,wf as $a,wi as eo,wl as Qre,wn as $re,wo as to,wr as eie,ws as tie,wt as no,wu as nie,x as rie,xa as ro,xc as io,xd as ao,xf as iie,xi as aie,xl as oie,xn as sie,xo as cie,xr as lie,xs as uie,xt as oo,xu as so,y as die,yc as fie,yf as co,yi as lo,yl as pie,yn as uo,yo as mie,yr as hie,ys as gie,yt as fo,yu as _ie,za as po,zc as vie,zd as yie,zi as bie,zl as xie,zn as Sie,zo as mo,zr as Cie,zs as wie,zt as ho,zu as Tie}from"./md-manager-BGnqyqi1-DRBNLmLZ.mjs";import{c as go,d as _o,h as Eie,i as vo,l as yo,n as bo,o as xo,p as So,t as Co}from"./esm-B3YyV3nD.mjs";import{t as Die}from"./libesm-DRoEqbAC.mjs";import{t as Oie}from"./yazl-BBz29IQN.mjs";import{t as wo}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as To,c as Eo,d as kie,f as Do,h as Aie,i as Oo,l as ko,m as Ao,n as jo,o as Mo,p as No,r as Po,s as Fo,t as Io,u as Lo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as Ro,B as zo,C as Bo,D as Vo,E as jie,F as Mie,H as Nie,I as Pie,L as Ho,M as Uo,N as Wo,O as Go,P as Ko,S as Fie,T as Iie,V as Lie,_ as Rie,a as qo,b as Jo,c as Yo,d as Xo,f as Zo,g as zie,h as Bie,i as Qo,j as $o,k as es,l as ts,m as Vie,n as Hie,o as ns,p as rs,r as is,s as as,t as Uie,u as os,v as ss,w as cs,x as ls,y as us,z as ds}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as fs,r as ps,t as ms}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as hs}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as gs}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as _s,t as vs}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as Wie,t as Gie}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as ys,r as bs,t as xs}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as Kie,t as Ss}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as Cs}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as ws}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as qie}from"./wrapper-BF8oRx3G.mjs";import{createRequire as Ts}from"node:module";import{execFile as Es,execFileSync as Ds,spawn as Os,spawnSync as ks}from"node:child_process";import*as As from"node:path";import{basename as js,delimiter as Ms,dirname as V,extname as Ns,isAbsolute as Ps,join as H,normalize as Fs,parse as Is,posix as Ls,relative as U,resolve as W,sep as Rs,win32 as zs}from"node:path";import{URLSearchParams as Jie,fileURLToPath as Bs,pathToFileURL as Vs}from"node:url";import*as Hs from"node:fs";import{accessSync as Yie,appendFileSync as Us,chmodSync as Ws,closeSync as Gs,constants as Ks,cpSync as Xie,createReadStream as qs,createWriteStream as Js,existsSync as G,fchmodSync as Zie,fstatSync as Qie,linkSync as $ie,lstatSync as Ys,mkdirSync as Xs,mkdtempSync as Zs,openSync as Qs,opendirSync as $s,readFile as eae,readFileSync as K,readSync as ec,readdirSync as tc,readlinkSync as tae,realpathSync as nc,renameSync as rc,rmSync as ic,rmdirSync as ac,statSync as oc,symlinkSync as nae,unlinkSync as sc,watch as rae,writeFileSync as cc,writeSync as lc}from"node:fs";import{arch as uc,availableParallelism as iae,homedir as dc,hostname as fc,platform as pc,tmpdir as mc,userInfo as aae}from"node:os";import{access as hc,appendFile as oae,chmod as sae,constants as cae,glob as lae,lstat as gc,mkdir as _c,readFile as vc,readdir as yc,readlink as uae,realpath as bc,rename as xc,rm as dae,stat as Sc,unlink as fae,writeFile as Cc}from"node:fs/promises";import{Readable as wc,Transform as pae,Writable as mae}from"node:stream";import hae from"crypto";import gae,{createHash as Tc,randomUUID as Ec,webcrypto as Dc}from"node:crypto";import{EventEmitter as _ae}from"node:events";import{Worker as vae}from"node:worker_threads";import*as yae from"zlib";import{Readable as Oc}from"stream";import{readdirSync as bae,statSync as xae}from"fs";import{spawn as Sae}from"child_process";import{promisify as kc,stripVTControlCharacters as Cae}from"node:util";import{DatabaseSync as Ac}from"node:sqlite";import{monitorEventLoopDelay as wae,performance as Tae}from"node:perf_hooks";import{createInterface as Eae}from"node:readline";import{setImmediate as Dae,setTimeout as Oae}from"node:timers/promises";import{AsyncLocalStorage as kae}from"node:async_hooks";import{pipeline as jc}from"node:stream/promises";import{request as Aae}from"node:http";import{Http2ServerRequest as Mc,constants as jae}from"node:http2";import{lookup as Mae}from"node:dns/promises";import{request as Nae}from"node:https";import{createBrotliDecompress as Pae,createGunzip as Fae,createInflate as Iae}from"node:zlib";import{join as Nc,resolve as Lae}from"path";import*as Rae from"node:querystring";import{Http2ServerRequest as Pc,constants as zae}from"http2";import{lookup as Bae}from"node:dns";import Vae from"node:tls";const Hae=2,Fc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},Uae={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},Wae={mcp:!0,"desktop-main":!0,cli:!0};function Gae(e){return Object.hasOwn(Uae,e)}function Kae(e){if(!(e===void 0||e.length===0||Object.hasOwn(Wae,e)))return Gae(e)?e:`unknown`}function qae({kind:e,runtimeVersion:t}){return{[Fc.protocol]:`2`,[Fc.runtime]:t,[Fc.kind]:e}}const Jae=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),Yae=/^={2,}/,Xae=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function Zae(e,t){return Xae.test(e.slice(t,t+512))}function Qae(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:Xae.exec(e.slice(n,t+1))?.[0].length===t+1-n}const $ae=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,eoe=/^!(?=\[)/,toe=/^\[\^/,noe=/^\]\[[^\]]*\]/,roe=/^\[\[[^\][|]*\|/,ioe=/^#[^\][|]*(?=\]\])/,aoe=/^\]\([^)]*\)/,ooe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,soe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,coe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function loe(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||!soe.test(i)&&!coe.test(i)?0:i.length}const uoe=/&#(?:x[0-9A-Fa-f]+|X[0-9A-Fa-f]+|[0-9]+);/y;function Ic(e,t){if(e[t]!==`&`)return null;let n=t,r=``;for(;;){uoe.lastIndex=n;let t=uoe.exec(e)?.[0];if(t===void 0)break;let i=nne(t);if(i===null)break;r+=i,n+=t.length}return n===t?null:{length:n-t,rendered:r}}function Lc(e){return e===` `||e===` `||e===`
3
3
  `||e===`\r`||e===`\f`||e===`\v`}function doe(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 Rc(e,t){let n=e[t];if(n===void 0)return 0;if(doe(e,t)){let n=loe(e,t);if(n>0)return n}if(n===`|`)return 1;if(n===`<`){let n=$ae.exec(e.slice(t,t+512))?.[0].length;return n===void 0?+!!Zae(e,t):n}if(n===`>`&&Qae(e,t))return 1;if(n===`=`){let n=Yae.exec(e.slice(t,t+3))?.[0].length;if(n!==void 0)return n}if(n===`!`)return+!!eoe.test(e.slice(t,t+2));if(Jae.has(n))return 1;if(n===`[`){let n=e.slice(t,t+512),r=roe.exec(n)?.[0].length;return r===void 0?toe.test(n)?2:1:r}if(n===`#`){let n=ioe.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=aoe.exec(n)?.[0].length;if(r!==void 0)return r;let i=noe.exec(n)?.[0].length;return i===void 0?1:i}return doe(e,t)?ooe.exec(e.slice(t,t+32))?.[0].length??0:0}function foe(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||Lc(a)||i&&a!==t[0]&&(Rc(e,n)>0||Ic(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(Lc(r)){s+=1;continue}if(Lc(n)){o+=1;continue}let a=i?Rc(e,o):Rc(t,s);if(a>0){i?o+=a:s+=a;continue}let c=i?Ic(e,o):Ic(t,s);if(c!==null){let n=i?t:e,r=i?s:o,a=!0;for(let e of c.rendered)if(!Lc(e)){for(;r<n.length&&Lc(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&&Lc(t[s]);)s+=1;s===t.length&&r.push({start:n,end:o})}return r}function zc(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(Lc(t)){a+=1;continue}if(r){let t=Rc(e,a);if(t>0){a+=t;continue}let n=Ic(e,a);if(n!==null){for(let e of n.rendered)Lc(e)||(i+=e);a+=n.length;continue}}i+=t,a+=1}return i}function poe(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 moe(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function hoe(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+=poe(zc(a,0,a.length,i),zc(e,t.start-n,t.start,s))}if(o.length>0){let n=o.length*8+64;c+=moe(zc(o,0,o.length,i),zc(e,t.end,t.end+n,s))}return c}function goe(e,{syntaxInContext:t=!1}={}){let n=zc(e.prefix??``,0,1/0,t).length+zc(e.suffix??``,0,1/0,t).length;return Math.min(8,n)}function _oe(e){return Math.max(e*4,e+64)}function Bc(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 Vc=`epoch`,voe=524288,Hc={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},Uc=[`incoming`,`outgoing`,`both`];function yoe(e){return Uc.includes(e)}const boe=[{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)">
@@ -2153,11 +2153,11 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
2153
2153
  `:``}function vCt(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is a non-GitHub remote (GitLab, Bitbucket, etc.). Share links require a GitHub remote (`github.com` or GitHub Enterprise Server).";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";case`unsupported-share-url`:return`The GitHub URL cannot be represented by the share-link format. Use a canonical DNS GitHub host and a shorter repository path.`;default:return`Unknown share-construct-url error: ${String(e)}`}}function yCt(e){try{return oc(e).isDirectory()}catch{return!1}}function bCt(e,t){for(let n of ka){let r=`${t}${n}`;if(G(r)){let t=N3(e,r);return t.ok?t.rel:null}}return null}function xCt(e,t,n){if(t===``)return n===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let r=N3(e,t);if(!r.ok)return{ok:!1,code:`target-not-found`};let i=bCt(e,r.abs.replace(/\.(mdx|md)$/i,``)),a=yCt(r.abs);return n===`doc`?i===null?a?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:i}:n===`folder`?a?{ok:!0,kind:`folder`,sharePath:r.rel}:i===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}:i===null?a?{ok:!0,kind:`folder`,sharePath:r.rel}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:i}}const SCt=U3({ok:ao().describe(`Success discriminator.`),shareUrl:R().optional().describe(`Marketing share URL (success only).`),sharedUrl:R().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:R().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:Si([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:yn.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:Si([...pne.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:R().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:R().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:R().optional().describe(`Internal: preview-URL provenance.`)});function CCt(e,t){e.registerTool(`share_link`,{description:gCt,inputSchema:{path:R().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:Si([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:R().optional().describe(F3)},outputSchema:SCt,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let n=await J3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return $(G3,!0);let o=xCt(H(r,i.content.dir),e.path,e.kind);if(!o.ok){let t;if(o.code===`kind-mismatch`){let n=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${n}. Pass \`kind: '${n===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=o.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let n={ok:!1,error:o.code,message:t};return W3(`Error: ${t}`,n,!0)}let s=o.kind===`doc`?{kind:`doc`,docPath:o.sharePath}:{kind:`folder`,folderPath:o.sharePath},c;try{c=await fetch(`${a}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e6(e,{mutating:!1});return W3(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let l;try{l=await c.json()}catch(e){let t=$3(e)?e6(e,{mutating:!1}):`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return W3(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!c.ok){let e;if(l&&typeof l==`object`){let t=l,n=typeof t.title==`string`?t.title:void 0,r=typeof t.detail==`string`?t.detail:void 0;e=n&&r?`${n}: ${r}`:n||r||`HTTP ${c.status}`}else e=`HTTP ${c.status}`;return W3(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let u=la.safeParse(l);if(!u.success){let e=`Server returned an unexpected share-construct-url response shape.`;return W3(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let d=u.data;if(!d.ok){let e=vCt(d.error,d.branch),t={ok:!1,error:d.error,message:e,...d.branch?{branch:d.branch}:{}};return W3(`Error: ${e}`,t,!0)}let{shareUrl:f,sharedUrl:p,branch:m,freshness:h}=d,g={ok:!0,shareUrl:f,sharedUrl:p,branch:m,resolvedKind:o.kind,...h?{freshness:h}:{}},_={config:t.config,resolveCwd:t.resolveCwd},v=await i7(o.sharePath.replace(/\.(mdx|md)$/i,``),_,r);if(v&&o.kind===`folder`){let e=o.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${t7(e)}/`;v={...v,url:t}}let y=e.path===``?`(content root)`:e.path;return W3(`${_Ct(h,o.kind)}Share link for ${o.kind} \`${y}\` on branch \`${m}\`:\n${f}`,{...g,previewUrl:v?.url??null,...v?{previewUrlSource:v.source}:{}})})}function wCt(e){return e.replace(/\\/g,`/`).startsWith(`scripts/`)?`script`:`reference`}function TCt(e){let t=String(e.name),n=e.scope===`global`?`global`:`project`,r=Array.isArray(e.hosts)?e.hosts:[],i=new Set(Array.isArray(e.symlinkedHosts)?e.symlinkedHosts:[]),a=e.hostAliases??{},o=new Set(Array.isArray(e.driftPaths)?e.driftPaths:[]),s=e=>e===`agents`?A:e.includes(`/`)?e:(n===`project`?Sa:Aa)[e]??e,c=e=>Object.keys(a).filter(t=>a[t]===e),l=r.map((e,n)=>{let r=s(e),a=`${r}/${t}`,l=c(r);return{id:e,path:a,role:n===0?`source`:i.has(e)?`symlink`:`copy`,...l.length>0?{audience:l}:{},...o.has(a)?{drift:!0}:{}}}),u=Array.isArray(e.customPlacements)?e.customPlacements:[];for(let e of u){if(l.some(t=>t.path===e.path))continue;let t=e.path.split(`/`).slice(0,-1).join(`/`),n=c(t);l.push({id:t,path:e.path,role:e.mode===`link`?`symlink`:`copy`,...n.length>0?{audience:n}:{},...o.has(e.path)?{drift:!0}:{}})}let d=Array.isArray(e.conflictHosts)?e.conflictHosts:[];return{name:e.name,scope:e.scope,...typeof e.description==`string`?{description:e.description}:{},installed:e.installed===!0,hosts:l.map(e=>e.id),locations:l,mode:e.linkMode===!0?`link`:`copy`,...d.length>0?{conflicts:d}:{}}}function ECt(e){return[`"${e}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,`It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.`,"The `skills` tool covers skills wherever they live — editor dirs (`.claude/skills`, …), the `.agents/skills` hub, custom roots, and the legacy `.ok/skills` store, at project AND global (user-home) level. Built-in `open-knowledge*` skills never appear."].join(` `)}const DCt="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",OCt=B({id:R().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:R().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:Si([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, refreshed from the source on watcher/startup sync while unedited (hand edits fork it); symlink = live link to the source.`),audience:z(R()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:ao().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)}),kCt=B({name:R().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:Si([`project`,`global`]).describe(DCt),description:R().optional().describe(`The skill's one-line description (when present).`),installed:ao().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:z(R()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:z(OCt).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:Si([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:z(R()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)}),ACt=B({path:R().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:Si([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")}),jCt=B({name:R().describe(`Skill name (its identity).`),scope:Si([`project`,`global`]).describe(DCt),description:R().describe(`The skill's one-line description (empty if none).`),body:R().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:z(ACt).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),MCt=B({path:R().describe(`Skill-relative path read.`),kind:Si([`reference`,`script`]).describe("`reference` or `script`."),text:R().describe(`Full text of the bundle file.`)}),NCt=B({name:R().describe("Skill name to pass as `skill` to `import`."),source:R().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:R().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:Fn().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:R().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),PCt=[`Read-only skill discovery. Requires the Hocuspocus server. query searches the skills.sh marketplace and returns import-ready name/source/description/publisher/install-count rows. Import a chosen row with import({source,skill:name}); external rows are not managed or active editor content until imported/projected.`,`Omit name to list Project and Global managed skills with scope/description/hosts. name reads description/body plus a bundle files list (path/kind, no inline text); name+file reads one reference/script/bundle file. Optional scope; name-only prefers Project. Address skills by name/scope, never raw .ok/ paths or native cat.`,`Built-in open-knowledge* runtime skills are already in your skill list; do not fetch them here. Use write/edit/delete/move/install for changes.`].join(`
2154
2154
  `);function FCt(e,t){e.registerTool(`skills`,{description:PCt,inputSchema:{query:R().optional().describe("Marketplace search query for skills.sh. Use this before `import` when looking for an external skill; do not combine with `name` or `file`."),name:R().optional().describe(`Managed skill name. Omit to LIST all managed skills; pass a name to READ that skill.`),file:R().optional().describe("With `name`: read ONE bundle file by its skill-relative path (e.g. `references/x.md`, `agents/openai.yaml`)."),scope:d7.optional(),cwd:R().optional().describe(F3)},outputSchema:U3({skills:z(kCt).optional().describe(`Present in LIST mode: every skill across Project + Global levels.`),skill:jCt.optional().describe(`Present in READ-skill mode: the named skill (description, body, files list).`),file:MCt.optional().describe(`Present in READ-file mode: one bundle file (path, kind, text).`),results:z(NCt).optional().describe("Present in Marketplace search mode: import-ready external skill candidates. Pick one, then call `import({ source, skill: name })`."),backend:Si([`skills.sh`,`github-fallback`]).optional().describe(`Marketplace backend that answered the query.`),degraded:ao().optional().describe(`True when the GitHub fallback answered instead of skills.sh.`)})},async e=>{if(e.query!==void 0&&(e.name!==void 0||e.file!==void 0))return $("Error: `query` is marketplace search mode — do not combine it with `name` or `file`.",!0);if(e.name!==void 0&&HZ.has(e.name))return $(`Error: ${ECt(e.name)}`,!0);let n=await J3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{url:r}=n;if(!r)return $(G3,!0);if(e.query!==void 0){let t=e.query.trim();if(t.length<2)return $("Error: `query` needs at least 2 characters — the skills.sh search rejects shorter terms.",!0);let n=await n6(r,`/api/skills/search?q=${encodeURIComponent(t)}`,`results`);if(`error`in n)return $(`Error: ${n.error}`,!0);let{rows:i,data:a}=n,o=i.flatMap(e=>typeof e.name!=`string`||typeof e.source!=`string`?[]:[{name:e.name,source:e.source,description:typeof e.description==`string`?e.description:``,installs:typeof e.installs==`number`&&Number.isInteger(e.installs)&&e.installs>=0?e.installs:null,publisher:typeof e.publisher==`string`?e.publisher:null}]),s=a.backend===`github-fallback`?`github-fallback`:`skills.sh`,c=a.degraded===!0;return W3(JSON.stringify({results:o,backend:s,degraded:c},null,2),{results:o,backend:s,degraded:c})}if(e.file!==void 0&&e.name===void 0)return $('Error: `file` reads ONE bundle file of a skill — pass `name` too: skills({ name, file: "references/x.md" }).',!0);let i;if(e.file!==void 0){let t=p7(e.file);if(!t.ok)return $(`Error: ${t.error}`,!0);i=t.path}if(e.name===void 0){let t=await n6(r,`/api/skills`,`skills`);if(`error`in t)return $(`Error: ${t.error}`,!0);let n=t.rows.filter(e=>!UZ(String(e.name))),i=(e.scope===void 0?n:n.filter(t=>t.scope===e.scope)).map(e=>TCt(e));return W3(JSON.stringify({skills:i},null,2),{skills:i})}let a=e.scope;if(a===void 0){let t=await n6(r,`/api/skills`,`skills`);if(`error`in t)return $(`Error: ${t.error}`,!0);let n=t.rows.filter(t=>t.name===e.name);if(n.length===0)return $(`Error: no skill named "${e.name}" (Project or Global).`,!0);a=n.find(e=>e.scope===`project`)===void 0?n[0]?.scope:`project`}if(e.file!==void 0){let t=await mbt(r,a,e.name,i??e.file);if(!t.ok)return $(`Error: ${t.error}`,!0);let n={path:t.path,kind:t.kind,text:t.text};return W3(JSON.stringify({file:n},null,2),{file:n})}let o=await fbt(r,a,e.name);if(!o.ok)return $(`Error: ${o.error}`,!0);let s={name:e.name,scope:a,description:o.description,body:o.body,files:o.files.map(e=>({path:e.path,kind:wCt(e.path)}))};return W3(JSON.stringify({skill:s},null,2),{skill:s})})}const ICt=["Create/replace exactly one `document`, `folder`, `template`, `skill`, or `asset`; use `documents` for an ordered batch. Requires the Hocuspocus server.","Nested paths such as `guides/overview` can be documents; put all requested blocks in one `document.content`. Use `folder` only for separate pages.","`document: {path, content|template, frontmatter?, position?}`: content and template are exclusive. Existing docs require position: replace/append/prepend; new docs default replace. frontmatter with literal content forces replace, even with append/prepend. Recent edits by another writer can refuse replace; follow the recovery response; append/prepend/edit bypass this refusal. Peers are per MCP connection; own writes and writers sharing a connection do not refuse each other; connected editors can. No agentId is needed.","`folder: {path, frontmatter?}` creates NEW folders; edit existing ones. `template: {path: '<folder>/<name>', content, frontmatter: {title, description?, tags?}}` creates reusable doc templates.","`skill: {name, description, body, scope?}` writes agent guidance; lowercase letters/digits/hyphens name is identity, description is when to use it. New skills use the default skill home; existing ones keep their real folder. Use install for editors.","`asset: {path, content|source}` uploads binary image/file: base64 content or local source path. `documents` takes document specs and reports each result.",`Optional summary: one-line outcome ≤80 chars, persisted to git history; avoid secrets or PII. Batches need per-entry summary; top-level is ignored.`,`Read response warnings: content-divergence/disk-edit-reconciled means re-read; mermaid-parse-error means the write landed but fix the fence.`,Cct].join(`
2155
2155
  `);function LCt(e,t){return e!==`prepend`&&e!==`append`||!t||fi(t).frontmatter.trim()===``?null:$W(t).frontmatter.trim()===``?`Note: this \`${e}\` payload opens with a \`---\` fence pair, but what is between the fences is not a YAML mapping, so it was written as BODY text (fence lines included) rather than treated as frontmatter. If you meant a thematic break, that is the correct outcome — \`***\` or \`___\` avoids the ambiguity. If you meant to set frontmatter, the YAML did not parse: use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function RCt(e,t){return`Created new document "${e}" — no document existed at this path, so \`${t}\` started a new one. If you meant to add to an existing document, the path is wrong (paths are relative to the content root): remove this one with \`delete({ document: "${e}" })\` and retry at the intended path.`}function zCt(e,t){return e!==`prepend`&&e!==`append`||t===void 0||$W(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function BCt(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function VCt(e,t,n){return e===null||t===null||e===t?null:`Note: "${n}" already exists as \`${n}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${n}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function HCt(e,t){let{frontmatter:n,body:r}=fi(t),i={};if(n!==``){let e=ct(yi(n));if(e.map===null)return{ok:!1,error:`EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${e.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`};i=e.map}let a=_6(i,e),o=Zt(a);return o===``?{ok:!0,markdown:r}:{ok:!0,markdown:hre(o)+r}}const UCt=new Set([`urn:ok:error:invalid-request`,`urn:ok:error:invalid-frontmatter-patch`]);function WCt(e){return e.committed===!1||UCt.has(e.type)}async function GCt(e,t,n,r,i){let a=X3(e.path);if(!a.ok)return{docName:e.path,ok:!1,error:Y3(e.path)??a.error};let o=a.docName,s=i.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:o,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:o,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let c=e.content??``,l=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,u=Act(n,o)??null,d=u!==null,f=e.extension??BCt(e.path),p;if(e.position!==void 0)p=e.position;else if(d)return{docName:o,ok:!1,error:`"${o}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else p=`replace`;let m;if(e.template===void 0&&!d){let e=S3(t,Xct(o));e.length>0&&(m=e.map(e=>({name:e.name,...e.description?{description:e.description}:{}})))}if(e.template!==void 0){let n=Xct(o),r=S3(t,n),i=r.find(t=>t.name===e.template);if(!i)return{docName:o,ok:!1,error:`template "${e.template}" not found for folder "${n||`.`}". Available: ${r.length===0?`(none)`:r.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let a;try{a=K(W(t,i.path),`utf-8`)}catch(e){return{docName:o,ok:!1,error:`failed to read template at ${i.path}: ${e.message}`}}c=act(Qt(a),{date:sct(),user:s?.displayName??``}),p=`replace`}else if(l){let t=HCt(e.frontmatter,c);if(!t.ok)return{docName:o,ok:!1,error:t.error};c=t.markdown,p=`replace`}if(!d&&ua(c)===``)return{docName:o,ok:!1,error:`"${o}" does not exist and the content is empty — provide non-empty content to create the document.`};let h=await i6(r,`/api/agent-write-md`,{docName:o,markdown:c,position:p,...f!==null&&!d?{extension:f}:{},...e.summary===void 0?{}:{summary:e.summary},...P3(s)});if(!h.ok){let t=h.type===`urn:ok:error:invalid-request`&&h.contentControlAdmission===!0?e.template===void 0?l?` Any markdown offset refers to composed Markdown including frontmatter.`:` Any markdown offset refers to document.content as forwarded.`:` Any markdown offset refers to generated template Markdown after substitution.`:``,n=h.type===`urn:ok:error:concurrent-overwrite-refused`?` Wait and retry, or use edit for a targeted change.`:``;return{docName:o,ok:!1,error:`${V3(h)}${t}${n}`}}if(e.template!==void 0&&l){let t=await i6(r,`/api/frontmatter-patch`,{docName:o,patch:e.frontmatter,...P3(s)});if(!t.ok)return{docName:o,ok:!1,error:WCt(t)?`document created from template "${e.template}", but its frontmatter patch was refused, so the document exists without that frontmatter: ${V3(t)} Apply the frontmatter alone with edit({ document: { path: "${o}", frontmatter } }); do not repeat the templated write.`:`document created from template "${e.template}", but its frontmatter patch failed, and this response does not show whether the frontmatter was applied: ${V3(t)} Re-read the document before changing it; do not repeat the templated write.`}}let g=VCt(f,u,o),_=!d&&(p===`append`||p===`prepend`)?p:void 0;return{docName:o,ok:!0,position:p,..._?{createdByPosition:_}:{},...e.template===void 0?{}:{fromTemplate:e.template},...g?{extensionNote:g}:{},...m?{templateHint:m}:{},raw:h}}function KCt(e){return`ℹ This folder has templates you can start from: ${e.map(e=>e.description?`${e.name} (${e.description})`:e.name).join(`, `)}. Pass \`template: "${e[0]?.name??``}"\` next time to match the folder's shape (the doc still landed).`}async function qCt(e,t,n,r){if(!n)return $(G3,!0);let i=r.identityRef?.current,a=await i6(Q3(n,r.localApi),`/api/create-folder`,{path:e.path,...t===void 0?{}:{summary:t},...P3(i)});if(!a.ok){let e=typeof a.detail==`string`&&a.detail.length>0?a.detail:``;return $(e?`Error: ${a.error} (${e})`:`Error: ${a.error}`,!0)}let o=[`Created folder ${e.path}.`];if(e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0){let r=await a6(n,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...P3(i)});if(!r.ok)return W3(`Created folder ${e.path}, but writing its properties failed: ${r.error}. Use edit({ folder: { path: "${e.path}", frontmatter } }) to retry the properties.`,{folder:{ok:!0,path:e.path,frontmatterError:String(r.error)}});o.push(`Set folder properties (${e.path}/.ok/frontmatter.yml).`)}return W3(o.join(`
2156
- `),{folder:{ok:!0,path:e.path}})}async function JCt(e,t,n,r){let i=l7(e.path);if(!i.ok)return $(`Error: ${i.error}`,!0);let{folder:a,name:o}=i;if(!n)return $(G3,!0);let s=await a6(n,`/api/template`,{folder:a,name:o,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...P3(r.identityRef?.current)});if(!s.ok)return $(H3(s,`Any body offset refers to the full submitted template.content.`),!0);let c=s.created===!0,l=typeof s.path==`string`?s.path:void 0;return W3(`${c?`Created`:`Updated`} template "${o}" in ${a||`(root)`}${l?` (${l})`:``}.`,{template:{ok:!0,path:l,created:c}})}async function YCt(e,t,n,r){if(!n)return $(G3,!0);if(e.content===void 0==(e.source===void 0))return $("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let i;try{i=e.content===void 0?K(W(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return $(`Error: could not read asset bytes: ${e.message}`,!0)}if(i.byteLength===0)return $(`Error: asset is empty (0 bytes).`,!0);let{folder:a,name:o}=obt(e.path),s=a?`${a}/${o}`:o,c=r.identityRef?.current,l=new URLSearchParams;c?.connectionId&&l.set(`agentId`,c.connectionId),c?.displayName&&l.set(`agentName`,c.displayName);let u=l.toString(),d=new FormData;d.append(`parentDocName`,s),d.append(`file`,new Blob([new Uint8Array(i)]),o);let f=`/api/upload${u?`?${u}`:``}`,p=r.localApi,m=null;if(p)try{let e=new Request(`http://localhost/api/upload`,{method:`POST`,body:d}),t=e.headers.get(`content-type`)??`multipart/form-data`;m={body:new Uint8Array(await e.arrayBuffer()),contentType:t}}catch(e){return $(`Error: upload request failed: ${e.message}`,!0)}let h,g;try{let e=p&&m?await p(`POST`,f,m):null;if(e!==null)h=e.status,g=e.bodyText;else{let e=await fetch(`${n}${f}`,{method:`POST`,body:d,signal:AbortSignal.timeout(3e4)});h=e.status,g=await e.text()}}catch(e){return $(`Error: ${e6(e)}`,!0)}let _=h>=200&&h<=299,v;try{v=JSON.parse(g)}catch(e){let t=e instanceof Error?e.message:String(e);return $(_?`Error: Server returned 2xx response with non-JSON body: ${t}`:`Error: Server returned HTTP ${h} with non-JSON body: ${t}`,!0)}let y=_?{ok:!0,status:h,data:v??{}}:{ok:!1,status:h,error:v&&(typeof v.title==`string`?v.title:v.error)||`Upload failed (HTTP ${h}).`};if(!y.ok)return $(`Error: ${y.error}`,!0);let b=typeof y.data?.src==`string`?y.data.src:void 0,x=typeof y.data?.path==`string`?y.data.path:void 0,S=y.data?.deduped===!0,C=b??x??o;return W3([`Uploaded asset to ${s}${S?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: ![${o}](${C})`].join(`
2157
- `),{asset:{ok:!0,...b?{src:b}:{},...x?{path:x}:{},...S?{deduped:S}:{}}})}async function XCt(e,t,n,r,i){let a=r.identityRef?.current,o=e.description!==void 0,s=e.files??[];if(!o&&s.length===0)return $("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!o)return $('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);let c=[];for(let e of s){let t=p7(e.path);if(!t.ok)return $(`Error: ${t.error}`,!0);c.push({...e,path:t.path})}let l=[],u=null;if(o&&(u=await dbt(n,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:a,lockDir:i}),u.isError))return u;for(let r of c){let i=await pbt(n,{name:e.name,scope:e.scope,path:r.path,content:r.content,summary:t,identity:a}),o=i.structuredContent;if(i.isError)l.push({path:r.path,ok:!1,error:i.content[0]?.text??`write failed`});else{let e=o?.skill?.file??{};l.push({path:r.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let d=l.filter(e=>e.ok).length,f=l.some(e=>!e.ok),p=u?.structuredContent??{},m=p.skill??{ok:!0},{text:h,...g}=p,_={...g,skill:{...m,...s.length>0?{files:l}:{}}},v=[];if(o&&u&&v.push(u.content[0]?.text??``),s.length>0){v.push(`${d}/${s.length} bundle file(s) written.`);for(let e of l)v.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return W3(v.filter(Boolean).join(`
2156
+ `),{folder:{ok:!0,path:e.path}})}async function JCt(e,t,n,r){let i=l7(e.path);if(!i.ok)return $(`Error: ${i.error}`,!0);let{folder:a,name:o}=i;if(!n)return $(G3,!0);let s=await a6(n,`/api/template`,{folder:a,name:o,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...P3(r.identityRef?.current)});if(!s.ok)return $(H3(s,`Any body offset refers to the full submitted template.content.`),!0);let c=s.created===!0,l=typeof s.path==`string`?s.path:void 0;return W3(`${c?`Created`:`Updated`} template "${o}" in ${a||`(root)`}${l?` (${l})`:``}.`,{template:{ok:!0,path:l,created:c}})}async function YCt(e,t,n,r){if(!n)return $(G3,!0);if(e.content===void 0==(e.source===void 0))return $("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let i;try{i=e.content===void 0?K(W(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return $(`Error: could not read asset bytes: ${e.message}`,!0)}if(i.byteLength===0)return $(`Error: asset is empty (0 bytes).`,!0);let{folder:a,name:o}=obt(e.path),s=a?`${a}/${o}`:o,c=r.identityRef?.current,l=new URLSearchParams;c?.connectionId&&l.set(`agentId`,c.connectionId),c?.displayName&&l.set(`agentName`,c.displayName);let u=l.toString(),d=new FormData;d.append(`parentDocName`,s),a&&d.append(`placement`,`parent-dir`),d.append(`file`,new Blob([new Uint8Array(i)]),o);let f=`/api/upload${u?`?${u}`:``}`,p=r.localApi,m=null;if(p)try{let e=new Request(`http://localhost/api/upload`,{method:`POST`,body:d}),t=e.headers.get(`content-type`)??`multipart/form-data`;m={body:new Uint8Array(await e.arrayBuffer()),contentType:t}}catch(e){return $(`Error: upload request failed: ${e.message}`,!0)}let h,g;try{let e=p&&m?await p(`POST`,f,m):null;if(e!==null)h=e.status,g=e.bodyText;else{let e=await fetch(`${n}${f}`,{method:`POST`,body:d,signal:AbortSignal.timeout(3e4)});h=e.status,g=await e.text()}}catch(e){return $(`Error: ${e6(e)}`,!0)}let _=h>=200&&h<=299,v;try{v=JSON.parse(g)}catch(e){let t=e instanceof Error?e.message:String(e);return $(_?`Error: Server returned 2xx response with non-JSON body: ${t}`:`Error: Server returned HTTP ${h} with non-JSON body: ${t}`,!0)}let y=_?{ok:!0,status:h,data:v??{}}:{ok:!1,status:h,error:v&&(typeof v.title==`string`?v.title:v.error)||`Upload failed (HTTP ${h}).`};if(!y.ok)return $(`Error: ${y.error}`,!0);let b=ire.safeParse(y.data);if(!b.success)return $(`Error: Server returned 2xx response with malformed upload body: ${Cee(b.error)}`,!0);let{src:x,path:S,deduped:C}=b.data;return W3([`Uploaded asset${S?` to ${S}`:``}${C?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: ![${o}](${x})`].join(`
2157
+ `),{asset:{ok:!0,src:x,...S?{path:S}:{},...C?{deduped:C}:{}}})}async function XCt(e,t,n,r,i){let a=r.identityRef?.current,o=e.description!==void 0,s=e.files??[];if(!o&&s.length===0)return $("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!o)return $('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);let c=[];for(let e of s){let t=p7(e.path);if(!t.ok)return $(`Error: ${t.error}`,!0);c.push({...e,path:t.path})}let l=[],u=null;if(o&&(u=await dbt(n,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:a,lockDir:i}),u.isError))return u;for(let r of c){let i=await pbt(n,{name:e.name,scope:e.scope,path:r.path,content:r.content,summary:t,identity:a}),o=i.structuredContent;if(i.isError)l.push({path:r.path,ok:!1,error:i.content[0]?.text??`write failed`});else{let e=o?.skill?.file??{};l.push({path:r.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let d=l.filter(e=>e.ok).length,f=l.some(e=>!e.ok),p=u?.structuredContent??{},m=p.skill??{ok:!0},{text:h,...g}=p,_={...g,skill:{...m,...s.length>0?{files:l}:{}}},v=[];if(o&&u&&v.push(u.content[0]?.text??``),s.length>0){v.push(`${d}/${s.length} bundle file(s) written.`);for(let e of l)v.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return W3(v.filter(Boolean).join(`
2158
2158
  `),_,f)}async function ZCt(e,t,n,r,i,a,o){let s=[];for(let a of e)s.push(await GCt(a,t,n,r,i));let c=s.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=s7(e.docName,{lockDir:a}),n=Z5(e.raw.warnings),r=Q5(e.raw.brokenLinks),i=$5(e.raw.brokenLinkSuppression);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...n?{warnings:n}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:r,...i?{brokenLinkSuppression:i}:{}}}),l=c.filter(e=>e.ok).length,u=l===c.length,d=e.map((e,t)=>{let n=s[t];if(!n?.ok)return`Failed ${e.path}: ${n?.error??`unknown error`}`;if(zCt(n.position,e.content))return`No change to ${e.path} — empty ${n.position}, document unchanged.`;let r=c[t],i=[n.createdByPosition?RCt(n.docName,n.createdByPosition):`Wrote ${e.path} (${n.position}).`];if(r?.ok&&r.warnings&&i.push(...Myt(r.warnings)),r?.ok){let e=byt(r.brokenLinks);e&&i.push(e),r.brokenLinkSuppression&&i.push(Xrt(r.brokenLinkSuppression))}return n.ok&&n.templateHint&&i.push(`ℹ ${n.templateHint.length} template${n.templateHint.length===1?``:`s`} available here (pass \`template\`).`),i.join(` `)}),f=e.flatMap((e,t)=>{let n=s[t];if(!n?.ok)return[];let r=LCt(n.position,e.content);return[...r?[r]:[],...n.extensionNote?[n.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),p=[`${l}/${c.length} written.`,...d,...f].join(`
2159
2159
  `),m={documents:c},h=s.find(e=>e.ok);return h&&h.raw.systemSubscriberCount===0&&(m.warning=r7(s7(h.docName,{lockDir:a}),o)),W3(p,m,!u)}async function QCt(e,t,n,r,i,a,o){let s=await GCt(e,t,n,r,i);if(!s.ok)return $(`Error: ${s.error}`,!0);let c=s.raw,l=s7(s.docName,{lockDir:a}),u=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,d=Array.isArray(c.hints)?c.hints:void 0,f=c.summary&&typeof c.summary==`object`?c.summary:void 0,p=typeof f?.hint==`string`?f.hint:void 0,m=Z5(c.warnings),h=Q5(c.brokenLinks),g=$5(c.brokenLinkSuppression),_=zCt(s.position,e.content),v=[s.createdByPosition?RCt(s.docName,s.createdByPosition):_??(s.fromTemplate===void 0?`Written successfully (${s.position}).`:`Written successfully (instantiated from template "${s.fromTemplate}").`)],y=LCt(s.position,e.content);if(y&&v.push(y),s.extensionNote&&v.push(s.extensionNote),u&&!l&&v.push(Zyt),p&&v.push(p),d)for(let e of d)e.message&&v.push(e.message);m&&v.push(...e7(m)),v.push(...yyt(h)),g&&v.push(Yrt(g)),s.templateHint&&v.push(KCt(s.templateHint));let b=v.join(`
2160
- `),x={brokenLinks:h};return g&&(x.brokenLinkSuppression=g),d&&(x.hints=d),f&&(x.summary=f),m&&(x.warnings=m),s.templateHint&&(x.templateHint=s.templateHint),W3(b,Mct(l,u?r7(l,o):void 0,x))}function $Ct(e,t){let n={path:R().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:R().optional().describe("The full Markdown body. C0 controls allow only TAB, LF and CR; remove others or use printable escapes. Mutually exclusive with `template`."),extension:abt.optional(),template:R().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:c7.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:ibt.optional()};e.registerTool(`write`,{description:ICt,inputSchema:{document:B(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:B({path:R().describe(`Folder path. Example: "meetings".`),frontmatter:c7.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:B({path:R().describe(sbt),content:R().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),frontmatter:B({title:R().min(1).describe(`Required — the label shown when an agent picks this template.`),description:R().optional().describe(`Optional — shown beside the title in the template menu.`),tags:z(R()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:B({name:R().describe(u7),description:R().optional().describe(`${cbt} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:R().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),files:z(B({path:R().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:R().describe(`Full text of the bundle file, including any frontmatter. For .md/.mdx paths, C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:d7.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:B({path:R().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:R().optional().describe(`Base64 of the binary. Use for small files.`),source:R().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:z(B({...n,summary:I3})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:I3,cwd:R().optional().describe(F3)},outputSchema:U3({document:B({hints:B3.optional().describe(`Server-provided write hints, when any.`),...jct}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet."),folder:B({ok:ao(),path:R(),frontmatterError:R().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:B({ok:ao(),path:R(),created:ao().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:B({ok:ao(),path:R().optional(),created:ao().optional().describe(`true if created, false if an existing skill was overwritten.`),files:B3.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`."),warnings:z(R()).optional().describe(`Non-fatal authoring warnings for the SKILL.md that was written. ${l6}`),warningCodes:z(Si(wi)).optional().describe(`${c6} ${u6}`)}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:B({ok:ao(),src:R().optional().describe(`The reference src to embed in a doc.`),path:R().optional(),deduped:ao().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:B3.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy)."),previewUrl:L3.optional(),previewUrlSource:R3,warning:Dct})},async e=>{let n=await J3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=zJ(r),s=LJ(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=m7(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?$(`Error: ${n}`,!0):a?ZCt(e.documents,r,s,a,t,o,c):$(G3,!0)}let l=m7(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?$(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?YCt(e.asset,r,a,t):XCt(e.skill,e.summary,a,t,o):JCt(e.template,e.summary,a,t):qCt(e.folder,e.summary,a,t):a?QCt({...e.document,summary:e.summary},r,s,a,t,o,c):$(G3,!0)})}function ewt(e,t){let n=t.logger,r=vyt(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(q5()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(q5()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};cSt(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),hCt(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),kSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),zSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),zyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),$Ct(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),zbt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),Ebt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),XSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),ESt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),SSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),ySt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),FCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Hyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),iCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),nCt(r,{resolveCwd:i(`palette`),config:t.config}),qyt(r,{config:t.config,resolveCwd:i(`config`)}),gSt(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:Zvt()}:{}}),CCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function N7(e){return Array.isArray(e)?e[0]:e}function P7(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function twt(e,t,n,r){let i=e.config,a=new KB({name:Ia,version:JZ});hvt(a);let o=n??Ec(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Z4e(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Ae(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return ewt(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=N3(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),mvt(a),{server:a,transport:t}}function nwt(e){let t=new Map,n=e.sessionTtlMs??18e5,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=N7(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){P7(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){P7(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),P7(o,503,`Too many active MCP sessions`);return}let c=N7(n.headers[Y4e]),l=qW(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=N7(n.headers[X4e])===`1`,d=new Kze({sessionIdGenerator:()=>Ec(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=twt(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const F7=1048576;function rwt(e){if(!e)return null;try{return qW(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function I7(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function iwt(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=I7(t.searchParams.get(`displayName`)),r=I7(t.searchParams.get(`clientName`)),i=I7(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function awt(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??T$({}),l=e.keepaliveGraceMs??1e4,u=new qie.default({noServer:!0,maxPayload:F7}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>E$(e.socket.remoteAddress,c)&&D$(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{oK(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!O$(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=rwt(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=iwt(e.url);if(t)try{let e=Un(t.clientName);a.setPresence(JW(s),{displayName:t.displayName,icon:e,color:no[e]??Ve(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now(),docTs:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(JW(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(JW(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{oK(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),D7e(e,{}),k$(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),A$(n,`collab-upgrade`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!O$(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>U5e(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!O$(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>F7){o=!0,uYe(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:F7},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(uYe(),n.warn({event:`collab-message-too-large`,limit:F7},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):oK(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}function owt({contentAssetMiddleware:e,reactShellMiddleware:t,ephemeral:n,ingressPolicy:r,log:i}){return(a,o)=>{let s=a.url?.split(`?`)[0];if(!z6(a,o,r,`mcp-mount`,i))return;let c=(e,t,n)=>{if(e===void 0){n();return}try{e(a,o,()=>{o.writableEnded||o.headersSent||n()})}catch(e){i.error({err:e},`Unhandled ${t} middleware error`),!o.writableEnded&&!o.headersSent?X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):o.writableEnded||o.end()}},l=t=>{if(n===!0&&e!==void 0){if(!E$(a.socket.remoteAddress,r)){X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!D$(a.headers.host,r)){X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:w$});return}}c(e,`content-asset`,t)},u=e=>c(t,`react-shell`,e),d=()=>{o.writableEnded||o.headersSent||X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${t===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${s??`/`}`})};if(t!==void 0&&(s?.startsWith(`/assets/`)||s?.startsWith(`/excalidraw-assets/`))){u(()=>l(d));return}if(e!==void 0||t!==void 0){l(()=>u(d));return}X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${s??`/`}`})}}const swt={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function cwt(e,t,n){return(r,i)=>{let a=r.headers.origin,o=Array.isArray(r.headers[`mcp-session-id`])?r.headers[`mcp-session-id`][0]:r.headers[`mcp-session-id`];if(!E$(r.socket.remoteAddress,t)){X(i,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!D$(r.headers.host,t)){X(i,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:w$});return}let s=w7e(a,r.method,t);if(!s.admitted){X(i,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`,detail:s.detail});return}if(a!==void 0&&i.setHeader(`Vary`,`Origin`),s.corsGrant){a!==void 0&&i.setHeader(`Access-Control-Allow-Origin`,a);for(let[e,t]of Object.entries(swt))i.setHeader(e,t)}if(r.method===`OPTIONS`){i.writeHead(204),i.end();return}e.handle(r,i).catch(e=>{n.error({err:e,sessionId:o},`Unhandled MCP HTTP error`),!i.writableEnded&&!i.headersSent?X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):i.writableEnded||i.end()})}}function lwt(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??T$({}),p=awt({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let r=e.url?.split(`?`)[0];z6(e,t,f,`mcp-mount`,i)&&n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||X(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${r}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(k$(e,f)&&(i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),A$(i,`ws-upgrade`)),t.destroy())},{requestListener:g}=Wut({health:e.health,nativeApi:e.nativeApi,mcpDispatch:r===void 0?void 0:cwt(r,f,i),ingressPolicy:f,legacyDispatch:m,contentDispatch:owt({contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d,ingressPolicy:f,log:i}),log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const uwt=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var dwt=class extends Error{kind;projectDir;constructor(e,t,n){super(uwt,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function fwt(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}const pwt=e=>{let t=sq(e);return t===`ENOENT`||t===`ENOTDIR`},mwt=(e,t)=>e.signature===t.signature&&(!e.racy||e.digest===t.digest),hwt=e=>e.racy?e:{...e,digest:void 0};async function gwt(e){let t;try{t=await Sc(e,{bigint:!0})}catch(e){if(pwt(e))return;throw e}return t.isFile()?t:void 0}async function _wt(e){try{return Tc(`sha256`).update(await vc(e)).digest(`hex`)}catch(e){if(pwt(e))return;throw e}}async function vwt(e,t,n){let r=oot(),i=await gwt(e);if(i===void 0)return;if(!t?.racy&&!M4(i,r))return{size:i.size,signature:j4(i),racy:!1,digest:void 0};if(n())return;let a=await _wt(e);if(a===void 0||n())return;let o=await gwt(e);if(o!==void 0)return{size:o.size,signature:j4(o),racy:M4(o,r),digest:a}}async function L7({listPaths:e,onEvent:t,onError:n}){let r=q(`polled-path-watcher`),i=new Map,a=!1,o=(e,t)=>{if(!a)try{n(e,t)}catch(n){try{r.error({err:e,error:n,path:t},`onError threw while reporting a watcher error`)}catch{}}},s=async t=>{let n=new Set(await e());for(let e of i.keys())n.has(e)||i.delete(e);let r=new Map;return await Promise.all(Array.from(n,async e=>{let n;try{n=await vwt(e,t.get(e),()=>a)}catch(n){let a=sq(n);(!i.has(e)||i.get(e)!==a)&&(i.set(e,a),o(n,e));let s=t.get(e);s&&r.set(e,s);return}i.delete(e),n&&r.set(e,n)})),r},c=await s(new Map),l=new Map,u=e=>{for(let[n,r]of e){let e=c.get(n);e!==void 0&&mwt(e,r)?(l.delete(n),e.racy&&c.set(n,hwt(r))):l.get(n)===r.size?(l.delete(n),c.set(n,hwt(r)),t(e?`change`:`add`,n)):l.set(n,r.size)}for(let n of c.keys())e.has(n)||(c.delete(n),t(`unlink`,n));for(let t of l.keys())e.has(t)||l.delete(t)},d,f=async()=>{try{let e=await s(c);a||u(e)}catch(e){o(e)}},p=()=>{d=setTimeout(()=>{f().finally(()=>{a||p()})},200)};return p(),async()=>{a||(a=!0,clearTimeout(d))}}function R7(e,t){try{return K(e,`utf-8`)}catch(n){return sq(n)!==`ENOENT`&&t.warn({err:n,path:e},`config file baseline read failed; treating it as absent`),null}}async function ywt(e,t){let n=q(`config-file-watcher`),r=V(e);try{MG(r,{recursive:!0})}catch(e){sq(e)!==`EEXIST`&&n.warn({err:e,watchDir:r},`failed to create watch directory; watcher may be inert`)}let i=R7(e,n),a=(r,a=!0)=>{if(r!==e)return;let o;try{o=K(r,`utf-8`)}catch(e){if(sq(e)===`ENOENT`){a&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(o!==i){i=o;try{t(o)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},o=t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)},s=await L7({listPaths:async()=>[e],onEvent:(e,t)=>e===`unlink`?o(t):a(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});return a(e,!1),Object.assign(()=>s(),{resync:()=>{i=R7(e,n)}})}async function bwt(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=q(`config-file-watcher`),r=new Set(e),i=Array.from(new Set(Array.from(r,e=>V(e))));for(let e of i)try{MG(e,{recursive:!0})}catch(t){sq(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let a=new Map,o=()=>{for(let e of r)a.set(e,R7(e,n))};o();let s=(e,i=!0)=>{if(!r.has(e))return;let o;try{o=K(e,`utf-8`)}catch(t){if(sq(t)===`ENOENT`){i&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(o!==a.get(e)){a.set(e,o);try{t(e,o)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},c=e=>{r.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)},l=await L7({listPaths:async()=>Array.from(r),onEvent:(e,t)=>e===`unlink`?c(t):s(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});for(let e of r)s(e,!1);return Object.assign(()=>l(),{resync:o})}const z7=q(`config-persistence`);function B7(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let xwt=null;function Swt(){return xwt||=cG().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),xwt}function Cwt(e){if(pn(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)Zte(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function V7(e,t){if(e===`__config__/project`)return aC(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return aC(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return aC(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return W(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let H7=null;function wwt(){return H7===null&&(H7=(0,Wc.stringify)(ha.parse({}))),H7}function Twt(e){if(e.length===0)return{ok:!0};let t=e.split(`
2160
+ `),x={brokenLinks:h};return g&&(x.brokenLinkSuppression=g),d&&(x.hints=d),f&&(x.summary=f),m&&(x.warnings=m),s.templateHint&&(x.templateHint=s.templateHint),W3(b,Mct(l,u?r7(l,o):void 0,x))}function $Ct(e,t){let n={path:R().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:R().optional().describe("The full Markdown body. C0 controls allow only TAB, LF and CR; remove others or use printable escapes. Mutually exclusive with `template`."),extension:abt.optional(),template:R().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:c7.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:ibt.optional()};e.registerTool(`write`,{description:ICt,inputSchema:{document:B(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:B({path:R().describe(`Folder path. Example: "meetings".`),frontmatter:c7.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:B({path:R().describe(sbt),content:R().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),frontmatter:B({title:R().min(1).describe(`Required — the label shown when an agent picks this template.`),description:R().optional().describe(`Optional — shown beside the title in the template menu.`),tags:z(R()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:B({name:R().describe(u7),description:R().optional().describe(`${cbt} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:R().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),files:z(B({path:R().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:R().describe(`Full text of the bundle file, including any frontmatter. For .md/.mdx paths, C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:d7.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:B({path:R().describe('Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png". A bare file name (no folder) goes to the attachment folder (`content.attachmentFolderPath`; by default the content root).'),content:R().optional().describe(`Base64 of the binary. Use for small files.`),source:R().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:z(B({...n,summary:I3})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:I3,cwd:R().optional().describe(F3)},outputSchema:U3({document:B({hints:B3.optional().describe(`Server-provided write hints, when any.`),...jct}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet."),folder:B({ok:ao(),path:R(),frontmatterError:R().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:B({ok:ao(),path:R(),created:ao().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:B({ok:ao(),path:R().optional(),created:ao().optional().describe(`true if created, false if an existing skill was overwritten.`),files:B3.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`."),warnings:z(R()).optional().describe(`Non-fatal authoring warnings for the SKILL.md that was written. ${l6}`),warningCodes:z(Si(wi)).optional().describe(`${c6} ${u6}`)}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:B({ok:ao(),src:R().describe(`The reference src to embed in a doc.`),path:R().optional().describe("Content-root-relative path the server reports holding the asset (the existing file when `deduped`). Absent when the server reports none."),deduped:ao().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:B3.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy)."),previewUrl:L3.optional(),previewUrlSource:R3,warning:Dct})},async e=>{let n=await J3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=zJ(r),s=LJ(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=m7(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?$(`Error: ${n}`,!0):a?ZCt(e.documents,r,s,a,t,o,c):$(G3,!0)}let l=m7(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?$(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?YCt(e.asset,r,a,t):XCt(e.skill,e.summary,a,t,o):JCt(e.template,e.summary,a,t):qCt(e.folder,e.summary,a,t):a?QCt({...e.document,summary:e.summary},r,s,a,t,o,c):$(G3,!0)})}function ewt(e,t){let n=t.logger,r=vyt(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(q5()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(q5()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};cSt(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),hCt(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),kSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),zSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),zyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),$Ct(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),zbt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),Ebt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),XSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),ESt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),SSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),ySt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),FCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Hyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),iCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),nCt(r,{resolveCwd:i(`palette`),config:t.config}),qyt(r,{config:t.config,resolveCwd:i(`config`)}),gSt(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:Zvt()}:{}}),CCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function N7(e){return Array.isArray(e)?e[0]:e}function P7(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function twt(e,t,n,r){let i=e.config,a=new KB({name:Ia,version:JZ});hvt(a);let o=n??Ec(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Z4e(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Ae(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return ewt(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=N3(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),mvt(a),{server:a,transport:t}}function nwt(e){let t=new Map,n=e.sessionTtlMs??18e5,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=N7(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){P7(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){P7(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),P7(o,503,`Too many active MCP sessions`);return}let c=N7(n.headers[Y4e]),l=qW(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=N7(n.headers[X4e])===`1`,d=new Kze({sessionIdGenerator:()=>Ec(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=twt(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const F7=1048576;function rwt(e){if(!e)return null;try{return qW(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function I7(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function iwt(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=I7(t.searchParams.get(`displayName`)),r=I7(t.searchParams.get(`clientName`)),i=I7(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function awt(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??T$({}),l=e.keepaliveGraceMs??1e4,u=new qie.default({noServer:!0,maxPayload:F7}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>E$(e.socket.remoteAddress,c)&&D$(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{oK(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!O$(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=rwt(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=iwt(e.url);if(t)try{let e=Un(t.clientName);a.setPresence(JW(s),{displayName:t.displayName,icon:e,color:no[e]??Ve(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now(),docTs:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(JW(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(JW(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{oK(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),D7e(e,{}),k$(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),A$(n,`collab-upgrade`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!O$(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>U5e(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!O$(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>F7){o=!0,uYe(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:F7},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(uYe(),n.warn({event:`collab-message-too-large`,limit:F7},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):oK(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}function owt({contentAssetMiddleware:e,reactShellMiddleware:t,ephemeral:n,ingressPolicy:r,log:i}){return(a,o)=>{let s=a.url?.split(`?`)[0];if(!z6(a,o,r,`mcp-mount`,i))return;let c=(e,t,n)=>{if(e===void 0){n();return}try{e(a,o,()=>{o.writableEnded||o.headersSent||n()})}catch(e){i.error({err:e},`Unhandled ${t} middleware error`),!o.writableEnded&&!o.headersSent?X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):o.writableEnded||o.end()}},l=t=>{if(n===!0&&e!==void 0){if(!E$(a.socket.remoteAddress,r)){X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!D$(a.headers.host,r)){X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:w$});return}}c(e,`content-asset`,t)},u=e=>c(t,`react-shell`,e),d=()=>{o.writableEnded||o.headersSent||X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${t===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${s??`/`}`})};if(t!==void 0&&(s?.startsWith(`/assets/`)||s?.startsWith(`/excalidraw-assets/`))){u(()=>l(d));return}if(e!==void 0||t!==void 0){l(()=>u(d));return}X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${s??`/`}`})}}const swt={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function cwt(e,t,n){return(r,i)=>{let a=r.headers.origin,o=Array.isArray(r.headers[`mcp-session-id`])?r.headers[`mcp-session-id`][0]:r.headers[`mcp-session-id`];if(!E$(r.socket.remoteAddress,t)){X(i,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!D$(r.headers.host,t)){X(i,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:w$});return}let s=w7e(a,r.method,t);if(!s.admitted){X(i,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`,detail:s.detail});return}if(a!==void 0&&i.setHeader(`Vary`,`Origin`),s.corsGrant){a!==void 0&&i.setHeader(`Access-Control-Allow-Origin`,a);for(let[e,t]of Object.entries(swt))i.setHeader(e,t)}if(r.method===`OPTIONS`){i.writeHead(204),i.end();return}e.handle(r,i).catch(e=>{n.error({err:e,sessionId:o},`Unhandled MCP HTTP error`),!i.writableEnded&&!i.headersSent?X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):i.writableEnded||i.end()})}}function lwt(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??T$({}),p=awt({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let r=e.url?.split(`?`)[0];z6(e,t,f,`mcp-mount`,i)&&n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||X(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${r}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(k$(e,f)&&(i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),A$(i,`ws-upgrade`)),t.destroy())},{requestListener:g}=Wut({health:e.health,nativeApi:e.nativeApi,mcpDispatch:r===void 0?void 0:cwt(r,f,i),ingressPolicy:f,legacyDispatch:m,contentDispatch:owt({contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d,ingressPolicy:f,log:i}),log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const uwt=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var dwt=class extends Error{kind;projectDir;constructor(e,t,n){super(uwt,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function fwt(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}const pwt=e=>{let t=sq(e);return t===`ENOENT`||t===`ENOTDIR`},mwt=(e,t)=>e.signature===t.signature&&(!e.racy||e.digest===t.digest),hwt=e=>e.racy?e:{...e,digest:void 0};async function gwt(e){let t;try{t=await Sc(e,{bigint:!0})}catch(e){if(pwt(e))return;throw e}return t.isFile()?t:void 0}async function _wt(e){try{return Tc(`sha256`).update(await vc(e)).digest(`hex`)}catch(e){if(pwt(e))return;throw e}}async function vwt(e,t,n){let r=oot(),i=await gwt(e);if(i===void 0)return;if(!t?.racy&&!M4(i,r))return{size:i.size,signature:j4(i),racy:!1,digest:void 0};if(n())return;let a=await _wt(e);if(a===void 0||n())return;let o=await gwt(e);if(o!==void 0)return{size:o.size,signature:j4(o),racy:M4(o,r),digest:a}}async function L7({listPaths:e,onEvent:t,onError:n}){let r=q(`polled-path-watcher`),i=new Map,a=!1,o=(e,t)=>{if(!a)try{n(e,t)}catch(n){try{r.error({err:e,error:n,path:t},`onError threw while reporting a watcher error`)}catch{}}},s=async t=>{let n=new Set(await e());for(let e of i.keys())n.has(e)||i.delete(e);let r=new Map;return await Promise.all(Array.from(n,async e=>{let n;try{n=await vwt(e,t.get(e),()=>a)}catch(n){let a=sq(n);(!i.has(e)||i.get(e)!==a)&&(i.set(e,a),o(n,e));let s=t.get(e);s&&r.set(e,s);return}i.delete(e),n&&r.set(e,n)})),r},c=await s(new Map),l=new Map,u=e=>{for(let[n,r]of e){let e=c.get(n);e!==void 0&&mwt(e,r)?(l.delete(n),e.racy&&c.set(n,hwt(r))):l.get(n)===r.size?(l.delete(n),c.set(n,hwt(r)),t(e?`change`:`add`,n)):l.set(n,r.size)}for(let n of c.keys())e.has(n)||(c.delete(n),t(`unlink`,n));for(let t of l.keys())e.has(t)||l.delete(t)},d,f=async()=>{try{let e=await s(c);a||u(e)}catch(e){o(e)}},p=()=>{d=setTimeout(()=>{f().finally(()=>{a||p()})},200)};return p(),async()=>{a||(a=!0,clearTimeout(d))}}function R7(e,t){try{return K(e,`utf-8`)}catch(n){return sq(n)!==`ENOENT`&&t.warn({err:n,path:e},`config file baseline read failed; treating it as absent`),null}}async function ywt(e,t){let n=q(`config-file-watcher`),r=V(e);try{MG(r,{recursive:!0})}catch(e){sq(e)!==`EEXIST`&&n.warn({err:e,watchDir:r},`failed to create watch directory; watcher may be inert`)}let i=R7(e,n),a=(r,a=!0)=>{if(r!==e)return;let o;try{o=K(r,`utf-8`)}catch(e){if(sq(e)===`ENOENT`){a&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(o!==i){i=o;try{t(o)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},o=t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)},s=await L7({listPaths:async()=>[e],onEvent:(e,t)=>e===`unlink`?o(t):a(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});return a(e,!1),Object.assign(()=>s(),{resync:()=>{i=R7(e,n)}})}async function bwt(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=q(`config-file-watcher`),r=new Set(e),i=Array.from(new Set(Array.from(r,e=>V(e))));for(let e of i)try{MG(e,{recursive:!0})}catch(t){sq(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let a=new Map,o=()=>{for(let e of r)a.set(e,R7(e,n))};o();let s=(e,i=!0)=>{if(!r.has(e))return;let o;try{o=K(e,`utf-8`)}catch(t){if(sq(t)===`ENOENT`){i&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(o!==a.get(e)){a.set(e,o);try{t(e,o)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},c=e=>{r.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)},l=await L7({listPaths:async()=>Array.from(r),onEvent:(e,t)=>e===`unlink`?c(t):s(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});for(let e of r)s(e,!1);return Object.assign(()=>l(),{resync:o})}const z7=q(`config-persistence`);function B7(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let xwt=null;function Swt(){return xwt||=cG().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),xwt}function Cwt(e){if(pn(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)Zte(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function V7(e,t){if(e===`__config__/project`)return aC(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return aC(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return aC(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return W(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let H7=null;function wwt(){return H7===null&&(H7=(0,Wc.stringify)(ha.parse({}))),H7}function Twt(e){if(e.length===0)return{ok:!0};let t=e.split(`
2161
2161
  `);for(let e=0;e<t.length;e++){let n=t[e]??``;if(n.length!==0&&/^\s+$/.test(n))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function U7(e,t){return e===`__config__/okignore`?Twt(t):Dwt(t)}function Ewt(e){return e===`__config__/okignore`?``:wwt()}function Dwt(e){let t=(0,Wc.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let n=t.toJSON()??{},r=ha.safeParse(n);return r.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:r.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function Owt(e,t,n){let r=e.getText(`source`);if(r.length>0)return;let i=V7(t,n),a=``;if(G(i))try{a=K(i,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);z7.warn({path:i,err:e},`[config-persistence] Could not read ${i}: ${t}. Seeding with empty content.`),a=``}let o=U7(t,a);!o.ok&&a.length>0&&z7.warn({docName:t,path:i},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{a.length>0&&r.insert(0,a)},C1),o.ok&&a.length>0?n.lkgCache.set(t,a):n.lkgCache.set(t,Ewt(t))}async function kwt(e,t){await kG(V(e),{recursive:!0});let n=tC(e);try{await TG(n,t,`utf-8`),await OG(n,e)}catch(e){try{FG(n)}catch{}throw e}}async function Awt(e,t,n,r){return Ca(`config.persist`,{"config.scope":B7(t),"config.transport":`fs`},async i=>{let a=await Mwt(e,t,n,r);return i.setAttribute(`config.outcome`,jwt(a)),a})}function jwt(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function Mwt(e,t,n,r){if(r.ephemeral&&t===`__config__/okignore`||n===C1)return`no-op`;let i=e.getText(`source`),a=i.toString(),o=r.lkgCache.get(t);if(a.length===0&&(t!==`__config__/okignore`||o===void 0||o===``)||o!==void 0&&a===o)return`no-op`;let s=B7(t),c=Ma(`config.validate`,{"config.scope":s,"config.validation.layer":`L3`},e=>{let n=U7(t,a);return e.setAttribute(`config.outcome`,n.ok?`success`:`rejected`),n.ok||Cwt(n.error),n});if(!c.ok)return await Ca(`config.revert`,{"config.scope":s,"config.outcome":`reverted`},async()=>{let n=o??Ewt(t);e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},C1),o===void 0&&r.lkgCache.set(t,n),t===`__config__/okignore`&&pn(c.error)&&Swt().add(1,{"error.code":c.error.code}),r.onConfigRejected?.(t,c.error)}),`reverted`;let l=V7(t,r);try{await kG(V(l),{recursive:!0})}catch(e){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] could not create parent dir for ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${l}: ${n}`}),`write-failed`}try{return await iC(`${l}.lock`,async()=>{let n=null;try{n=K(l,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] could not read config for reconciliation: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${l}: ${n}`}),`write-failed`}}if(n!==null&&o!==void 0&&n!==o){if(U7(t,n).ok)return e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},cet),r.lkgCache.set(t,n),z7.info({docName:t,path:l},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;z7.warn({docName:t,path:l},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await kwt(l,a)}catch(e){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] write-failed at ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${l}: ${n}`}),`write-failed`}return r.lkgCache.set(t,a),`persisted`},{onWarn:(e,t)=>{z7.warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof rC)return z7.warn({docName:t,path:l,err:e},`[config-persistence] lock timeout at ${l}: ${e.message}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function Nwt(e,t,n){try{FG(V7(t,n))}catch(e){if(e.code!==`ENOENT`)throw e}if(n.lkgCache.delete(t),e===null)return;let r=e.getText(`source`);r.length>0&&e.transact(()=>{r.delete(0,r.length)},C1),Owt(e,t,n)}function Pwt(e,t,n){return n.lkgCache.get(e)===t}function W7(e,t,n,r){if(!e||Pwt(t,n,r))return`no-op`;let i=B7(t),a=Ma(`config.validate`,{"config.scope":i,"config.validation.layer":`L3`},e=>{let r=U7(t,n);return e.setAttribute(`config.outcome`,r.ok?`success`:`rejected`),r.ok||Cwt(r.error),r});if(!a.ok)return t===`__config__/okignore`&&pn(a.error)&&Swt().add(1,{"error.code":a.error.code}),r.onConfigRejected?.(t,a.error),`rejected`;let o=e.getText(`source`);return e.transact(()=>{o.length>0&&o.delete(0,o.length),o.insert(0,n)},cet),r.lkgCache.set(t,n),`applied`}const Fwt=`Other`,Iwt=`Subdirectories`,G7=`Index`,Lwt=new Set([G7,Fwt,Iwt]),Rwt={control:`generated index metadata contained a Cc control; replaced it with U+FFFD`,"parser-reservation":`generated index metadata contained a parser-reserved private-use code point; replaced it with U+FFFD`};function K7(e){return`${e.path}\0${e.field}`}var zwt=class{contentDir;#e=new Map;constructor(e){this.contentDir=e}update(e,t,n){let r=K7(t),i=`${e}\0${r}`;if(!n){this.#e.delete(i);return}this.#e.has(i)||(this.#e.set(i,r),q(`generated-index`).warn({contentDir:this.contentDir,...t,kind:e},Rwt[e]))}retain(e){for(let[t,n]of this.#e)e.has(n)||this.#e.delete(t)}};function Bwt(e){return new zwt(e)}function Vwt(e,t,n){if(!e)return;let r=new Set;for(let e of t)r.add(K7({path:e.path,field:`title`})),r.add(K7({path:e.path,field:`type`})),e.description!==void 0&&r.add(K7({path:e.path,field:`description`}));for(let e of n)r.add(K7({path:e.directory,field:`folder-label`}));e.retain(r)}function q7(e,t){let n=!1,r=!1,i=Array.from(Uwt(e),e=>/\p{Cc}/u.test(e)?(n=!0,`�`):Rre(e)?(r=!0,`�`):e).join(``);return t.kind===`attributed`&&t.warningScope&&(t.warningScope.update(`control`,t.source,n),t.warningScope.update(`parser-reservation`,t.source,r)),{visible:i,identity:i.normalize(`NFC`),source:i.replace(/[\u0021-\u002f\u003a-\u0040\u005b-\u0060\u007b-\u007e]/g,`\\$&`)}}function Hwt(e,t){let n=q7(e.type??``,{kind:`attributed`,source:{path:e.path,field:`type`},warningScope:t});return n.visible?n:q7(Fwt,{kind:`generator-owned`})}function Uwt(e){return e.replace(/\s+/g,` `).trim()}function J7(e,t){return e<t?-1:+(e>t)}function Y7(e){return Uwt(e).normalize(`NFC`).toLowerCase()}function Wwt(e,t){return J7(Y7(e),Y7(t))||J7(e.normalize(`NFC`),t.normalize(`NFC`))}function Gwt(e,t){return(Wwt(e,t)||J7(e,t))<0}function Kwt(e,t){return J7(Y7(e.title.visible),Y7(t.title.visible))||J7(e.path.replaceAll(`\\`,`/`).normalize(`NFC`),t.path.replaceAll(`\\`,`/`).normalize(`NFC`))}function qwt(e,t){let n=`directory`in e?{path:e.directory,field:`folder-label`}:{path:e.path,field:`title`};return{path:`directory`in e?`${e.directory}/index.md`:e.path,title:q7(e.title,{kind:`attributed`,source:n,warningScope:t}),description:`description`in e&&e.description!==void 0?q7(e.description,{kind:`attributed`,source:{path:e.path,field:`description`},warningScope:t}):void 0}}function Jwt(e,t){let n=t.replaceAll(`\\`,`/`),r=e.replaceAll(`\\`,`/`).replace(/\/+$/,``);if(r===``)return n;let i=`${r}/`;return n.startsWith(i)?n.slice(i.length):n}function Ywt(e){let t=e.replaceAll(`\\`,`/`);return`./${oo(t)}`}function Xwt(e,t){let n=e.normalize(`NFC`);return t.resolve(n)===e?n:e}function Zwt(e,t,n){let r=Xwt(Jwt(t,e.path),n),i=`* [${e.title.source}](${Ywt(r)})`;return e.description?.source?`${i} - ${e.description.source}`:i}function Qwt(e,t,n){return e.slice().sort(Kwt).map(e=>Zwt(e,t,n)).join(`
2162
2162
  `)}function $wt(e,t){let n=t.directory??``,r=t.subdirectories??[],i=t.warningScope,a=q7(G7,{kind:`generator-owned`}).identity,o=new Map,s=ga(`document`),c=e=>{let t=e.identity,n=Lwt.has(e.visible),r=o.get(t);if(!r){let r={heading:e,pinned:n,links:[]};return o.set(t,r),r.links}return n&&!r.pinned?(r.heading=e,r.pinned=!0):!n&&!r.pinned&&Gwt(e.visible,r.heading.visible)&&(r.heading=e),r.links},l=e=>(s.add(Jwt(n,e.path)),e);for(let t of e)c(Hwt(t,i)).push(l(qwt(t,i)));r.length>0&&c(q7(Iwt,{kind:`generator-owned`})).push(...r.map(e=>l(qwt(e,i))));let u=[...o].filter(([e])=>e!==a).sort(([,e],[,t])=>Wwt(e.heading.visible,t.heading.visible)).map(([,{heading:e,links:t}])=>`## ${e.source}\n\n${Qwt(t,n,s)}`),d=t.isRoot?`---
2163
2163
  okf_version: "0.2"