@inkeep/open-knowledge 0.83.0-beta.6 → 0.83.0-beta.7

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 (179) hide show
  1. package/dist/assets/skills/project/references/linking.md +1 -1
  2. package/dist/cli.mjs +60 -60
  3. package/dist/constants-CCYsBRvI.mjs +1 -0
  4. package/dist/dist-DMhyZWXW.mjs +2198 -0
  5. package/dist/{dist-ByQ8IZXo.mjs → dist-ObUBLmuL.mjs} +1 -1
  6. package/dist/index.d.mts +7 -0
  7. package/dist/index.mjs +236 -234
  8. package/dist/{init-C5n0LZMn.mjs → init-B4K69pZS.mjs} +36 -36
  9. package/dist/init-DORmPVEO.mjs +1 -0
  10. package/dist/{launch-json-removal-BE6cJksG.mjs → launch-json-removal-CT0i-3-W.mjs} +1 -1
  11. package/dist/loader-BQnA36qb.mjs +1 -0
  12. package/dist/{loader-DOvCHCV-.mjs → loader-DZHqBHXr.mjs} +1 -1
  13. package/dist/{md-manager-BGnqyqi1-DsBy1Dky.mjs → md-manager-BGnqyqi1-B1QSgyMJ.mjs} +158 -156
  14. package/dist/{open-browser-CJogphTe.mjs → open-browser-B-7x1MTL.mjs} +1 -1
  15. package/dist/parse-worker.mjs +1 -1
  16. package/dist/preview-BWmm6t1q.mjs +1 -0
  17. package/dist/{preview-BDgV2eEH.mjs → preview-BdmlMCtY.mjs} +1 -1
  18. package/dist/public/assets/{AccountSection-BpY8fXau.js → AccountSection-DJh9iLbq.js} +1 -1
  19. package/dist/public/assets/{ActivityModeContent-B7SYD_oX.js → ActivityModeContent-BAm_Sv3o.js} +1 -1
  20. package/dist/public/assets/{AddPropertiesButton-VyqVtzIN.js → AddPropertiesButton-B1mRaQFw.js} +2 -2
  21. package/dist/public/assets/{AgentConnectionsSection-CJhM0Oqw.js → AgentConnectionsSection-D_gmSJG4.js} +1 -1
  22. package/dist/public/assets/{AgentDiffPane-DAIaj_6D.js → AgentDiffPane-rX7T_Ooo.js} +1 -1
  23. package/dist/public/assets/{AttachmentsSection-DL8roP-O.js → AttachmentsSection-FLGDe3pX.js} +1 -1
  24. package/dist/public/assets/{AuthModal-DcixDUcD.js → AuthModal-CkHLmy_N.js} +1 -1
  25. package/dist/public/assets/CodeMirrorPropInput-BuFeADVI.js +166 -0
  26. package/dist/public/assets/{ContentRulesSection-h6pHMqD1.js → ContentRulesSection-DZmyRVa0.js} +1 -1
  27. package/dist/public/assets/{DiffViewBoundary-B5VRWFoq.js → DiffViewBoundary-BVzts2c4.js} +1 -1
  28. package/dist/public/assets/DocumentContext-C8ape_2m.js +108 -0
  29. package/dist/public/assets/{EditorModeToggle-rSAArExF.js → EditorModeToggle-DS_xfOtT.js} +1 -1
  30. package/dist/public/assets/{ExcalidrawDocEditor-DiIxuNaj.js → ExcalidrawDocEditor-DWd6a8Sl.js} +1 -1
  31. package/dist/public/assets/FeedbackForm-MbJXUGuy.js +1 -0
  32. package/dist/public/assets/{GraphPanel-ZgCaGJ14.js → GraphPanel-COpuyFxT.js} +1 -1
  33. package/dist/public/assets/{ImageAttachments-ChGavHQ_.js → ImageAttachments-By1ZcRNT.js} +1 -1
  34. package/dist/public/assets/{ImportSkillDialog-lPX3LQOm.js → ImportSkillDialog-C2_Su5XJ.js} +1 -1
  35. package/dist/public/assets/{LinkPreviewsSection-mmAXSLtK.js → LinkPreviewsSection-ChJ4iMSL.js} +1 -1
  36. package/dist/public/assets/{LintConfigEditor-BbhL2owO.js → LintConfigEditor-BbSzjMFm.js} +1 -1
  37. package/dist/public/assets/{LintingSection-CSM0_1QE.js → LintingSection-4HBYSeJr.js} +1 -1
  38. package/dist/public/assets/{ManagedArtifactProperties-YaOwWUAx.js → ManagedArtifactProperties-2ky67bIe.js} +1 -1
  39. package/dist/public/assets/ManagedArtifactProperties-CatYQWAb.js +1 -0
  40. package/dist/public/assets/{MermaidDocEditor-BQetPb3J.js → MermaidDocEditor-CA7gNCDw.js} +1 -1
  41. package/dist/public/assets/{NetworkAccessSection-CJ0RJ37j.js → NetworkAccessSection-OcPnmrqG.js} +1 -1
  42. package/dist/public/assets/{OkignoreSection-B6lKSJGD.js → OkignoreSection-DUIPj4Vl.js} +1 -1
  43. package/dist/public/assets/PageListContext-CYKNvec7.js +1 -0
  44. package/dist/public/assets/{ProjectTemplatesSection-Cf5bgyHk.js → ProjectTemplatesSection-Ctdx9_AL.js} +1 -1
  45. package/dist/public/assets/{PropertyDisplayRow-BxgncotE.js → PropertyDisplayRow-BvC-5Aoc.js} +1 -1
  46. package/dist/public/assets/{PublishToGitHubDialog-BjLmDxVs.js → PublishToGitHubDialog-BAs3Rgt6.js} +1 -1
  47. package/dist/public/assets/{RegisteredAgentIcon-jysj1Acv.js → RegisteredAgentIcon-Begcc-nC.js} +1 -1
  48. package/dist/public/assets/{ReportBugDialogBody-CW-yLP7E.js → ReportBugDialogBody-CPjEs_zr.js} +1 -1
  49. package/dist/public/assets/{ReportBugMenuTrigger-D2RpbMHk.js → ReportBugMenuTrigger-DwuaKFu1.js} +1 -1
  50. package/dist/public/assets/{SchemaConfigEditor-CL13boF8.js → SchemaConfigEditor-_iycEDNg.js} +1 -1
  51. package/dist/public/assets/{SearchSection-D6cO9U0B.js → SearchSection-BXFLBgQF.js} +1 -1
  52. package/dist/public/assets/{SessionsHost-BH4nUjR2.js → SessionsHost-YR8a-CBs.js} +2 -2
  53. package/dist/public/assets/{SettingsDialogBody-DOlLSJng.js → SettingsDialogBody-FXTDyHIp.js} +2 -2
  54. package/dist/public/assets/{ShareReceiveMissDialog-C4IgyZWj.js → ShareReceiveMissDialog-D0feG-ij.js} +1 -1
  55. package/dist/public/assets/{SkillCostValue-Bgy3wkjV.js → SkillCostValue-Bajv3P86.js} +1 -1
  56. package/dist/public/assets/{SkillForkDialog-CwCSC6Z0.js → SkillForkDialog-BKGY1iRx.js} +1 -1
  57. package/dist/public/assets/{SkillInstallMenu-BIs2wAUZ.js → SkillInstallMenu-CuOKJ4_n.js} +1 -1
  58. package/dist/public/assets/{SkillOriginInline-Dr1zcAGa.js → SkillOriginInline-BrUb4Fgy.js} +1 -1
  59. package/dist/public/assets/{SkillToolbarControls-CnDExhdQ.js → SkillToolbarControls-BOtPYfa8.js} +1 -1
  60. package/dist/public/assets/{SkillsManagerSection-CiaThXM_.js → SkillsManagerSection-dqXRCM3C.js} +1 -1
  61. package/dist/public/assets/{SlidesToolbarControls-BpGxFSJu.js → SlidesToolbarControls-D-0pa5F-.js} +1 -1
  62. package/dist/public/assets/{SourceEditor-3U1rZw1J.js → SourceEditor-ZhZtt3fQ.js} +1 -1
  63. package/dist/public/assets/{SpellingSettings-BAFQbL_s.js → SpellingSettings-DaGy2fT9.js} +1 -1
  64. package/dist/public/assets/{SyncSection-Ciu87ehb.js → SyncSection-B17cmijr.js} +1 -1
  65. package/dist/public/assets/{SyncStatusBadge-CJXgXQeb.js → SyncStatusBadge-DckHbstF.js} +1 -1
  66. package/dist/public/assets/{TemplateRow-Bj4hpJ-E.js → TemplateRow-C8tLmbrb.js} +1 -1
  67. package/dist/public/assets/{TerminalLaunchContext-kR8NUVFa.js → TerminalLaunchContext-58PQDilg.js} +1 -1
  68. package/dist/public/assets/{TerminalPanel-CBpH9VnO.js → TerminalPanel-DOYDhObX.js} +1 -1
  69. package/dist/public/assets/{TerminalSection-BIeBUi3Y.js → TerminalSection-CWS2W27g.js} +1 -1
  70. package/dist/public/assets/{TerminalWindowApp-D75W_nOD.js → TerminalWindowApp-0S4powU1.js} +1 -1
  71. package/dist/public/assets/{TextDocEditor-Dir-jZtA.js → TextDocEditor-DIsBDCjZ.js} +1 -1
  72. package/dist/public/assets/{ThemePluginSection-CovSRzUr.js → ThemePluginSection-0b67foiM.js} +1 -1
  73. package/dist/public/assets/{ThreadView-B5ZZtVV4.js → ThreadView-KbVr8sEz.js} +3 -3
  74. package/dist/public/assets/{TimelineDiffPane-QDBoFYDb.js → TimelineDiffPane-PhDxCy33.js} +1 -1
  75. package/dist/public/assets/{agent-connections-BmjcmCOh.js → agent-connections-Bc1t_U_m.js} +1 -1
  76. package/dist/public/assets/{agent-registry--47SG0kt.js → agent-registry-3ko3YkCm.js} +1 -1
  77. package/dist/public/assets/{bridge-njD5PB6P.js → bridge-BqL-1MyE.js} +1 -1
  78. package/dist/public/assets/{card-BsBNZHzU.js → card-CHd8wMSS.js} +1 -1
  79. package/dist/public/assets/{catalog-DtlAjcAT.js → catalog-nXBoyoEn.js} +1 -1
  80. package/dist/public/assets/{comment-chips-C9FVyemH.js → comment-chips-DOajrkhR.js} +3 -3
  81. package/dist/public/assets/{config-provider-ang-QnXf.js → config-provider-Dp4Rfq0I.js} +1 -1
  82. package/dist/public/assets/config-schema-8zesQqFR.js +1 -0
  83. package/dist/public/assets/{css-color-to-hex-vFOfC-Pa.js → css-color-to-hex-Dk3DSeEK.js} +1 -1
  84. package/dist/public/assets/{doc-undo-manager-D4kt3rYd.js → doc-undo-manager-ahQPlK9S.js} +1 -1
  85. package/dist/public/assets/field-controls-D4Q9aSAc.js +1 -0
  86. package/dist/public/assets/{field-controls-DdO1Jfbb.js → field-controls-c03mLOtp.js} +1 -1
  87. package/dist/public/assets/{file-tree-adapter-B1gVPdEq.js → file-tree-adapter-BeSKxnyg.js} +1 -1
  88. package/dist/public/assets/{frontmatter-tags-B-pVcI4P.js → frontmatter-tags-B7FS--Ga.js} +1 -1
  89. package/dist/public/assets/{index-BCiCqT8R.js → index-CWM5nCtw.js} +10 -10
  90. package/dist/public/assets/{lint-config-client-D0TnXak8.js → lint-config-client-DBaQUIFB.js} +1 -1
  91. package/dist/public/assets/{lint-plugins-CT78JavG.js → lint-plugins-B7BcnvBQ.js} +1 -1
  92. package/dist/public/assets/{markdown-lint-BKCKKMvW.js → markdown-lint-CciVlHiz.js} +1 -1
  93. package/dist/public/assets/{markdownlint-rule-browser-CLiJDsUJ.js → markdownlint-rule-browser-CV8JXarL.js} +1 -1
  94. package/dist/public/assets/messages-7VNu1LEh.js +1 -0
  95. package/dist/public/assets/messages-BoIpsnrB.js +1 -0
  96. package/dist/public/assets/messages-BtoWyWp4.js +1 -0
  97. package/dist/public/assets/messages-CAWZbzxC.js +1 -0
  98. package/dist/public/assets/messages-CGY-qBkm.js +1 -0
  99. package/dist/public/assets/messages-CI6bk3ZZ.js +1 -0
  100. package/dist/public/assets/messages-CKSKVChp.js +1 -0
  101. package/dist/public/assets/messages-CVkIPXvF.js +1 -0
  102. package/dist/public/assets/messages-CpkkpjCc.js +1 -0
  103. package/dist/public/assets/messages-DP2kzUjm.js +1 -0
  104. package/dist/public/assets/messages-DUncwHK7.js +1 -0
  105. package/dist/public/assets/messages-WS5AYLW5.js +1 -0
  106. package/dist/public/assets/messages-yosQwPO3.js +1 -0
  107. package/dist/public/assets/navigation-targets-DTSxcGor.js +1 -0
  108. package/dist/public/assets/{page-list-cache-s0lTSAFU.js → page-list-cache-BNFVKu-D.js} +1 -1
  109. package/dist/public/assets/{pending-receive-nav-store-DVgbBI_j.js → pending-receive-nav-store-Ji-MjcTi.js} +1 -1
  110. package/dist/public/assets/{preferred-session-events-Ayg96deM.js → preferred-session-events-DZS0rMoL.js} +1 -1
  111. package/dist/public/assets/{progress-DK60f0xv.js → progress-RYUnJ5Yy.js} +4 -4
  112. package/dist/public/assets/{saved-themes-client-DQgpb_Nl.js → saved-themes-client-C0V8gWns.js} +1 -1
  113. package/dist/public/assets/{schema-section-DShGMOyT.js → schema-section-BEhtY3tq.js} +1 -1
  114. package/dist/public/assets/{schemas-api-C4CP1G39.js → schemas-api-BM3O7zA1.js} +1 -1
  115. package/dist/public/assets/{selection-context-ClNQPaFJ.js → selection-context-DFzIaDVr.js} +1 -1
  116. package/dist/public/assets/{skills-api-BUVVp6gv.js → skills-api-Cwv39pKK.js} +1 -1
  117. package/dist/public/assets/{src-HUmS96mW.js → src-Cc4wFWWl.js} +1 -1
  118. package/dist/public/assets/storage-scope-67lIepq6.js +1 -0
  119. package/dist/public/assets/{tag-pill-input-BoyxN9pC.js → tag-pill-input-DoehfrBo.js} +1 -1
  120. package/dist/public/assets/{target-navigation-intent-DAN5F8dH.js → target-navigation-intent-D7IZjXLN.js} +1 -1
  121. package/dist/public/assets/{terminal-launch-events-Cy8GAcTt.js → terminal-launch-events-vPUm3fxK.js} +1 -1
  122. package/dist/public/assets/typing-burst-detector-D_B94C2V.js +8 -0
  123. package/dist/public/assets/{uninstall-CHUB11SP.js → uninstall-SlWuPbLL.js} +1 -1
  124. package/dist/public/assets/{use-activity-panel-DZWu1j8R.js → use-activity-panel-BynfAds7.js} +1 -1
  125. package/dist/public/assets/{use-apply-config-color-theme-lLFWDFMc.js → use-apply-config-color-theme-DsCyuU3O.js} +1 -1
  126. package/dist/public/assets/{use-apply-config-language-cr1JKqWJ.js → use-apply-config-language-CNWS2YSn.js} +2 -2
  127. package/dist/public/assets/{use-conflicts-B0yvUiLf.js → use-conflicts-CpABgIGI.js} +1 -1
  128. package/dist/public/assets/{use-installed-clis-4inF6O-n.js → use-installed-clis-CXwm5pk2.js} +2 -2
  129. package/dist/public/assets/{use-live-xterm-theme-BIzA-mu0.js → use-live-xterm-theme-CkVAs5Ql.js} +1 -1
  130. package/dist/public/assets/{use-open-skill-DpJ_35HO.js → use-open-skill-oBbTNCkY.js} +1 -1
  131. package/dist/public/assets/{use-semantic-search-status-CGPJyDjj.js → use-semantic-search-status-BYu4PoVz.js} +1 -1
  132. package/dist/public/assets/{use-skill-origin-Cv_S5gSq.js → use-skill-origin-Be1NTkgW.js} +1 -1
  133. package/dist/public/assets/{use-skill-targets-D-Tfz8TQ.js → use-skill-targets-Cf23drqO.js} +1 -1
  134. package/dist/public/assets/{use-skills-CRuEYkjM.js → use-skills-gbn1t63C.js} +1 -1
  135. package/dist/public/assets/{use-terminal-enabled-VopbK1KQ.js → use-terminal-enabled-DZ-JhCyV.js} +1 -1
  136. package/dist/public/assets/{use-timeline-entry-diff-DPE4FYBg.js → use-timeline-entry-diff-3gupsEXJ.js} +2 -2
  137. package/dist/public/assets/{use-workspace-Bf2VHQrp.js → use-workspace-BafUpQnS.js} +1 -1
  138. package/dist/public/index.html +55 -55
  139. package/dist/public/uninstall.html +3 -3
  140. package/dist/{registry-probes-CjXFMEIZ.mjs → registry-probes-D6HyJ_8R.mjs} +3 -3
  141. package/dist/{removal-file-path-DAe04iIF.mjs → removal-file-path-DpI99hTo.mjs} +1 -1
  142. package/dist/{repair-launch-json-Db5HnCXi.mjs → repair-launch-json--_R-76cC.mjs} +1 -1
  143. package/dist/{repair-mcp-configs-C21Kb5o_.mjs → repair-mcp-configs-CZSnWHtM.mjs} +1 -1
  144. package/dist/src-BrQpMSWu.mjs +11 -0
  145. package/dist/src-CY1smm1s.mjs +1 -0
  146. package/dist/{start-C8VQZz6U.mjs → start-CDnYOrHP.mjs} +3 -3
  147. package/dist/start-Pg-N_eC0.mjs +1 -0
  148. package/package.json +4 -4
  149. package/dist/constants-D7JQKPXh.mjs +0 -1
  150. package/dist/dist-BHg9XI3A.mjs +0 -2198
  151. package/dist/init-ec6ffu4x.mjs +0 -1
  152. package/dist/loader-DksiD2SW.mjs +0 -1
  153. package/dist/preview-D42uDe8a.mjs +0 -1
  154. package/dist/public/assets/CodeMirrorPropInput-BWNyI9V2.js +0 -164
  155. package/dist/public/assets/DocumentContext-DxDNsrxc.js +0 -108
  156. package/dist/public/assets/FeedbackForm-n4cK_QGh.js +0 -1
  157. package/dist/public/assets/ManagedArtifactProperties-uoCdZH2I.js +0 -1
  158. package/dist/public/assets/PageListContext-OHnhzUbe.js +0 -1
  159. package/dist/public/assets/config-schema-CcRHTCTU.js +0 -1
  160. package/dist/public/assets/field-controls-DF8qjTLS.js +0 -1
  161. package/dist/public/assets/messages-B3fCTSsU.js +0 -1
  162. package/dist/public/assets/messages-B4LuE4Uj.js +0 -1
  163. package/dist/public/assets/messages-BE2Gn3RX.js +0 -1
  164. package/dist/public/assets/messages-BI2FOXv1.js +0 -1
  165. package/dist/public/assets/messages-BW-Cdt9C.js +0 -1
  166. package/dist/public/assets/messages-BvhAxQrI.js +0 -1
  167. package/dist/public/assets/messages-CTIWBL1W.js +0 -1
  168. package/dist/public/assets/messages-CWGa07Dg.js +0 -1
  169. package/dist/public/assets/messages-DWxo7VDJ.js +0 -1
  170. package/dist/public/assets/messages-Df0SITTo.js +0 -1
  171. package/dist/public/assets/messages-HU4oqbuE.js +0 -1
  172. package/dist/public/assets/messages-b7a1Syss.js +0 -1
  173. package/dist/public/assets/messages-viWmNfI1.js +0 -1
  174. package/dist/public/assets/navigation-targets-BVafzc0v.js +0 -1
  175. package/dist/public/assets/storage-scope-DRWogX35.js +0 -1
  176. package/dist/public/assets/typing-burst-detector-BeLp1KqP.js +0 -8
  177. package/dist/src-CbgdwIHT.mjs +0 -11
  178. package/dist/src-DAzDkuCr.mjs +0 -1
  179. package/dist/start-CzEAj2qz.mjs +0 -1
@@ -1,5 +1,5 @@
1
- import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Bd as r,Ea as i,Rd as a,Ud as o,Vd as s,Yu as c,ef as l,kc as u,ku as d,of as f,rf as p,sf as m,wc as h}from"./md-manager-BGnqyqi1-DsBy1Dky.mjs";import{Jn as g,Pn as _,Xo as v,Yo as y,fa as ee,lr as b,m as x,ns as S,ts as te,wo as ne,zo as re}from"./dist-BHg9XI3A.mjs";import{$ as ie,A as C,J as ae,M as w,O as T,P as oe,R as se,T as ce,X as E,at as le,ct as ue,d as de,dt as fe,f as pe,it as me,j as he,k as ge,lt as _e,nt as ve,o as ye,rt as be,tt as xe,v as Se,w as Ce,x as we,y as Te}from"./init-C5n0LZMn.mjs";import{t as Ee}from"./is-object-BGze3w87.mjs";import{t as De}from"./removal-file-path-DAe04iIF.mjs";import{spawn as Oe}from"node:child_process";import{basename as D,dirname as O,join as k,resolve as A,win32 as ke}from"node:path";import{accessSync as Ae,constants as j,existsSync as M,lstatSync as N,mkdirSync as je,readFileSync as P,readdirSync as F,realpathSync as I,rmSync as Me,rmdirSync as Ne,statSync as L,unlinkSync as Pe}from"node:fs";import{homedir as Fe}from"node:os";import{createHash as Ie}from"node:crypto";import{isDeepStrictEqual as Le}from"node:util";import{setTimeout as Re}from"node:timers/promises";var ze=d();let Be;function Ve(){return Be}function He(e,t){if(t!==void 0&&t.length>0)return t;try{return b(e)?.rootPath}catch{return}}function Ue(e){let t=He(e.cwd,e.configuredProjectName),n=_({name:`cli`,project:t});return Be=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}function R(){return u(h)}function z(){return p().keyringService}function B(e){try{e()}catch{}}var We=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(z(),e).getPassword()}catch(t){return B(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return B(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return B(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(z(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(z(),e).deletePassword()}catch{}}},V=class{backend=`file`;authFile;constructor(e){this.authFile=e??k(v(),`auth.yml`)}read(){if(!M(this.authFile))return{};try{let e=P(this.authFile,`utf-8`);return(0,ze.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=O(this.authFile);M(t)||je(t,{recursive:!0,mode:448}),y(this.authFile,(0,ze.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},Ge=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${R()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function Ke(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(z(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
- `),B(()=>t?.onBackendSelected?.({backend:`keyring`})),new Ge(new We(t?.onKeychainRead),new V(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (${R()}) — OS keychain unavailable: ${r}\n`),B(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new V(e)}}function qe(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (${R()})\n`),r(new V(e))},n)});try{return await Promise.race([Ke(e),r])}catch{return new V(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Je(e){let t=qe(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function Ye(e){let t=qe(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function Xe(e,t){let n=[],r=new V(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));let i;try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(z(),`__probe__`);let r,a=await new We(e=>{e.kind===`read-error`&&(r=e.error??`read-error`)}).get(e);if(r!==void 0)i=r;else if(a!=null)try{new t(z(),e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function Ze(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Qe(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function $e(e){return ne({detached:!0,stdio:`ignore`,shell:!1,env:Ze(e)})}function et(e,t,n={}){let r=(n.spawn??Oe)(e,[...t],$e(n.env??process.env));return r.unref(),r}function tt(e,t,n={}){let r=n.spawn??Oe,i=n.timeoutMs??2e3;return new Promise(a=>{let o=!1,s=e=>{o||(o=!0,a(e))},c=setTimeout(()=>s({ok:!1,reason:`timeout`}),i);try{let i=r(e,[...t],$e(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(Qe(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(Qe(e))}})}const nt=l.stable.appId,H=[l.stable,l.beta];function rt(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return L(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function it(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}let t=e.homeDir??Fe();for(let n of H)for(let r of[k(t,`Applications`),`/Applications`]){let t=k(r,`${n.productName}.app`);if(at(e,k(t,`Contents`,`MacOS`,n.productName)))return t}return null}function at(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}function ot(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&H.find(t=>e.execPath.toLowerCase().endsWith(`\\${f(t).toLowerCase()}`)))return e.execPath;let t=e.env.LOCALAPPDATA;if(t)for(let n of H)for(let r of m(n)){let i=ke.join(t,`Programs`,r,f(n));if(at(e,i))return i}return null}function st(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&H.find(t=>e.execPath.endsWith(`/${t.linuxExecutableName}`)))return e.execPath;for(let t of H){let n=`/opt/${t.productName}/${t.linuxExecutableName}`;if(at(e,n))return n}return null}function ct(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`};let t;try{t=e.platform===`darwin`?it(e):e.platform===`win32`?ot(e):st(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function lt(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;n("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}if(r===`darwin`){et(`open`,[`-a`,i],{spawn:e.spawn});return}et(i,[],{spawn:e.spawn})}function ut(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it from https://openknowledge.ai/download, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function U(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function dt(e){return Ie(`sha256`).update(e).digest(`hex`)}function W(e){return k(v(A(e)),`pi-trust`)}function ft(e,t){return k(W(e),dt(A(t)))}function pt(e,t,n){return k(ft(e,t),`${dt(n)}.json`)}var G=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${U(e)} ${U(t)}; ${U(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function K(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new G(e,`could not ${t}: ${i}`,a,n)}function q(e){let t;try{t=N(e)}catch(t){if(t.code===`ENOENT`)return!1;throw K(e,`be inspected`,t)}if(!t.isDirectory())throw new G(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function mt(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function ht(e,t){if(!Ee(e)||!mt(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==A(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==A(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==A(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!Ee(e.previous))throw new G(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&mt(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&mt(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new G(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function gt(e,t,n){let r;try{r=N(n)}catch(e){throw K(n,`be inspected`,e)}if(!r.isFile())throw new G(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=P(n,`utf8`)}catch(e){throw K(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new G(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=ht(a,n);if(o.cwd!==A(t)||n!==pt(e,t,o.canonicalTrustPath))throw new G(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function _t(e,t){let{record:n,path:r}=t;for(let t of[W(e),ft(e,n.cwd)])if(!q(t))throw new G(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=gt(e,n.cwd,r);if(!Le(i.record,n))throw new G(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function vt(e,t,n,r,i){let a={version:1,cwd:A(t),configuredTrustPath:A(n),canonicalTrustPath:A(r),state:`pending`,previous:i},o=pt(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Le(ht(JSON.parse(s),o),a))throw new G(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);q(W(e)),q(O(o));try{je(O(o),{recursive:!0,mode:448})}catch(e){throw K(O(o),`be created`,e)}let c;try{c=N(o,{throwIfNoEntry:!1})}catch(e){throw K(o,`be inspected`,e)}if(c)throw new G(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{y(o,s,{mode:384})}catch(e){throw K(o,`be written`,e)}return{path:o,record:a}}function yt(e,t){let n=_t(e,t);if(n.record.state!==`pending`)throw new G(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{y(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw K(n.path,`be committed`,e)}return{path:n.path,record:r}}function J(e,t){if(!q(W(e)))return[];let n=ft(e,t);if(!q(n))return[];let r;try{r=F(n).sort()}catch(e){throw K(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>gt(e,t,k(n,r)))}function Y(e,t){let n=_t(e,t);try{Pe(n.path)}catch(e){throw K(n.path,`be removed after reconciling its grant`,e)}for(let t of[O(n.path),W(e)])try{Ne(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw K(t,`be removed after reconciling its grant`,e)}}var bt=n(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),xt=n(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),St=n(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),Ct=n(((t,n)=>{var r=e(`fs`),i=bt(),a=xt(),o=St(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
1
+ import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Fa as r,Nc as i,Qd as a,Rc as o,Ru as s,Xd as c,Yd as l,ff as u,gf as d,hf as f,id as p,lf as m,qd as h}from"./md-manager-BGnqyqi1-B1QSgyMJ.mjs";import{Jn as g,Pn as _,Xo as v,Yo as y,fa as ee,lr as b,m as x,ns as S,ts as te,wo as ne,zo as re}from"./dist-DMhyZWXW.mjs";import{$ as ie,A as C,J as ae,M as w,O as T,P as oe,R as se,T as ce,X as E,at as le,ct as ue,d as de,dt as fe,f as pe,it as me,j as he,k as ge,lt as _e,nt as ve,o as ye,rt as be,tt as xe,v as Se,w as Ce,x as we,y as Te}from"./init-B4K69pZS.mjs";import{t as Ee}from"./is-object-BGze3w87.mjs";import{t as De}from"./removal-file-path-DpI99hTo.mjs";import{spawn as Oe}from"node:child_process";import{basename as D,dirname as O,join as k,resolve as A,win32 as ke}from"node:path";import{accessSync as Ae,constants as j,existsSync as M,lstatSync as N,mkdirSync as je,readFileSync as P,readdirSync as F,realpathSync as I,rmSync as Me,rmdirSync as Ne,statSync as L,unlinkSync as Pe}from"node:fs";import{homedir as Fe}from"node:os";import{createHash as Ie}from"node:crypto";import{isDeepStrictEqual as Le}from"node:util";import{setTimeout as Re}from"node:timers/promises";var ze=s();let Be;function Ve(){return Be}function He(e,t){if(t!==void 0&&t.length>0)return t;try{return b(e)?.rootPath}catch{return}}function Ue(e){let t=He(e.cwd,e.configuredProjectName),n=_({name:`cli`,project:t});return Be=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}function R(){return o(i)}function z(){return u().keyringService}function B(e){try{e()}catch{}}var We=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(z(),e).getPassword()}catch(t){return B(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return B(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return B(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(z(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(z(),e).deletePassword()}catch{}}},V=class{backend=`file`;authFile;constructor(e){this.authFile=e??k(v(),`auth.yml`)}read(){if(!M(this.authFile))return{};try{let e=P(this.authFile,`utf-8`);return(0,ze.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=O(this.authFile);M(t)||je(t,{recursive:!0,mode:448}),y(this.authFile,(0,ze.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},Ge=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${R()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function Ke(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(z(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ `),B(()=>t?.onBackendSelected?.({backend:`keyring`})),new Ge(new We(t?.onKeychainRead),new V(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (${R()}) — OS keychain unavailable: ${r}\n`),B(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new V(e)}}function qe(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (${R()})\n`),r(new V(e))},n)});try{return await Promise.race([Ke(e),r])}catch{return new V(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Je(e){let t=qe(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function Ye(e){let t=qe(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function Xe(e,t){let n=[],r=new V(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));let i;try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(z(),`__probe__`);let r,a=await new We(e=>{e.kind===`read-error`&&(r=e.error??`read-error`)}).get(e);if(r!==void 0)i=r;else if(a!=null)try{new t(z(),e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function Ze(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Qe(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function $e(e){return ne({detached:!0,stdio:`ignore`,shell:!1,env:Ze(e)})}function et(e,t,n={}){let r=(n.spawn??Oe)(e,[...t],$e(n.env??process.env));return r.unref(),r}function tt(e,t,n={}){let r=n.spawn??Oe,i=n.timeoutMs??2e3;return new Promise(a=>{let o=!1,s=e=>{o||(o=!0,a(e))},c=setTimeout(()=>s({ok:!1,reason:`timeout`}),i);try{let i=r(e,[...t],$e(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(Qe(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(Qe(e))}})}const nt=m.stable.appId,H=[m.stable,m.beta];function rt(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return L(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function it(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}let t=e.homeDir??Fe();for(let n of H)for(let r of[k(t,`Applications`),`/Applications`]){let t=k(r,`${n.productName}.app`);if(at(e,k(t,`Contents`,`MacOS`,n.productName)))return t}return null}function at(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}function ot(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&H.find(t=>e.execPath.toLowerCase().endsWith(`\\${f(t).toLowerCase()}`)))return e.execPath;let t=e.env.LOCALAPPDATA;if(t)for(let n of H)for(let r of d(n)){let i=ke.join(t,`Programs`,r,f(n));if(at(e,i))return i}return null}function st(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&H.find(t=>e.execPath.endsWith(`/${t.linuxExecutableName}`)))return e.execPath;for(let t of H){let n=`/opt/${t.productName}/${t.linuxExecutableName}`;if(at(e,n))return n}return null}function ct(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`};let t;try{t=e.platform===`darwin`?it(e):e.platform===`win32`?ot(e):st(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function lt(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;n("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}if(r===`darwin`){et(`open`,[`-a`,i],{spawn:e.spawn});return}et(i,[],{spawn:e.spawn})}function ut(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it from https://openknowledge.ai/download, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function U(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function dt(e){return Ie(`sha256`).update(e).digest(`hex`)}function W(e){return k(v(A(e)),`pi-trust`)}function ft(e,t){return k(W(e),dt(A(t)))}function pt(e,t,n){return k(ft(e,t),`${dt(n)}.json`)}var G=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${U(e)} ${U(t)}; ${U(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function K(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new G(e,`could not ${t}: ${i}`,a,n)}function q(e){let t;try{t=N(e)}catch(t){if(t.code===`ENOENT`)return!1;throw K(e,`be inspected`,t)}if(!t.isDirectory())throw new G(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function mt(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function ht(e,t){if(!Ee(e)||!mt(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==A(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==A(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==A(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!Ee(e.previous))throw new G(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&mt(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&mt(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new G(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function gt(e,t,n){let r;try{r=N(n)}catch(e){throw K(n,`be inspected`,e)}if(!r.isFile())throw new G(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=P(n,`utf8`)}catch(e){throw K(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new G(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=ht(a,n);if(o.cwd!==A(t)||n!==pt(e,t,o.canonicalTrustPath))throw new G(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function _t(e,t){let{record:n,path:r}=t;for(let t of[W(e),ft(e,n.cwd)])if(!q(t))throw new G(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=gt(e,n.cwd,r);if(!Le(i.record,n))throw new G(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function vt(e,t,n,r,i){let a={version:1,cwd:A(t),configuredTrustPath:A(n),canonicalTrustPath:A(r),state:`pending`,previous:i},o=pt(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Le(ht(JSON.parse(s),o),a))throw new G(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);q(W(e)),q(O(o));try{je(O(o),{recursive:!0,mode:448})}catch(e){throw K(O(o),`be created`,e)}let c;try{c=N(o,{throwIfNoEntry:!1})}catch(e){throw K(o,`be inspected`,e)}if(c)throw new G(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{y(o,s,{mode:384})}catch(e){throw K(o,`be written`,e)}return{path:o,record:a}}function yt(e,t){let n=_t(e,t);if(n.record.state!==`pending`)throw new G(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{y(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw K(n.path,`be committed`,e)}return{path:n.path,record:r}}function J(e,t){if(!q(W(e)))return[];let n=ft(e,t);if(!q(n))return[];let r;try{r=F(n).sort()}catch(e){throw K(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>gt(e,t,k(n,r)))}function Y(e,t){let n=_t(e,t);try{Pe(n.path)}catch(e){throw K(n.path,`be removed after reconciling its grant`,e)}for(let t of[O(n.path),W(e)])try{Ne(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw K(t,`be removed after reconciling its grant`,e)}}var bt=n(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),xt=n(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),St=n(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),Ct=n(((t,n)=>{var r=e(`fs`),i=bt(),a=xt(),o=St(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
3
3
  GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=ne,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);b=g.ReadStream,S=g.WriteStream}var _=e.ReadStream;_&&(b.prototype=Object.create(_.prototype),b.prototype.open=x);var v=e.WriteStream;v&&(S.prototype=Object.create(v.prototype),S.prototype.open=te),Object.defineProperty(e,"ReadStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return S},set:function(e){S=e},enumerable:!0,configurable:!0});var y=b;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var ee=S;Object.defineProperty(e,"FileWriteStream",{get:function(){return ee},set:function(e){ee=e},enumerable:!0,configurable:!0});function b(e,t){return this instanceof b?(_.apply(this,arguments),this):b.apply(Object.create(b.prototype),arguments)}function x(){var e=this;C(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function S(e,t){return this instanceof S?(v.apply(this,arguments),this):S.apply(Object.create(S.prototype),arguments)}function te(){var e=this;C(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var ie=e.open;e.open=C;function C(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return ie(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),wt=n(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Tt=n((e=>{var t=wt();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),Et=n(((e,t)=>{t.exports=Tt()})),Dt=n(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),Ot=n(((t,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=e(`assert`),o=Dt(),s=/^win/i.test(r.platform),c=e(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),kt=n(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),At=n(((t,n)=>{let r=e(`path`),i=Ct(),a=Et(),o=Ot(),s=kt(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),jt=n(((e,t)=>{let n=Ct();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),Mt=t(n(((e,t)=>{let n=At(),{toPromise:r,toSync:i,toSyncOptions:a}=jt();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const Nt=5e3;function Pt(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${Nt}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Ft(e,t){Ve()?.warn(t,e)}function It(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function Lt(e,t,n){await te(`${t}.ok.lock`,async()=>{let t=performance.now()+Nt,r;for(;;)try{r=await Mt.default.lock(O(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Re(Pt(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}It(i,e)},{onWarn:Ft})}function Rt(e,t,n){S(`${t}.ok.lock`,()=>{let t=performance.now()+Nt,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=Mt.default.lockSync(O(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,Pt(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}It(a,e)},{onWarn:Ft})}const zt=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var Bt=class extends Error{name=`PiResourceInspectionError`};function X(e){let t;try{t=N(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=L(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new Bt(he(`missing-symlink-target`),{cause:e}):e}return Ae(e,j.R_OK|(n.isDirectory()?j.X_OK:0)),!0}function Vt(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function Ht(e,t,n){let r=e;try{let i=I(e),a;r=t;try{a=I(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=A(t)}let o=k(a,`.agents`,`skills`),s=[];for(let e of zt)r=k(i,`.pi`,e),X(r)&&s.push(r);if(r=k(i,`.pi`,`extensions`),X(r))for(let t of F(r).sort()){let i=k(r,t);A(n)!==k(A(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[k(i,`.pi`,`skills`),k(i,`.agents`,`skills`)])if(e!==o&&(r=e,X(e)))for(let t of F(e).sort())Vt(t)||s.push(k(e,t));let c=O(i);for(;c!==i;){r=k(c,`.agents`,`skills`),r!==o&&X(r)&&s.push(r);let e=O(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${U(r)}: ${e instanceof Bt?e.message:he(w(e))}`}}}function Ut(e,t,n){let r=A(e),i=ue({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:E.pi.projectConfigPath(r),trustPath:k(i,`trust.json`)}}function Z(e){try{let t=I(e);return L(t).isDirectory()?(Ae(t,j.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${U(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${U(e)} could not be resolved or accessed: ${U(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function Wt(e){let t=Z(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${U(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function Gt(e,t,n){let r=ye(E.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return be(i)?{state:`own-current`,text:a}:ce(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function Kt(e,t){let n;try{n=P(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:w(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return Ee(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
4
4
  `)}:{state:`unreadable`,reason:`invalid-json`}}function qt(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return he(e)}}function Q(e,t){return{kind:`refused`,error:`trust store ${U(e)}: ${qt(t)}`}}function Jt(e){let t=De(e);try{switch(t.kind){case`declined`:return Q(e,t.reason);case`ready`:return{kind:`ready`,path:I(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=O(e),r=[D(e)],i=N(n,{throwIfNoEntry:!1});for(;!i;){let t=O(n);if(t===n)return Q(e,`unavailable-root`);r.unshift(D(n)),n=t,i=N(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:k(I(n),...r)}}catch(t){return Q(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:w(t))}}catch(t){return Q(e,w(t))}}function Yt(e,t){let n=Jt(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?Q(e,`path-changed`):n}function Xt(e,t,n){let r=Ut(e,t,n),i=Z(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=Gt(r.cwd,r.bridgePath,t).state,o=Jt(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:Kt(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:Zt(r.bridgePath).displayNames}}function Zt(e){let t=O(e),n=D(e);try{return{displayNames:F(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>U(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function Qt(e,t={mode:`published`},n,r,i){let a=Ut(e,n,r),o=Z(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${U(i)} no longer matches the current directory ${U(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=Gt(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=Ce(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=Te(E.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:U(e.error)}}let l=await $t(a.trustPath,o.project,n??Fe());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function $t(e,t,n){let r=t.canonical,i=Jt(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{je(O(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:U(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await Lt(e,i.path,()=>{let o=Wt(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=Yt(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=Kt(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=Q(e,c.reason).error;return}let l=$(n,()=>{let t=J(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&Y(n,t),vt(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
5
5
  `:``),f=T(s.path);y(s.path,d,f===void 0?void 0:{mode:f}),$(n,()=>yt(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:U(e instanceof Error?e.message:String(e))}}return a}function en(e){let t=[],n=e;try{for(;;){if(N(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=I(n);return L(e).isDirectory()?(Ae(e,j.X_OK),k(e,...t)):void 0}let e=O(n);if(e===n)return;t.unshift(D(n)),n=e}}catch{return}}function tn(e){let t={"not-present":0,removed:1,"kept-unowned":2,"kept-shared":3,"kept-unverified":4,"refused-unreadable":5,failed:6},n=e.reduce((e,n)=>t[n.action]>t[e.action]?n:e,{action:`not-present`}),r=e.flatMap(e=>e.error??[]),i=e.flatMap(e=>e.detail??[]);return r.length>0?{action:n.error===void 0?`failed`:n.action,error:[...r,...i].join(`
@@ -14,4 +14,4 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
14
14
  `),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
15
15
  `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
16
16
  `).replace(/\n/g,`\r
17
- `));let u=`${i?``:``}${l}`;return u!==r&&y(e,u,{mode:T(e)}),{kind:`removed`}}function mn(e,t){let n=s[e];return n===null?null:k(t,...n.split(`/`),x.discovery,`SKILL.md`)}function hn(e,t){let n=mn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!g(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=ee(`discovery`,{checkDesktop:!0});return oe(O(n),t),{editorId:e,label:e,action:se(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function gn(e){return M(k(e,...`.agents/skills`.split(`/`),x.discovery))?!0:a.some(t=>{let n=mn(t,e);return n!==null&&M(O(n))})}function _n(e,t){let n=mn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=O(n);try{return M(n)?(oe(r,t),Me(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function vn(e){return e===`opencode`?le:ve}function yn(e,t,n){let r=E[e],i=vn(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=pe(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function bn(e,t,n=[]){let r=M(k(e,x[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function xn(e,t){let n=ae.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=o.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:i}));return[...n,...r]}function Sn(e,t,n,r){let i=re(e,xn(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function Cn(e,t){let n=(t??Fe()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function wn(e,t){let n=E[e];return we(n,``,t)&&!de(n,``,t)}function Tn(e,t,n,r,i){let a=E[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?Cn(o,r):void 0,c=ye(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&wn(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];be(r)&&i.push(`reclaim-permissive`),me(r)&&i.push(`pre-approval-exact`),vn(e)(r)&&i.push(`injection-functional`);let o=ie(a,n);return i.length>0&&(o!==null&&xe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:_e(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function En(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let a=c(e.pathId);if(a===null)return null;if(a.kind===`central-skill-store`)return n===void 0?null:bn(k(n,i),`discovery`,Sn(n,s,e.agent,`global`));let o=a.editor;switch(a.kind){case`editor-user-skill-root`:{let e=s[o];return e===null||n===void 0?null:g(n).some(e=>e.editorId===o)?bn(k(n,e),`discovery`,Sn(n,s,o,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=r[o];return e===null?null:bn(k(t,e),`project`,Sn(t,r,o,`project`))}case`editor-user-config`:return Tn(o,e.strictness,t,n);case`editor-project-config`:{let r=E[o].projectConfigPath?.(t);return r===void 0?null:Tn(o,e.strictness,t,n,r)}}}}export{Ue as S,Xe as _,hn as a,Ye as b,Xt as c,ct as d,lt as f,R as g,tt as h,gn as i,nt as l,et as m,yn as n,un as o,ut as p,_n as r,Qt as s,En as t,rt as u,Ke as v,Ve as x,Je as y};
17
+ `));let u=`${i?``:``}${l}`;return u!==r&&y(e,u,{mode:T(e)}),{kind:`removed`}}function mn(e,t){let n=c[e];return n===null?null:k(t,...n.split(`/`),x.discovery,`SKILL.md`)}function hn(e,t){let n=mn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!g(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=ee(`discovery`,{checkDesktop:!0});return oe(O(n),t),{editorId:e,label:e,action:se(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function gn(e){return M(k(e,...`.agents/skills`.split(`/`),x.discovery))?!0:h.some(t=>{let n=mn(t,e);return n!==null&&M(O(n))})}function _n(e,t){let n=mn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=O(n);try{return M(n)?(oe(r,t),Me(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function vn(e){return e===`opencode`?le:ve}function yn(e,t,n){let r=E[e],i=vn(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=pe(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function bn(e,t,n=[]){let r=M(k(e,x[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function xn(e,t){let n=ae.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),i=a.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:r}));return[...n,...i]}function Sn(e,t,n,r){let i=re(e,xn(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function Cn(e,t){let n=(t??Fe()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function wn(e,t){let n=E[e];return we(n,``,t)&&!de(n,``,t)}function Tn(e,t,n,r,i){let a=E[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?Cn(o,r):void 0,c=ye(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&wn(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];be(r)&&i.push(`reclaim-permissive`),me(r)&&i.push(`pre-approval-exact`),vn(e)(r)&&i.push(`injection-functional`);let o=ie(a,n);return i.length>0&&(o!==null&&xe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:_e(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function En(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let i=p(e.pathId);if(i===null)return null;if(i.kind===`central-skill-store`)return n===void 0?null:bn(k(n,r),`discovery`,Sn(n,c,e.agent,`global`));let a=i.editor;switch(i.kind){case`editor-user-skill-root`:{let e=c[a];return e===null||n===void 0?null:g(n).some(e=>e.editorId===a)?bn(k(n,e),`discovery`,Sn(n,c,a,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=l[a];return e===null?null:bn(k(t,e),`project`,Sn(t,l,a,`project`))}case`editor-user-config`:return Tn(a,e.strictness,t,n);case`editor-project-config`:{let r=E[a].projectConfigPath?.(t);return r===void 0?null:Tn(a,e.strictness,t,n,r)}}}}export{Ue as S,Xe as _,hn as a,Ye as b,Xt as c,ct as d,lt as f,R as g,tt as h,gn as i,nt as l,et as m,yn as n,un as o,ut as p,_n as r,Qt as s,En as t,rt as u,Ke as v,Ve as x,Je as y};
@@ -1 +1 @@
1
- import{M as e,S as t}from"./init-C5n0LZMn.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(t){return t.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:e(t)}}let o=t(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(t){return{kind:`declined`,reason:a&&t.code===`ENOENT`?`missing-symlink-target`:e(t)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
1
+ import{M as e,S as t}from"./init-B4K69pZS.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(t){return t.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:e(t)}}let o=t(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(t){return{kind:`declined`,reason:a&&t.code===`ENOENT`?`missing-symlink-target`:e(t)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
@@ -1 +1 @@
1
- import{t as e}from"./launch-json-removal-BE6cJksG.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
1
+ import{t as e}from"./launch-json-removal-CT0i-3-W.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
@@ -1 +1 @@
1
- import{C as e}from"./md-manager-BGnqyqi1-DsBy1Dky.mjs";import{J as t,X as n,et as r,f as i,rt as a,y as o}from"./init-C5n0LZMn.mjs";import{homedir as s}from"node:os";function c(e){let{priorCommand:t,priorArgs:n}=l(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function l(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function u(e){let r=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=d(()=>t.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},s=i(t.target,t.cwd,t.home,t.configPathOverride);if(s===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(s))return{...n,outcome:`canonical`}}else{let i=e(s);if(i.kind===`recognized`&&i.disposition===`keep`){let e=r(s,t.target.buildEntry(t.cwd,{}));if(e.length===0)return{...n,outcome:`canonical`};let i=p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(i.outcome===`repaired`||i.outcome===`canonical`)&&t.logger({event:i.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:i.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),i.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:i}if(i.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:i.reason}),{...n,outcome:`foreign`,reason:i.reason}}return t.logger({...c({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:s}),severity:`info`}),p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride))}function p(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function m(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as n,u as repairMcpConfigs,c as t};
1
+ import{C as e}from"./md-manager-BGnqyqi1-B1QSgyMJ.mjs";import{J as t,X as n,et as r,f as i,rt as a,y as o}from"./init-B4K69pZS.mjs";import{homedir as s}from"node:os";function c(e){let{priorCommand:t,priorArgs:n}=l(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function l(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function u(e){let r=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=d(()=>t.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},s=i(t.target,t.cwd,t.home,t.configPathOverride);if(s===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(s))return{...n,outcome:`canonical`}}else{let i=e(s);if(i.kind===`recognized`&&i.disposition===`keep`){let e=r(s,t.target.buildEntry(t.cwd,{}));if(e.length===0)return{...n,outcome:`canonical`};let i=p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(i.outcome===`repaired`||i.outcome===`canonical`)&&t.logger({event:i.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:i.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),i.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:i}if(i.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:i.reason}),{...n,outcome:`foreign`,reason:i.reason}}return t.logger({...c({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:s}),severity:`info`}),p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride))}function p(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function m(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as n,u as repairMcpConfigs,c as t};
@@ -0,0 +1,11 @@
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{Al as t,B as n,H as r,Hc as i,Ru as a,Uc as o,V as s,_f as c,ff as l,ha as u,if as d,kl as f,l as p,ma as ee,mf as m,u as te,zc as h}from"./md-manager-BGnqyqi1-B1QSgyMJ.mjs";import{$o as g,Dt as _,Mi as v,Ni as y,Qo as b,Sr as x,Xo as S,Yn as C,_i as w,ar as T,ba as E,es as D,gi as O,hi as ne,li as k,lr as A,m as j,ri as M,wo as N,ys as P}from"./dist-DMhyZWXW.mjs";import{t as F}from"./yazl-BBz29IQN.mjs";import{Ct as I,ot as re,st as ie}from"./init-B4K69pZS.mjs";import{l as ae,x as oe}from"./registry-probes-D6HyJ_8R.mjs";import{c as se}from"./colors-r_owlCuY.mjs";import{t as ce}from"./is-object-BGze3w87.mjs";import{n as le}from"./constants-CCYsBRvI.mjs";import"./loader-DZHqBHXr.mjs";import"./preview-BdmlMCtY.mjs";import{execSync as ue,spawnSync as de}from"node:child_process";import{basename as L,dirname as R,isAbsolute as fe,join as z,relative as pe,resolve as B,sep as V}from"node:path";import{closeSync as me,cpSync as he,createWriteStream as ge,existsSync as H,lstatSync as _e,mkdirSync as U,mkdtempSync as ve,openSync as ye,readFileSync as W,readSync as be,readdirSync as G,readlinkSync as xe,realpathSync as Se,rmSync as K,rmdirSync as Ce,statSync as we,writeFileSync as q}from"node:fs";import{arch as Te,freemem as Ee,homedir as J,hostname as De,platform as Oe,release as ke,tmpdir as Ae,totalmem as je,type as Me,uptime as Ne}from"node:os";import"node:fs/promises";import{createHash as Pe}from"node:crypto";function Fe(e,t){let n=t.map(e=>[P(e),e]);for(let t of e){let e=P(t);if(e===null)continue;let r=n.find(([t])=>t===e);if(r!==void 0)return r[1]}}function Ie(e){let{override:t,storedPreference:n,preferenceList:r,supportedLocales:i}=e,a=e.autoDetectableLocales??i;if(t!==void 0){let e=Fe([t],i);if(e!==void 0)return{locale:e,source:`override`}}if(n!==void 0&&n!==`system`&&i.includes(n))return{locale:n,source:`explicit`};let o=Fe(r,a);return o===void 0?{locale:`en`,source:`fallback`}:{locale:o,source:`system`}}function Le(e,t=Date.now()){let n=Date.parse(e);if(!Number.isFinite(n))return`unknown`;let r=Math.floor(Math.max(0,t-n)/1e3);if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}const Re=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`audit`,`deinit`,`auth`]);function ze(e,t,n=A){if(e!==void 0&&!Re.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Be=null;function Ve(e){Be=e}function He(){return Be??process.cwd()}const Ue=`Open Knowledge`;function We(e={}){let t=e.platformName??process.platform,n=e.productName??l().productName;return re(t).join(ie({...e,platformName:t}),n)}function Ge(e={}){let t=e.platformName??process.platform,n=e.home??J(),r=e.env??process.env,i=re(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`${l().packageName.replaceAll(`/`,``)}-updater`)}function Ke(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function qe(e){let t=z(e,`state.json`);if(!H(t))return[];let n;try{n=JSON.parse(W(t,`utf-8`))}catch{return[]}return Ke(n)??[]}function Je(e){let t=z(e,`state.json`);if(!H(t))return!1;try{return Ke(JSON.parse(W(t,`utf-8`)))!==null}catch{return!1}}const Ye=8192;function Xe(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function Ze(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Qe=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function $e(e){return e.replace(Qe,`$1"[REDACTED-DEVICE-ID]"`)}function et(e){return $e(Ze(e))}const tt=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function nt(e){if(typeof e!=`string`)return null;let t=tt.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function rt(e){let t=ye(e,`r`);try{let e=Buffer.alloc(Ye),n=0,r=!1;for(;n<Ye;){let i=be(t,e,n,Ye-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{me(t)}}function it(e){try{let t=rt(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:nt(a)}}catch{return{kind:`unreadable`}}}function at(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function ot(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=G(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=z(e,t.name),r;try{r=we(n).mtimeMs}catch{continue}if(r<i)continue;let c=it(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!at(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function Y(){return z(S(),`bug-reports`)}function st(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Y(),r=`${t}-bugreport`,i=z(n,`${r}.zip`);for(let e=2;H(i);e+=1)i=z(n,`${r}-${e}.zip`);return i}function ct(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function lt(e,t){let n=z(e,`.ok`,`config.yml`);if(H(n))try{let e=W(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return H(z(e,`.ok`))?Pe(`sha256`).update(B(e)).digest(`hex`).slice(0,12):null}function ut(){let e={timestamp:new Date().toISOString(),platform:Oe(),osType:Me(),osRelease:ke(),hostname:`[redacted]`,uptime:Ne(),freeMem:Ee(),totalMem:je(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=ue(`sw_vers -productVersion 2>/dev/null`,N({encoding:`utf8`})).trim()}catch{}try{let t=z(__dirname,`..`,`..`,`package.json`);H(t)&&(e.okVersion=JSON.parse(W(t,`utf8`)).version)}catch{}return e}const dt=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function ft(e){let t=L(e);return dt.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function pt(e,t){return _t(e,t).files}const mt=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function ht(e,t=ae){let n=z(e,`${t}.ShipIt`);if(!H(n))return[];let r;try{r=G(n)}catch{return[]}return mt.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>z(n,e.entry)))}function gt(e){if(!H(e))return[];try{let t=new Map;for(let n of G(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-p.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>z(e,t))}catch{return[]}}function _t(e,t){if(!H(t))return{files:[],excludedByProjectSlug:0};let n=G(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>z(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(ft),i=[],a=r.filter(t=>{try{return W(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!ft(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function vt(e){let t=z(e,`.ok`,`local`);return H(t)?{files:[`server.lock`,`last-spawn-error.log`,i,h].map(e=>z(t,e)).filter(e=>H(e))}:{files:[]}}function yt(e){let t=z(e,`.ok`,`local`,`logs`);return H(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>z(t,e)).filter(e=>H(e))}:{files:[]}}function bt(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Pe(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function xt(e){let t=e.revealDocNames?e.content:bt(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=u(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function X(e){for(let t of e.files)try{let n=W(t,`utf8`);xt({zipfile:e.zipfile,name:`${e.prefix}/${L(t)}`,content:t.endsWith(`.ips`)?et(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function St(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??z(S(),`logs`),s=t.projectDir?lt(t.projectDir,i):null;U(R(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=ut();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=_t(s,o),{files:d}=t.projectDir?vt(t.projectDir):{files:[]},{files:f}=t.projectDir?yt(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:_}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new _;X({zipfile:v,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:te,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i});for(let e of t.extraFiles??[])try{let t=W(e.sourcePath),n=`extra/${e.zipName??L(e.sourcePath)}`;v.addBuffer(t,n),g.push(n);let r=ct(e,n);r!==null&&h.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&xt({zipfile:v,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${L(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Xe(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`);let C=JSON.stringify(c,null,2);v.addBuffer(Buffer.from(C,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let w={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:g,redactions:h,sysinfo:c};v.addBuffer(Buffer.from(JSON.stringify(w,null,2),`utf8`),`MANIFEST.json`);let T=h.reduce((e,t)=>e+t.lineCount,0),E=new Set(p.map(e=>`logs/${L(e)}`)),D=g.filter(e=>E.has(e)),O=new Set((t.bugReportLedgerFiles??[]).map(e=>`${te}/${L(e)}`)),ne=g.filter(e=>O.has(e)),k=s?g.filter(e=>e.startsWith(`logs/`)&&!ft(e)&&!E.has(e)):[],A=b.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],j=A.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...A]:[`Redaction was disabled for this bundle; file contents are unmodified.`],M=[`# Bug Report Bundle`,``,`Generated: ${w.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${w.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...k.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...k.map(e=>`- ${e}`),``]:[],...D.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...D.map(e=>`- ${e}`),``]:[],...b.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...b.map(e=>`- ${e}`),``]:[],...ne.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${ee.join(`, `)}`,T>0?`${T} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...A,``,`This bundle is safe to attach to a GitHub issue.`]:j].join(`
2
+ `);v.addBuffer(Buffer.from(M,`utf8`),`README.md`),v.end();let N=ge(r);return v.outputStream.pipe(N),await new Promise((e,t)=>{N.on(`close`,e),N.on(`error`,t)}),i?.info({bundlePath:r,fileCount:g.length,redactionCount:T},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:g,redactions:h,redactedLineCount:T,generatedAt:w.generatedAt}}}var Ct=a(),wt=e(F(),1),Z=e(se(),1);function Tt(e){let t=D(`user`,e,e);return b({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function Et({home:e=J(),env:n=process.env}={}){let r=Tt(e),{override:i,preferenceList:a}=g(n),{locale:o,source:s}=Ie({override:i,storedPreference:r,supportedLocales:t,preferenceList:a,autoDetectableLocales:f});return{preference:r,locale:o,source:s,systemLanguages:a}}function Dt(e){let t=new Set([e]);try{t.add(Se.native(e))}catch{return[e].filter(e=>e.length>0)}return[...t].filter(e=>e.length>0).sort((e,t)=>t.length-e.length)}function Ot(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function kt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function At(e,t){if(typeof e==`string`)return Ot(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>At(e,t));if(!kt(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=At(i,t);return n}function jt(e,t){let n=W(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
3
+ `),i=n.split(`
4
+ `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(e!==i.length-1||n!==``){if(n.length===0){a.push(``);continue}try{let e=At(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
5
+ `)}\n`:a.join(`
6
+ `);q(e,o)}function Mt(e,t){let n=W(e,`utf-8`);if(n.trim().length!==0)try{let r=At(JSON.parse(n),t),i=n.endsWith(`
7
+ `)?`
8
+ `:``;q(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=Ot(n,t.contentDirSpellings);r!==n&&q(e,r)}}function Nt(e,t){let n=W(e,`utf-8`),r=Ot(n,t.contentDirSpellings);r!==n&&q(e,r)}function Pt(e){try{return G(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>z(e,t.name))}catch{return[]}}const Ft=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function It(e){return/\.log\.\d+$/.test(e)}function Lt(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||It(e)}const Rt=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function zt(e){let t={contentDirSpellings:Dt(e.contentDir)};for(let n of Rt)for(let r of Pt(z(e.stagingDir,n)))Lt(r)?jt(r,t):r.endsWith(`.json`)?Mt(r,t):Nt(r,t);for(let n of Pt(z(e.stagingDir,`state`))){let e=L(n);n.endsWith(`.jsonl`)?jt(n,t):Ft.has(e)?Mt(n,t):Nt(n,t)}}const Bt=[`.ok`,`local`,`telemetry`],Vt=[`.ok`,`local`,`logs`],Ht=[`.ok`,`local`,`loss-capture`],Ut=`spans-current.jsonl`,Wt=`spans-prev.jsonl`,Gt=`server-current.jsonl`,Kt=`server-prev.jsonl`,qt=`loss-current.jsonl`,Jt=`loss-prev.jsonl`;function Yt(e){return z(e,...Bt,Ut)}function Xt(e){return z(e,...Bt,Wt)}function Zt(e){return z(e,...Vt,Gt)}function Qt(e){return z(e,...Vt,Kt)}function $t(e){return z(e,...Ht,qt)}function en(e){return z(e,...Ht,Jt)}const tn=1e3;async function nn(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(tn)});return t.ok?await t.text():null}catch{return null}}async function rn(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(tn)});return t.ok?await t.text():null}catch{return null}}async function an(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(tn)});return t.ok?await t.text():null}catch{return null}}function on(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
9
+ `)}\n`:null}catch{return null}}function sn(e){let t=z(e,`.git`,`ok`);if(!H(t))return null;let n=de(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function cn(e){let t=z(e,`.git`,`ok`);if(!H(t))return null;let n=de(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function ln(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function un(){return{nodeVersion:process.version,platform:Oe(),arch:Te()}}function dn(){return process.env.OTEL_SDK_DISABLED===`false`}function fn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pn(e){if(!H(e))return{};let t;try{t=(0,Ct.parse)(W(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!fn(t))return{};let n=t.telemetry;if(!fn(n))return{};let r=n.localSink;return fn(r)?r:{}}function mn(e){return typeof e==`boolean`?e:void 0}function hn(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function gn(e){if(fn(e))return hn(e.maxBytes)}function _n(e){let t=pn(D(`project`,e)),n=pn(D(`project-local`,e));return{enabled:mn(n.enabled)??mn(t.enabled)??!0,spansMaxBytes:gn(n.spans)??gn(t.spans)??52428800,logsMaxBytes:gn(n.logs)??gn(t.logs)??26214400}}function vn(e){return Pe(`sha256`).update(e).digest(`hex`)}function yn(e){let t=W(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const bn=[`"doc.name"`,`"docName"`];function xn(e){let t=W(e,`utf-8`),n=0;for(let e of bn){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Q(e,t){if(!H(e))return!1;try{return U(R(t),{recursive:!0}),e.endsWith(`.ips`)?q(t,et(W(e,`utf-8`))):he(e,t),!0}catch{return!1}}function Sn(e){let t=[],n=e=>{let r=G(e,{withFileTypes:!0});for(let i of r){let r=z(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Cn=new Set([`.jsonl`]);function wn(e){let t=e.lastIndexOf(`.`);return t!==-1&&Cn.has(e.slice(t))}const Tn=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function En(e){if(It(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Tn.has(e.slice(t))}function Dn(e){let t=[];for(let n of Sn(e)){let r=On(e,n);if(!En(r))continue;let{redacted:i,patterns:a,lineCount:o}=u(W(n,`utf-8`));a.length!==0&&(q(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function On(e,t){return pe(e,t).split(V).join(`/`)}async function kn(e){let t=B(e.contentDir),n=B(e.projectDir??e.contentDir),r=e.deps??{},a=r.fetchAgentPresence??nn,s=r.fetchAgentEffects??rn,c=r.fetchWatcherRecent??an,l=r.readShadowHead??sn,u=r.readCheckpointRefs??cn,d=r.now??(()=>new Date),f=r.okVersion??(()=>le),p=r.readDesktopEnv??ln,ee=r.readLanguage??Et,m=r.readRuntime??un,g=r.isOtlpPushEnabled??dn,_=ve(z(Ae(),`ok-bundle-`));try{U(z(_,`telemetry`),{recursive:!0}),U(z(_,`logs`),{recursive:!0}),U(z(_,`state`),{recursive:!0}),Q(Yt(n),z(_,`telemetry`,Ut)),Q(Xt(n),z(_,`telemetry`,Wt)),Q(Zt(n),z(_,`logs`,Gt)),Q(Qt(n),z(_,`logs`,Kt));for(let t of e.userLogFiles??[])Q(t,z(_,`logs`,L(t)));for(let t of e.userStateFiles??[])Q(t,z(_,te,L(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Q(t,z(_,`diagnostic-reports`,L(t)))&&(v+=1);let y=z(n,`.ok`,`local`),b=z(y,`server.lock`),x=`not-running`,S=`no server.lock`,C=null;if(H(b)){Q(b,z(_,`state`,`server.lock`));try{let e=W(b,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?C=t.port:S=`lock present but no port`}catch{S=`lock present but unparseable`}}if(C!==null){let e=await a(C);e===null?S=`agent-presence endpoint at :${C} unreachable`:(q(z(_,`state`,`agent-presence.json`),e),x=`running`,S=``);let t=await s(C);t!==null&&q(z(_,`state`,`agent-effects.json`),t);let n=await c(C);if(n!==null){let e=on(n);e!==null&&q(z(_,`state`,`watcher-recent.jsonl`),e)}}let w=l(t);w!==null&&q(z(_,`state`,`shadow-head.txt`),w);let T=u(t);T!==null&&q(z(_,`state`,`checkpoint-refs.txt`),T),Q($t(n),z(_,`state`,qt)),Q(en(n),z(_,`state`,Jt)),Q(z(y,`last-spawn-error.log`),z(_,`state`,`last-spawn-error.log`)),Q(z(y,o),z(_,`state`,o)),Q(z(y,i),z(_,`state`,i)),Q(z(y,h),z(_,`state`,h));let E=m(),D=p(),O=ee(),ne={ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O}};q(z(_,`state`,`runtime.json`),`${JSON.stringify(ne,null,2)}\n`);let k=x===`running`?`running
10
+ `:`not-running (${S})\n`;q(z(_,`state`,`server-status.txt`),k);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:Xe(e.diagnosticReports,v);if(q(z(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),e.processDir&&H(e.processDir)){let t=z(_,`process`);U(t,{recursive:!0}),he(e.processDir,t,{recursive:!0})}let j=e.redact===!0;j&&zt({stagingDir:_,contentDir:t}),e.note&&q(z(_,`note.txt`),e.note);let M=null;e.scrubSecrets===!0&&(M=Dn(_));for(let t of e.extraFiles??[]){let e=t.zipName??L(t.sourcePath);if(!Q(t.sourcePath,z(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=ct(t,`extra/${e}`);n!==null&&(M??={redactions:[],redactedLineCount:0},M.redactions.push(n),M.redactedLineCount+=n.lineCount)}let N=_n(n),P=Sn(_),F=[],I=0,re=0;for(let e of P){let t=On(_,e),n=we(e).size,r=wn(t)?yn(e):0;F.push({path:t,bytes:n,lines:r}),I+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(re+=xn(e))}let ie={applied:j};M!==null&&(ie.secretScrub=M);let ae={schemaVersion:2,createdAt:d().toISOString(),ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O},contentDir:{pathSha256:vn(t),absolutePath:j?`<CONTENT_DIR>`:t},telemetry:{localSink:N,otlpPushEnabled:g()},redaction:ie,serverStatus:x,files:F};q(z(_,`manifest.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=Dt(t),se=P.some(e=>{try{let t=W(e,`utf-8`);return oe.some(e=>t.includes(e))}catch{return!1}}),ce={stagedDiagnosticReports:v,totalBytes:I,fileCount:F.length,docNameCount:re,contentDirVisible:se,redacted:j},le=!1;return{stagingDir:_,manifest:ae,summary:ce,cleanup:()=>{le||(le=!0,K(_,{recursive:!0,force:!0}))}}}catch(e){throw K(_,{recursive:!0,force:!0}),e}}async function An(e){let{collected:t,outputPath:n}=e,r=R(n);if(!H(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new wt.ZipFile,a=Sn(t.stagingDir);for(let e of a){let n=On(t.stagingDir,e);i.addFile(e,n)}i.end();let o=ge(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function jn(e,t){let n=z(e,`.ok`,`config.yml`);if(H(n))try{let t=(0,Ct.parse)(W(n,`utf-8`)),r=ce(t)?t.content:void 0,i=ce(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return B(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return B(e)}async function Mn(e,t,n,r,i){let a=lt(t,e.logger),o=await kn({contentDir:jn(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...pt(a,e.userLogsDir??z(S(),`logs`)),...ht(e.cachesDir??z(J(),`Library`,`Caches`))],userStateFiles:gt(e.bugReportsDir??Y()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{U(R(e.outputPath),{recursive:!0}),await An({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Nn(e){let{projectDir:t}=e,n=e.readDesktopEnv??ln,r=e.readLanguage??Et,i=()=>ot(e.diagnosticReportsDir??z(J(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Mn(e,t,n,r,i());let{zipPath:a,summary:o}=await St({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:ht(e.cachesDir??z(J(),`Library`,`Caches`)),bugReportLedgerFiles:gt(e.bugReportsDir??Y()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=w(e,t),i;try{i=W(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r}}let o=a&&typeof a==`object`?a:{},s=`machineId`in o&&typeof o.machineId==`string`?o.machineId!==(n.machineId??x()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??De());if(!a||typeof a!=`object`||!k(a.pid))return{status:`corrupt`,lockPath:r,...s?{foreignHost:!0}:{}};let c=a.pid,l=`machineId`in o&&typeof o.machineId==`string`||`hostname`in o&&typeof o.hostname==`string`;return s?{status:`foreign-host`,lockPath:r,lock:a}:(n.isAlive??M)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function Pn(e){return e.status===`unverified-owner`?`Cannot verify shutdown: the server lock at ${e.lockPath} does not record its owning machine, and its recorded process ${e.pid} is still running on this machine. Check whether process ${e.pid} is an OpenKnowledge server. If it is, stop it and retry. Do not remove the lock file while that process is running.`:`Cannot verify shutdown: the server lock at ${e.lockPath} belongs to another machine. Stop OpenKnowledge on the owning machine. Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it. Only then remove the stale lock file at ${e.lockPath} and retry cleanup.`}function Fn(e){return e.replace(/:\d+$/,``)}function In(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Fn(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Fn(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Fn(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const Ln=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function Rn(e){return r(c(),e)}function zn(){return s(c())}function Bn(){let e=c();if(e===`stable`)return Ln;let t=n(e);return RegExp(`^# >>> ${t} >>>\\n[\\s\\S]*?^# <<< ${t} <<<\\n?`,`m`)}const Vn={existsSync:e=>H(e),readFileSync:(e,t)=>W(e,t),lstatSync:e=>_e(e),readlinkSync:e=>xe(e)};function Hn(e,t=Vn){let n=Rn(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function Un(e){let t=e.replace(Bn(),``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function Wn(e,t,n=Vn){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const Gn=[{hostDir:`.adal`,pruneRoot:`.adal`},{hostDir:`.aider-desk`,pruneRoot:`.aider-desk`},{hostDir:`.astrbot/data`,pruneRoot:`.astrbot`},{hostDir:`.augment`,pruneRoot:`.augment`},{hostDir:`.autohand`,pruneRoot:`.autohand`},{hostDir:`.bob`,pruneRoot:`.bob`},{hostDir:`.codeartsdoer`,pruneRoot:`.codeartsdoer`},{hostDir:`.codebuddy`,pruneRoot:`.codebuddy`},{hostDir:`.codeium/windsurf`,pruneRoot:`.codeium`},{hostDir:`.codemaker`,pruneRoot:`.codemaker`},{hostDir:`.codestudio`,pruneRoot:`.codestudio`},{hostDir:`.commandcode`,pruneRoot:`.commandcode`},{hostDir:`.config/crush`,pruneRoot:`.config/crush`},{hostDir:`.config/devin`,pruneRoot:`.config/devin`},{hostDir:`.config/goose`,pruneRoot:`.config/goose`},{hostDir:`.config/kimchi/harness`,pruneRoot:`.config/kimchi`},{hostDir:`.continue`,pruneRoot:`.continue`},{hostDir:`.factory`,pruneRoot:`.factory`},{hostDir:`.forge`,pruneRoot:`.forge`},{hostDir:`.grok`,pruneRoot:`.grok`},{hostDir:`.iflow`,pruneRoot:`.iflow`},{hostDir:`.inferencesh`,pruneRoot:`.inferencesh`},{hostDir:`.jazz`,pruneRoot:`.jazz`},{hostDir:`.junie`,pruneRoot:`.junie`},{hostDir:`.kilocode`,pruneRoot:`.kilocode`},{hostDir:`.kiro`,pruneRoot:`.kiro`},{hostDir:`.kode`,pruneRoot:`.kode`},{hostDir:`.lingma`,pruneRoot:`.lingma`},{hostDir:`.mcpjam`,pruneRoot:`.mcpjam`},{hostDir:`.moxby`,pruneRoot:`.moxby`},{hostDir:`.mux`,pruneRoot:`.mux`},{hostDir:`.neovate`,pruneRoot:`.neovate`},{hostDir:`.ona`,pruneRoot:`.ona`},{hostDir:`.openhands`,pruneRoot:`.openhands`},{hostDir:`.pochi`,pruneRoot:`.pochi`},{hostDir:`.qoder`,pruneRoot:`.qoder`},{hostDir:`.qoder-cn`,pruneRoot:`.qoder-cn`},{hostDir:`.qwen`,pruneRoot:`.qwen`},{hostDir:`.reasonix`,pruneRoot:`.reasonix`},{hostDir:`.roo`,pruneRoot:`.roo`},{hostDir:`.rovodev`,pruneRoot:`.rovodev`},{hostDir:`.snowflake/cortex`,pruneRoot:`.snowflake`},{hostDir:`.tabnine/agent`,pruneRoot:`.tabnine`},{hostDir:`.terramind`,pruneRoot:`.terramind`},{hostDir:`.tinycloud`,pruneRoot:`.tinycloud`},{hostDir:`.trae`,pruneRoot:`.trae`},{hostDir:`.trae-cn`,pruneRoot:`.trae-cn`},{hostDir:`.vibe`,pruneRoot:`.vibe`},{hostDir:`.zcode`,pruneRoot:`.zcode`},{hostDir:`.zencoder`,pruneRoot:`.zencoder`}],Kn=[..._.map(e=>j[e]),`open-knowledge`];function qn(e){if(!fe(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=B(e);if(t===V||R(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function Jn(e,t){let n=pe(e,t);if(n.startsWith(`..`)||fe(n))return!1;let r=e;for(let e of n.split(V)){r=z(r,e);try{if(!_e(r).isDirectory())return!1}catch{return!1}}return!0}function Yn(e,t){try{return G(e).every(n=>t.has(z(e,n)))}catch{return!1}}function Xn(e){let t=qn(e),n=[],r=[],i=new Set;for(let e of Gn){let a=z(t,e.hostDir,`skills`);if(!Jn(t,a))continue;let o=Kn.map(e=>z(a,e)).filter(e=>H(e));n.push(...o);for(let e of o)i.add(e);let s=z(t,e.pruneRoot),c=a;for(;Yn(c,i)&&(r.push(c),i.add(c),c!==s);){let e=R(c);if(e===c||e===t||!e.startsWith(t+V))break;c=e}}return{skillDirs:n,emptyDirs:r}}function Zn(e){try{if(!_e(e).isDirectory())return!1;let t=G(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function Qn(e){let t=new Set,n=new Set;for(let r of Gn){let i=z(e,r.hostDir,`skills`);for(let e of Kn)t.add(z(i,e));let a=z(e,r.pruneRoot),o=i;for(;n.add(o),o!==a;){let t=R(o);if(t===o||t===e||!t.startsWith(e+V))break;o=t}}return{skillDirs:t,emptyDirs:n}}function $n(e,t){let n=qn(e),r=Qn(n),i=[...t.skillDirs.filter(e=>!r.skillDirs.has(e)),...t.emptyDirs.filter(e=>!r.emptyDirs.has(e))];if(i.length>0)throw Error(`refusing skill cleanup — ${i.length} path(s) outside the known legacy set: ${i.join(`, `)}`);let a=[];for(let e of t.skillDirs)if(Jn(n,e)&&Zn(e))try{K(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Jn(n,e))try{Ce(e),a.push(e)}catch{}return a}function er(e){let t=qn(e),n=[];for(let e of _){let r=j[e];n.push({path:z(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of d)n.push({path:z(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function tr(e,t){let n=[];for(let r of er(e))if(r.bundleId===t)try{K(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function nr(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function rr(e,t=Date.now()){if(e===null)return`—`;let n=Le(e,t);return n===`unknown`?`—`:n}function ir(e){let t=R(e);return L(e)===`local`&&L(t)===`.ok`?R(t):L(e)===`.ok`?t:null}function ar(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:ir(e),server:{port:null,status:t.status,pid:t.pid,startedAt:null,usage:null},ui:null,hostname:null,lockPath:t.lockPath,binary:null,command:null,isDesktop:!1};let i=t.lock,a=t.status===`alive`&&ne(i)?{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r}:null;return{directory:i.worktreeRoot,server:{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r},ui:a,hostname:i.hostname,lockPath:t.lockPath,binary:n==null?null:T(n),command:n,isDesktop:nr(n)}}function or(e){let t=e.server.status;switch(t){case`unverified-owner`:return`unverified`;case`alive`:return e.isDesktop?`desktop`:`running`;case`foreign-host`:return e.isDesktop?`desktop`:`foreign`;case`dead-pid`:return`stale`;default:return t}}const sr=new Set([`running`,`desktop`,`foreign`,`unverified`]);function cr(e){switch(e){case`running`:return Z.default.green(e);case`desktop`:return Z.default.blue(e);case`foreign`:return Z.default.cyan(e);case`unverified`:case`stale`:return Z.default.yellow(e)}}function lr(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ur(e){return`${lr(e.server.usage)} | ${lr(e.ui?.usage??null)}`}function dr(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function fr(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,dr(e),ur(e),or(e),String(e.server.pid),rr(e.server.startedAt),e.binary??`—`]),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=cr(or(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=Z.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
11
+ `)}async function pr(e={}){let t=e.discover??C,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??v,a=e.resolveUsage??y,o=await t(),s=[];for(let e of o){let t=n(e),r=ar(e,t,t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:a(t.lock.pid));r!=null&&s.push(r)}if(e.json){let e=s.map(e=>({...e,displayStatus:or(e)}));r(JSON.stringify(e,null,2));return}r(fr(e.all?s:s.filter(e=>sr.has(or(e)))))}function mr(){return new I(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale entries (foreign and unverified entries already show)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await pr({all:t.all===!0||e===`all`,json:t.json===!0})})}async function hr(e,t=oe()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=O(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500),redirect:`manual`});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function gr(e,t={}){return{targets:yr(e,t.isAlive??M)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function _r(e){try{return c()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function vr(e){let t=e.inspect??(()=>$(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??hr,o=e.logger??oe(),s=t(),c=gr(s,{isAlive:e.isAlive});if(c.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};let l=s.status===`alive`||s.status===`foreign-host`?s.lock.channel:void 0;if(e.force!==!0&&typeof l==`string`&&l.length>0){let t=e.selfChannel??_r(o);if(t!==void 0&&l!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${m(l)}. Stop it from that app or its CLI, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,holderChannel:l,selfChannel:t,pids:c.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:l}}}if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:c.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let u=[],d=[];for(let e of c.targets)try{n(e.pid,`SIGTERM`),u.push(e)}catch(t){d.push({target:e,error:t instanceof Error?t.message:String(t)})}return u.length>0&&r(`Stopped: ${u.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:u.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:d.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),d.length>0&&i(`Failed to stop: ${d.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:u,failed:d,hadTargets:!0}}function yr(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function br(e,t=M){let n=await C(),r=null;for(let i of n){let n=$(i,`server`);if(yr(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}async function xr(e,t){let n=await vr({lockDir:e,force:t});return(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1),n}function Sr(e,t,n={}){return t===0?`Nothing was running for ${e}, and no other open-knowledge servers are running.`:`Nothing was running for ${e}. ${t} other open-knowledge server${t===1?` is`:`s are`} running${n.listingFollows===!0?``:" — run `ok ps` to list them"}.`}async function Cr(e){let t=await C(),n=0;for(let r of t)r!==e&&yr($(r,`server`),M)&&n++;return n}function wr(e){return new I(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the enclosing project — run it from anywhere inside the project. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).option(`--force`,`Stop even when the server belongs to another OpenKnowledge app (Stable or Beta) or editor windows or agents are still connected to it`).action(async(t,n)=>{let r=n.force===!0,i=t.length===0?void 0:t.join(` `);if(i===void 0){e();let t=E(process.cwd()),n=await vr({lockDir:t,force:r,log:()=>{}});if(n.hadTargets){if(n.stopped.length>0){let e=n.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1)}else{let e=await Cr(t);console.log(Sr(process.cwd(),e,{listingFollows:e>0})),e>0&&await pr({})}return}if(i===`all`){let e=await C();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e)yr($(n,`server`),M)&&(await xr(n,r),t++);t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(i)){let e=Number.parseInt(i,10),t=await br(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await xr(t,r);return}let a=B(He(),i),o=E(a),s=[],c=await vr({lockDir:o,force:r,log:e=>s.push(e)});if((c.failed.length>0||c.declined!==void 0)&&(process.exitCode=1),c.hadTargets)for(let e of s)console.log(e);else console.log(Sr(a,await Cr(o)))})}export{He as A,ot as C,We as D,Ge as E,ze as M,qe as O,Y as S,Ue as T,$ as _,$n as a,An as b,er as c,Rn as d,zn as f,Pn as g,In as h,mr as i,Ve as j,Je as k,Ln as l,Un as m,vr as n,Xn as o,Hn as p,wr as r,tr as s,hr as t,Wn as u,Nn as v,Xe as w,st as x,kn as y};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-B1QSgyMJ.mjs";import"./src-BrQpMSWu.mjs";import"./init-B4K69pZS.mjs";import"./registry-probes-D6HyJ_8R.mjs";import"./start-CDnYOrHP.mjs";import{n as e}from"./loader-DZHqBHXr.mjs";import"./preview-BdmlMCtY.mjs";import"./repair-mcp-configs-CZSnWHtM.mjs";export{e as loadConfig};
@@ -1,5 +1,5 @@
1
- import{J as e,N as t,Y as n,Yu as r,b as i,i as a,rl as o}from"./md-manager-BGnqyqi1-DsBy1Dky.mjs";import{Qo as s,ds as c,es as l,hi as u,ii as d,ji as f,k as p,yi as m}from"./dist-BHg9XI3A.mjs";import{Ct as h,L as g,Tt as _,X as v,b as y,ut as b,wt as x,y as S,z as C}from"./init-C5n0LZMn.mjs";import{a as w,c as T,d as E,f as D,i as ee,n as O,o as k,p as A,r as j,s as M,t as N,u as P,y as te}from"./registry-probes-CjXFMEIZ.mjs";import{n as F}from"./constants-D7JQKPXh.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,resolve as B}from"node:path";import{existsSync as V,realpathSync as ne}from"node:fs";import{homedir as re,tmpdir as ie}from"node:os";import{rm as ae}from"node:fs/promises";import{setTimeout as oe}from"node:timers/promises";const se=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ce={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function le(e,t={}){let{login:n}=t,r=t._exec??I,i=H(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=U(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=U(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function H(e){return[`gh`,...se.filter(e)]}function U(e,t,n){for(let r of t)try{let t=e(r,n,ce).toString().trim();if(t.length>0)return t}catch{}}function W(e,t={}){let n=t._exec??I,r=H(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=U(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=ue(a,e);if(t)return t}let o=U(n,r,i);if(o!==void 0){let e=he(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ue(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const de=/Logged in to \S+ account (\S+) \(/,fe=/(?:Failed to log in to|Timeout trying to log in to) \S+/,pe=/^\s*-\s*Active account:\s*true\s*$/,me=/\u001b\[[0-9;]*m/g;function he(e){let t=[],n;for(let r of e.split(`
2
- `)){let e=r.replace(me,``),i=de.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(fe.test(e)){n=void 0;continue}n&&pe.test(e)&&(n.active=!0)}return t}const ge={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){c(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function _e(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}function ve(e,t,n,r,i){let a=v[e];try{let o=k(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&c(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),_e(o.kind)}catch(i){return c(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function ye(e,t,n){if(v[e].scope!==`global`)return q();if(n===`absent`)return ve(e,``,t.home,void 0,t.env);let r=(await y({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function be(e,t,n){let r=v[e].projectConfigPath?.(t.cwd);if(r===void 0)return q();if(n===`absent`)return ve(e,t.cwd,t.home,r,t.env);let i=S(v[e],t.cwd,ge,void 0,r);switch(i.action){case`written`:case`overwritten`:return{action:i.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function xe(e,t,n){let r=t.home??re();if(n===`absent`){let t=j(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=w(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function Se(e,t,n){if(n===`absent`){let n=g(v[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=C(v[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function Ce(e){return t=>{if(t.pathId===void 0)return Y();let n=r(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return ye(n.editor,e,t.desired);case`editor-project-config`:return be(n.editor,e,t.desired);case`editor-project-skill-root`:return Se(n.editor,e,t.desired);case`editor-user-skill-root`:return xe(n.editor,e,t.desired)}}}function we(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Te(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function Ee(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function De(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function Oe(e){if(e===`off`)return`off`;if(!o.test(e))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function ke(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Ae(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function je(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||ke(e.host))&&e.isTTY}function Me(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Ne(e){return Me(`--external-url`,e)}function Pe(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${p}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??ie,r=t.realpathFn??ne,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function $(e,t,n=e=>ae(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${p}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Fe(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Ie(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:x}=await import(`./dist-ByQ8IZXo.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?f(e.singleFile).canonicalFilePath:void 0,E=w?l(w):void 0,D=w?c(w):void 0,k,A=!1;if(E!==void 0){if(e.projectDir!==void 0){if(k=e.projectDir,!Q(k))throw new Z(k);o(u(k,`.ok`,`config.yml`))||y(k,E)}else k=h(E),A=!0}let j=async()=>{if(!(!A||k===void 0)){if(!Q(k)){S.warn({ephemeralProjectDir:k},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await ae(k,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:k},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},P=k;if(!C){if(!i&&!d(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-C21Kb5o_.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r}).outcomes.filter(e=>e.outcome!==`no-entry`&&e.outcome!==`canonical`&&e.outcome!==`repaired`&&e.outcome!==`foreign`);i.length>0&&S.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-Db5HnCXi.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let F=E??_(t,n);!C&&!o(F)&&(s(F,{recursive:!0}),S.info({contentDir:F},`Created content directory`));let I=te(),L=m(),R;try{{let e=v(k??n),t=Date.now(),r=await x(e);r!==`no-drain`&&S.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}R=await p({config:t,contentDir:F,projectDir:k??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:le,detectGhAccounts:W,tokenStore:I,embeddingsKeyStore:L,mcpTomlEditor:b(),...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>O(e,t),probePiAcpBridge:e=>T(e),ensurePiAcpBridge:(e,t)=>M(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:k??n,home:re(),env:process.env};return{probe:N(e),execute:Ce(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Fe(P===void 0?n:$(n,P),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}catch(e){throw await j(),e}let z=R.destroy,B=A?async()=>{try{await z()}finally{await j()}}:z;return{httpServer:R.httpServer,destroy:B,lockDir:R.lockDir,contentDir:F,port:R.port,ready:R.ready,degraded:R.degraded}}function Le(e,t,n=()=>s({absPath:l(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Re(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function ze(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Be(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Ve(r,o){let s=Le(r,o.singleFile),c=ze(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Pe(m);let h;try{h=e(process.env)}catch(e){throw e instanceof a&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=i(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=n(g),S=v??(_||b===void 0?[...x.bind]:[b]);Ae({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=o.externalUrl,E=n(i(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
3
- `)))}let D=o.port===void 0?void 0:Number(o.port),ee=h.overrides.find(e=>e.envVar===`PORT`)?.value,O=D??ee??s.server?.port,k=De({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:Ee}),A=k.dir;k.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let j;try{j=await Ie({config:s,cwd:m,host:C,port:O,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:t(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{},...o.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}catch(e){e instanceof X&&(console.error(f(e.message)),process.exit(1)),e instanceof Z&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-ByQ8IZXo.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),(e instanceof t.MissingOkConfigError||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),We(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await He({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>oe(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=Ue(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=Ge(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let M=!1,N=async e=>{if(M)return;M=!0;let[t,...n]=Be(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await j.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{N(`SIGINT`)}),process.once(`SIGTERM`,()=>{N(`SIGTERM`)});let P=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${j.port}`,te=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${j.port}`:void 0,I=P;console.log(l({name:`open-knowledge`,version:F,localUrl:I,networkUrl:te,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let L={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};j.ready.then(async()=>{if(j.degraded.length>0){console.log();for(let e of j.degraded){let t=L[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(je({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-CJogphTe.mjs`);e(I)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function He(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:u(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function Ue(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function We(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function Ge(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function Ke(e){return new h(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,Te).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,Oe).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Re).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new _(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new _(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new _(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Ne).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
1
+ import{J as e,N as t,Y as n,b as r,fl as i,i as a,id as o}from"./md-manager-BGnqyqi1-B1QSgyMJ.mjs";import{Qo as s,ds as c,es as l,hi as u,ii as d,ji as f,k as p,yi as m}from"./dist-DMhyZWXW.mjs";import{Ct as h,L as g,Tt as _,X as v,b as y,ut as b,wt as x,y as S,z as C}from"./init-B4K69pZS.mjs";import{a as w,c as T,d as E,f as D,i as ee,n as O,o as k,p as A,r as j,s as M,t as N,u as P,y as te}from"./registry-probes-D6HyJ_8R.mjs";import{n as F}from"./constants-CCYsBRvI.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,resolve as B}from"node:path";import{existsSync as V,realpathSync as ne}from"node:fs";import{homedir as re,tmpdir as ie}from"node:os";import{rm as ae}from"node:fs/promises";import{setTimeout as oe}from"node:timers/promises";const se=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ce={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function le(e,t={}){let{login:n}=t,r=t._exec??I,i=H(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=U(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=U(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function H(e){return[`gh`,...se.filter(e)]}function U(e,t,n){for(let r of t)try{let t=e(r,n,ce).toString().trim();if(t.length>0)return t}catch{}}function W(e,t={}){let n=t._exec??I,r=H(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=U(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=ue(a,e);if(t)return t}let o=U(n,r,i);if(o!==void 0){let e=he(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ue(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const de=/Logged in to \S+ account (\S+) \(/,fe=/(?:Failed to log in to|Timeout trying to log in to) \S+/,pe=/^\s*-\s*Active account:\s*true\s*$/,me=/\u001b\[[0-9;]*m/g;function he(e){let t=[],n;for(let r of e.split(`
2
+ `)){let e=r.replace(me,``),i=de.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(fe.test(e)){n=void 0;continue}n&&pe.test(e)&&(n.active=!0)}return t}const ge={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){c(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function _e(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}function ve(e,t,n,r,i){let a=v[e];try{let o=k(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&c(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),_e(o.kind)}catch(i){return c(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function ye(e,t,n){if(v[e].scope!==`global`)return q();if(n===`absent`)return ve(e,``,t.home,void 0,t.env);let r=(await y({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function be(e,t,n){let r=v[e].projectConfigPath?.(t.cwd);if(r===void 0)return q();if(n===`absent`)return ve(e,t.cwd,t.home,r,t.env);let i=S(v[e],t.cwd,ge,void 0,r);switch(i.action){case`written`:case`overwritten`:return{action:i.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function xe(e,t,n){let r=t.home??re();if(n===`absent`){let t=j(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=w(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function Se(e,t,n){if(n===`absent`){let n=g(v[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=C(v[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function Ce(e){return t=>{if(t.pathId===void 0)return Y();let n=o(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return ye(n.editor,e,t.desired);case`editor-project-config`:return be(n.editor,e,t.desired);case`editor-project-skill-root`:return Se(n.editor,e,t.desired);case`editor-user-skill-root`:return xe(n.editor,e,t.desired)}}}function we(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Te(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function Ee(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function De(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function Oe(e){if(e===`off`)return`off`;if(!i.test(e))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function ke(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Ae(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function je(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||ke(e.host))&&e.isTTY}function Me(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Ne(e){return Me(`--external-url`,e)}function Pe(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${p}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??ie,r=t.realpathFn??ne,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function $(e,t,n=e=>ae(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${p}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Fe(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Ie(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:x}=await import(`./dist-ObUBLmuL.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?f(e.singleFile).canonicalFilePath:void 0,E=w?l(w):void 0,D=w?c(w):void 0,k,A=!1;if(E!==void 0){if(e.projectDir!==void 0){if(k=e.projectDir,!Q(k))throw new Z(k);o(u(k,`.ok`,`config.yml`))||y(k,E)}else k=h(E),A=!0}let j=async()=>{if(!(!A||k===void 0)){if(!Q(k)){S.warn({ephemeralProjectDir:k},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await ae(k,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:k},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},P=k;if(!C){if(!i&&!d(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-CZSnWHtM.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r}).outcomes.filter(e=>e.outcome!==`no-entry`&&e.outcome!==`canonical`&&e.outcome!==`repaired`&&e.outcome!==`foreign`);i.length>0&&S.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json--_R-76cC.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let F=E??_(t,n);!C&&!o(F)&&(s(F,{recursive:!0}),S.info({contentDir:F},`Created content directory`));let I=te(),L=m(),R;try{{let e=v(k??n),t=Date.now(),r=await x(e);r!==`no-drain`&&S.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}R=await p({config:t,contentDir:F,projectDir:k??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:le,detectGhAccounts:W,tokenStore:I,embeddingsKeyStore:L,mcpTomlEditor:b(),...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>O(e,t),probePiAcpBridge:e=>T(e),ensurePiAcpBridge:(e,t)=>M(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:k??n,home:re(),env:process.env};return{probe:N(e),execute:Ce(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Fe(P===void 0?n:$(n,P),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}catch(e){throw await j(),e}let z=R.destroy,B=A?async()=>{try{await z()}finally{await j()}}:z;return{httpServer:R.httpServer,destroy:B,lockDir:R.lockDir,contentDir:F,port:R.port,ready:R.ready,degraded:R.degraded}}function Le(e,t,n=()=>s({absPath:l(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Re(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function ze(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Be(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Ve(i,o){let s=Le(i,o.singleFile),c=ze(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Pe(m);let h;try{h=e(process.env)}catch(e){throw e instanceof a&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=r(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=n(g),S=v??(_||b===void 0?[...x.bind]:[b]);Ae({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=o.externalUrl,E=n(r(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
3
+ `)))}let D=o.port===void 0?void 0:Number(o.port),ee=h.overrides.find(e=>e.envVar===`PORT`)?.value,O=D??ee??s.server?.port,k=De({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:Ee}),A=k.dir;k.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let j;try{j=await Ie({config:s,cwd:m,host:C,port:O,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:t(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{},...o.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}catch(e){e instanceof X&&(console.error(f(e.message)),process.exit(1)),e instanceof Z&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-ObUBLmuL.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),(e instanceof t.MissingOkConfigError||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),We(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await He({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>oe(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=Ue(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=Ge(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let M=!1,N=async e=>{if(M)return;M=!0;let[t,...n]=Be(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await j.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{N(`SIGINT`)}),process.once(`SIGTERM`,()=>{N(`SIGTERM`)});let P=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${j.port}`,te=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${j.port}`:void 0,I=P;console.log(l({name:`open-knowledge`,version:F,localUrl:I,networkUrl:te,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let L={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};j.ready.then(async()=>{if(j.degraded.length>0){console.log();for(let e of j.degraded){let t=L[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(je({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-B-7x1MTL.mjs`);e(I)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function He(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:u(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function Ue(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function We(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function Ge(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function Ke(e){return new h(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,Te).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,Oe).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Re).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new _(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new _(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new _(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Ne).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
4
4
  `),process.exit(2)),t.projectDir!==void 0&&t.singleFile===void 0&&(process.stderr.write(`error: option '--project-dir' requires '--single-file'
5
5
  `),process.exit(2)),t.mode===`app`){let e=[];if(t.port!==void 0&&e.push(`--port`),t.bind!==void 0&&e.push(`--bind`),t.only!==void 0&&e.push(`--only`),t.idleShutdown!==void 0&&e.push(`--idle-shutdown`),t.openBrowser===!1&&e.push(`--no-open-browser`),t.externalUrl!==void 0&&e.push(`--external-url`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=E(P());if(n.available){D({spawn:L},n);return}console.error(A(n.reason)),process.exit(1)}await Ve(n,t)})}export{Ge as C,W as D,le as E,Ke as S,Fe as T,ze as _,Ue as a,je as b,Q as c,Oe as d,Te as f,Le as g,He as h,Pe as i,We as l,we as m,X as n,Be as o,Ee as p,Ie as r,ke as s,Z as t,Ne as u,De as v,$ as w,Ae as x,Ve as y};
@@ -0,0 +1 @@
1
+ import{S as e,m as t,p as n,r}from"./start-CDnYOrHP.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.83.0-beta.6",
3
+ "version": "0.83.0-beta.7",
4
4
  "description": "Local-first, agent-friendly Markdown knowledge base with a cross-platform CLI and web editor",
5
5
  "keywords": [
6
6
  "knowledge-base",
@@ -65,10 +65,10 @@
65
65
  "@parcel/watcher": "^2.5.6"
66
66
  },
67
67
  "devDependencies": {
68
- "@inkeep/open-knowledge-app": "0.83.0-beta.6",
69
- "@inkeep/open-knowledge-core": "0.83.0-beta.6",
68
+ "@inkeep/open-knowledge-app": "0.83.0-beta.7",
69
+ "@inkeep/open-knowledge-core": "0.83.0-beta.7",
70
70
  "@inkeep/open-knowledge-native-config": "0.0.0",
71
- "@inkeep/open-knowledge-server": "0.83.0-beta.6",
71
+ "@inkeep/open-knowledge-server": "0.83.0-beta.7",
72
72
  "@types/node": "^24.7.0",
73
73
  "@types/proper-lockfile": "^4.1.4",
74
74
  "@types/yazl": "^3.3.1",
@@ -1 +0,0 @@
1
- import"./md-manager-BGnqyqi1-DsBy1Dky.mjs";var e=`0.83.0-beta.6`;const t=`config.yml`,n=e;export{n,t};