@inkeep/open-knowledge 0.83.1 → 0.83.2

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 (172) hide show
  1. package/dist/cli.mjs +71 -71
  2. package/dist/constants-BgiJo9Qd.mjs +1 -0
  3. package/dist/dist-B5T_Ng2N.mjs +2212 -0
  4. package/dist/dist-BECizC_o.mjs +1 -0
  5. package/dist/index.d.mts +19 -0
  6. package/dist/index.mjs +237 -234
  7. package/dist/{init-BCovADrd.mjs → init-Ds2rWcU4.mjs} +55 -55
  8. package/dist/init-iSUd1eOo.mjs +1 -0
  9. package/dist/{launch-json-removal-B9t9Mq8v.mjs → launch-json-removal-Bnud4UsB.mjs} +1 -1
  10. package/dist/loader-7sRaalsM.mjs +1 -0
  11. package/dist/{loader-BbuaTl8Z.mjs → loader-qjb32th5.mjs} +1 -1
  12. package/dist/{md-manager-BGnqyqi1-DsBy1Dky.mjs → md-manager-BGnqyqi1-CuKuFQ68.mjs} +155 -155
  13. package/dist/{open-browser-CJogphTe.mjs → open-browser-Br_Sqq7L.mjs} +1 -1
  14. package/dist/parse-worker.mjs +1 -1
  15. package/dist/{preview-BGuq_NIN.mjs → preview-8YAHDBa9.mjs} +1 -1
  16. package/dist/preview-B2P852PA.mjs +1 -0
  17. package/dist/public/assets/{AccountSection-BpY8fXau.js → AccountSection-DzGs1F6L.js} +1 -1
  18. package/dist/public/assets/{ActivityModeContent-B7SYD_oX.js → ActivityModeContent-Dp_4QTXE.js} +1 -1
  19. package/dist/public/assets/AddPropertiesButton-N5qX1cMO.js +2 -0
  20. package/dist/public/assets/{AgentDiffPane-DAIaj_6D.js → AgentDiffPane-BPQZT31V.js} +1 -1
  21. package/dist/public/assets/{AppMenubar-D7u5sV7t.js → AppMenubar-D69jeA80.js} +1 -1
  22. package/dist/public/assets/{AttachmentsSection-DL8roP-O.js → AttachmentsSection-D_2_w9Zq.js} +1 -1
  23. package/dist/public/assets/{BugReportHistory-BPO915fE.js → BugReportHistory-vkJJmJy4.js} +1 -1
  24. package/dist/public/assets/{BugReportHistoryDialog-CY6vlR_h.js → BugReportHistoryDialog-C3TJGSid.js} +1 -1
  25. package/dist/public/assets/{CodeMirrorPropInput-BWNyI9V2.js → CodeMirrorPropInput-DGOi_5YD.js} +67 -67
  26. package/dist/public/assets/{ConsentDialogBody-CGhUvR3J.js → ConsentDialogBody-DoUjdfGN.js} +1 -1
  27. package/dist/public/assets/{ContentRulesSection-h6pHMqD1.js → ContentRulesSection-ByQNDh2Z.js} +1 -1
  28. package/dist/public/assets/{DiffViewBoundary-B5VRWFoq.js → DiffViewBoundary-EV8QVf_2.js} +1 -1
  29. package/dist/public/assets/DocumentContext-CWlIZ6qH.js +108 -0
  30. package/dist/public/assets/{EditorModeToggle-rSAArExF.js → EditorModeToggle-B443ihFh.js} +1 -1
  31. package/dist/public/assets/{ExcalidrawDocEditor-DiIxuNaj.js → ExcalidrawDocEditor-D_p9RTAc.js} +1 -1
  32. package/dist/public/assets/FeedbackForm-Be6_tfFY.js +1 -0
  33. package/dist/public/assets/{ImageAttachments-ChGavHQ_.js → ImageAttachments-DUqpSTbQ.js} +1 -1
  34. package/dist/public/assets/{ImportSkillDialog-lPX3LQOm.js → ImportSkillDialog-D3DE1Mou.js} +1 -1
  35. package/dist/public/assets/{LinkPreviewsSection-mmAXSLtK.js → LinkPreviewsSection-DKlxZFAP.js} +1 -1
  36. package/dist/public/assets/{LintConfigEditor-BbhL2owO.js → LintConfigEditor-ISW_r5TW.js} +1 -1
  37. package/dist/public/assets/{LintingSection-CSM0_1QE.js → LintingSection-Y8PujMca.js} +1 -1
  38. package/dist/public/assets/ManagedArtifactProperties-BtzmYRxW.js +1 -0
  39. package/dist/public/assets/ManagedArtifactProperties-fxWYQdPN.js +1 -0
  40. package/dist/public/assets/{MermaidDocEditor-BQetPb3J.js → MermaidDocEditor-BYYuavWx.js} +1 -1
  41. package/dist/public/assets/{NetworkAccessSection-CJ0RJ37j.js → NetworkAccessSection-CNs2K_uP.js} +1 -1
  42. package/dist/public/assets/{OkignoreSection-B6lKSJGD.js → OkignoreSection-DJsgJ1Cy.js} +1 -1
  43. package/dist/public/assets/{ProjectTemplatesSection-Cf5bgyHk.js → ProjectTemplatesSection-DHnb0Yh6.js} +1 -1
  44. package/dist/public/assets/{PropertyDisplayRow-BxgncotE.js → PropertyDisplayRow-CPFXHPIR.js} +2 -2
  45. package/dist/public/assets/{PublishToGitHubDialog-BjLmDxVs.js → PublishToGitHubDialog-C6QscIBp.js} +1 -1
  46. package/dist/public/assets/ReportBugDialogBody-r-9QuNCJ.js +3 -0
  47. package/dist/public/assets/{ReportBugMenuTrigger-D2RpbMHk.js → ReportBugMenuTrigger-BfH054Js.js} +1 -1
  48. package/dist/public/assets/{SchemaConfigEditor-CL13boF8.js → SchemaConfigEditor-BP7b9ArG.js} +1 -1
  49. package/dist/public/assets/{SearchSection-D6cO9U0B.js → SearchSection-DThBwsH1.js} +1 -1
  50. package/dist/public/assets/{SessionsHost-BH4nUjR2.js → SessionsHost-UTfla6_J.js} +2 -2
  51. package/dist/public/assets/{SettingsDialogBody-DOlLSJng.js → SettingsDialogBody-Dzvpfy7X.js} +2 -2
  52. package/dist/public/assets/{ShareReceiveMissDialog-C4IgyZWj.js → ShareReceiveMissDialog-B7sdQx80.js} +1 -1
  53. package/dist/public/assets/{SharingSection-BvdibR47.js → SharingSection-Bjl_f8Kj.js} +1 -1
  54. package/dist/public/assets/{SkillEditBanner-B0ZxQBAN.js → SkillEditBanner-B9u6ym-U.js} +1 -1
  55. package/dist/public/assets/{SkillInstallMenu-BIs2wAUZ.js → SkillInstallMenu-C9d-4KPx.js} +1 -1
  56. package/dist/public/assets/{SkillOriginInline-Dr1zcAGa.js → SkillOriginInline-DL0IEln0.js} +1 -1
  57. package/dist/public/assets/{SkillToolbarControls-CnDExhdQ.js → SkillToolbarControls-Qxn7xafR.js} +1 -1
  58. package/dist/public/assets/{SkillsManagerSection-CiaThXM_.js → SkillsManagerSection-p2CbgR2n.js} +1 -1
  59. package/dist/public/assets/{SlidesPluginSection-Bk1073RP.js → SlidesPluginSection-gB_5IAe_.js} +1 -1
  60. package/dist/public/assets/SourceEditor-Oddu0PNx.js +1 -0
  61. package/dist/public/assets/{SpellingSettings-BAFQbL_s.js → SpellingSettings-CS8I6HPM.js} +1 -1
  62. package/dist/public/assets/SyncSection-BYcb6PKU.js +1 -0
  63. package/dist/public/assets/SyncStatusBadge-LthqWfcb.js +1 -0
  64. package/dist/public/assets/{TemplateRow-Bj4hpJ-E.js → TemplateRow-dLxfDAhr.js} +1 -1
  65. package/dist/public/assets/{TerminalSection-BIeBUi3Y.js → TerminalSection-7edNtzwB.js} +1 -1
  66. package/dist/public/assets/{TerminalWindowApp-D75W_nOD.js → TerminalWindowApp-DArVk2Kh.js} +1 -1
  67. package/dist/public/assets/{TextDocEditor-Dir-jZtA.js → TextDocEditor-BDtIQT6j.js} +1 -1
  68. package/dist/public/assets/{ThemePluginSection-CovSRzUr.js → ThemePluginSection-D5Xsrfh1.js} +1 -1
  69. package/dist/public/assets/{ThreadView-B5ZZtVV4.js → ThreadView-BhsSP99F.js} +4 -4
  70. package/dist/public/assets/{TimelineDiffPane-QDBoFYDb.js → TimelineDiffPane-CACvr8tQ.js} +1 -1
  71. package/dist/public/assets/{calendar-U3XIfpfI.js → calendar-B94KcaTl.js} +1 -1
  72. package/dist/public/assets/{card-BsBNZHzU.js → card-D4T5oWdu.js} +1 -1
  73. package/dist/public/assets/{comment-chips-C9FVyemH.js → comment-chips-DI_fKQNs.js} +3 -3
  74. package/dist/public/assets/{config-provider-ang-QnXf.js → config-provider-D70XncwM.js} +1 -1
  75. package/dist/public/assets/config-schema-HkuAlUPr.js +1 -0
  76. package/dist/public/assets/{doc-undo-manager-D4kt3rYd.js → doc-undo-manager-CUavhtIC.js} +1 -1
  77. package/dist/public/assets/{field-controls-DdO1Jfbb.js → field-controls-CMcq5Jlb.js} +1 -1
  78. package/dist/public/assets/field-controls-DKKqhoeX.js +1 -0
  79. package/dist/public/assets/index-CjaVQwM3.js +2205 -0
  80. package/dist/public/assets/{input-group-D_ozMCmW.js → input-group-CvtNBDpz.js} +1 -1
  81. package/dist/public/assets/{lint-config-client-D0TnXak8.js → lint-config-client-BIFdxWH9.js} +1 -1
  82. package/dist/public/assets/{lint-plugins-CT78JavG.js → lint-plugins-D2M6PNPb.js} +1 -1
  83. package/dist/public/assets/{markdown-lint-BKCKKMvW.js → markdown-lint-Db7OYKa3.js} +1 -1
  84. package/dist/public/assets/{markdownlint-rule-browser-CLiJDsUJ.js → markdownlint-rule-browser-DIzrHyA-.js} +1 -1
  85. package/dist/public/assets/messages-BWbZIq5T.js +1 -0
  86. package/dist/public/assets/messages-CL7wpXl4.js +1 -0
  87. package/dist/public/assets/messages-CPct3YoX.js +1 -0
  88. package/dist/public/assets/messages-CPfoTEKg.js +1 -0
  89. package/dist/public/assets/messages-CechMWab.js +1 -0
  90. package/dist/public/assets/messages-D8zhKCme.js +1 -0
  91. package/dist/public/assets/messages-DCkhcB_d.js +1 -0
  92. package/dist/public/assets/messages-DG8PRa3O.js +1 -0
  93. package/dist/public/assets/messages-DGcPY68T.js +1 -0
  94. package/dist/public/assets/messages-DcEt20Pz.js +1 -0
  95. package/dist/public/assets/messages-DqsADXD4.js +1 -0
  96. package/dist/public/assets/messages-Dsh6qqJA.js +1 -0
  97. package/dist/public/assets/messages-TOxTRDJi.js +1 -0
  98. package/dist/public/assets/pending-receive-nav-store-NzlLQlw9.js +1 -0
  99. package/dist/public/assets/{preferred-session-events-Ayg96deM.js → preferred-session-events-CFhOfdIO.js} +1 -1
  100. package/dist/public/assets/{progress-DK60f0xv.js → progress-GNGzCkUn.js} +4 -4
  101. package/dist/public/assets/{saved-themes-client-DQgpb_Nl.js → saved-themes-client-Ca_NArEp.js} +1 -1
  102. package/dist/public/assets/{schema-section-DShGMOyT.js → schema-section-BLVrck71.js} +1 -1
  103. package/dist/public/assets/{selection-context-ClNQPaFJ.js → selection-context-DNMN8INw.js} +1 -1
  104. package/dist/public/assets/{src-HUmS96mW.js → src-5ILnggAh.js} +1 -1
  105. package/dist/public/assets/typing-burst-detector-BKApx_-j.js +8 -0
  106. package/dist/public/assets/{uninstall-CHUB11SP.js → uninstall-DiWtr94N.js} +1 -1
  107. package/dist/public/assets/{use-activity-panel-DZWu1j8R.js → use-activity-panel-BlQKyExq.js} +1 -1
  108. package/dist/public/assets/{use-apply-config-language-cr1JKqWJ.js → use-apply-config-language-BFZvDUfA.js} +2 -2
  109. package/dist/public/assets/{use-installed-clis-4inF6O-n.js → use-installed-clis-Bc_o3IHZ.js} +2 -2
  110. package/dist/public/assets/{use-open-skill-DpJ_35HO.js → use-open-skill-B13nnCe2.js} +1 -1
  111. package/dist/public/assets/{use-terminal-enabled-VopbK1KQ.js → use-terminal-enabled-LhWLNeeB.js} +1 -1
  112. package/dist/public/assets/{use-timeline-entry-diff-DPE4FYBg.js → use-timeline-entry-diff-DQ_NzdXz.js} +1 -1
  113. package/dist/public/index.html +41 -41
  114. package/dist/public/uninstall.html +4 -4
  115. package/dist/registry-probes-MsEZ-ooi.mjs +17 -0
  116. package/dist/{removal-file-path-CA1EsHkE.mjs → removal-file-path-CPf54bQs.mjs} +1 -1
  117. package/dist/{repair-launch-json-CrXvLHAP.mjs → repair-launch-json-BMWk1OGD.mjs} +1 -1
  118. package/dist/{repair-mcp-configs-DSzqhiSN.mjs → repair-mcp-configs-2k3OjTM7.mjs} +1 -1
  119. package/dist/src-CHPaqKmY.mjs +14 -0
  120. package/dist/src-D7pYLNSF.mjs +1 -0
  121. package/dist/{start-BJjgwTqm.mjs → start-CiROTLiG.mjs} +3 -3
  122. package/dist/start-CtLC7354.mjs +1 -0
  123. package/package.json +4 -4
  124. package/dist/constants-BYOV-C2G.mjs +0 -1
  125. package/dist/dist-BHg9XI3A.mjs +0 -2198
  126. package/dist/dist-ByQ8IZXo.mjs +0 -1
  127. package/dist/init-CXmnCQgu.mjs +0 -1
  128. package/dist/loader-DaIoHbyS.mjs +0 -1
  129. package/dist/preview-DNxSFxNa.mjs +0 -1
  130. package/dist/public/assets/AddPropertiesButton-VyqVtzIN.js +0 -2
  131. package/dist/public/assets/DocumentContext-DxDNsrxc.js +0 -108
  132. package/dist/public/assets/FeedbackForm-n4cK_QGh.js +0 -1
  133. package/dist/public/assets/ManagedArtifactProperties-YaOwWUAx.js +0 -1
  134. package/dist/public/assets/ManagedArtifactProperties-uoCdZH2I.js +0 -1
  135. package/dist/public/assets/ReportBugDialogBody-CW-yLP7E.js +0 -3
  136. package/dist/public/assets/SourceEditor-3U1rZw1J.js +0 -1
  137. package/dist/public/assets/SyncSection-Ciu87ehb.js +0 -1
  138. package/dist/public/assets/SyncStatusBadge-CJXgXQeb.js +0 -1
  139. package/dist/public/assets/config-schema-CcRHTCTU.js +0 -1
  140. package/dist/public/assets/field-controls-DF8qjTLS.js +0 -1
  141. package/dist/public/assets/index-BCiCqT8R.js +0 -2205
  142. package/dist/public/assets/messages-B3fCTSsU.js +0 -1
  143. package/dist/public/assets/messages-B4LuE4Uj.js +0 -1
  144. package/dist/public/assets/messages-BE2Gn3RX.js +0 -1
  145. package/dist/public/assets/messages-BI2FOXv1.js +0 -1
  146. package/dist/public/assets/messages-BW-Cdt9C.js +0 -1
  147. package/dist/public/assets/messages-BvhAxQrI.js +0 -1
  148. package/dist/public/assets/messages-CTIWBL1W.js +0 -1
  149. package/dist/public/assets/messages-CWGa07Dg.js +0 -1
  150. package/dist/public/assets/messages-DWxo7VDJ.js +0 -1
  151. package/dist/public/assets/messages-Df0SITTo.js +0 -1
  152. package/dist/public/assets/messages-HU4oqbuE.js +0 -1
  153. package/dist/public/assets/messages-b7a1Syss.js +0 -1
  154. package/dist/public/assets/messages-viWmNfI1.js +0 -1
  155. package/dist/public/assets/pending-receive-nav-store-DVgbBI_j.js +0 -1
  156. package/dist/public/assets/typing-burst-detector-BeLp1KqP.js +0 -8
  157. package/dist/registry-probes-Bm4pqoc3.mjs +0 -17
  158. package/dist/src-CnLRA8A1.mjs +0 -1
  159. package/dist/src-DbgqTa1M.mjs +0 -11
  160. package/dist/start-DmTUxqZp.mjs +0 -1
  161. /package/dist/public/assets/{ChangedOutsideBadge-BB-SCUmw.js → ChangedOutsideBadge-Dzr-p6dI.js} +0 -0
  162. /package/dist/public/assets/{DeleteConfirmationDialog-DrwlL-Hc.js → DeleteConfirmationDialog-BXUDIZYO.js} +0 -0
  163. /package/dist/public/assets/{SkillCostValue-Bgy3wkjV.js → SkillCostValue-CFSdX7GQ.js} +0 -0
  164. /package/dist/public/assets/{SkillModeBanner-DaZYmbfZ.js → SkillModeBanner-DcxGGSM7.js} +0 -0
  165. /package/dist/public/assets/{alert-BY4HHcfV.js → alert-rmEQg7oS.js} +0 -0
  166. /package/dist/public/assets/{folder-config-api-bwKmZWh2.js → folder-config-api-hhckojyT.js} +0 -0
  167. /package/dist/public/assets/{format-Yv4YAHdV.js → format-INdUJq6M.js} +0 -0
  168. /package/dist/public/assets/{platform-labels-CtgIRyUl.js → platform-labels-C40lrxa6.js} +0 -0
  169. /package/dist/public/assets/{sortable.esm-DuJVOTXv.js → sortable.esm-k5B4BkZq.js} +0 -0
  170. /package/dist/public/assets/{textarea-qPZDtk8V.js → textarea-CWb90goJ.js} +0 -0
  171. /package/dist/public/assets/{use-skill-origin-Cv_S5gSq.js → use-skill-origin-Bmj-FzoM.js} +0 -0
  172. /package/dist/public/assets/{use-skill-targets-D-Tfz8TQ.js → use-skill-targets-CrrT8-Rv.js} +0 -0
@@ -0,0 +1,14 @@
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$d as t,Cl as n,H as r,Ic as i,Lc as a,Mc as o,Mu as s,U as c,W as l,ca as u,ff as d,if as f,l as p,lf as m,sa as ee,sf as h,u as te,uf as g,wl as _}from"./md-manager-BGnqyqi1-CuKuFQ68.mjs";import{Eo as v,Fi as y,Pi as b,Qo as x,Sa as S,Zn as C,_i as w,ai as T,di as E,dr as D,es as O,kt as k,m as A,ns as j,sr as M,ts as N,vi as P,wr as ne,xs as F,yi as re}from"./dist-B5T_Ng2N.mjs";import{t as ie}from"./yazl-BBz29IQN.mjs";import{Ct as I,ot as L,st as ae}from"./init-Ds2rWcU4.mjs";import{l as oe,x as se}from"./registry-probes-MsEZ-ooi.mjs";import{c as ce}from"./colors-r_owlCuY.mjs";import{t as le}from"./is-object-BGze3w87.mjs";import{n as ue}from"./constants-BgiJo9Qd.mjs";import"./loader-qjb32th5.mjs";import"./preview-8YAHDBa9.mjs";import{execFile as de,execSync as fe,spawnSync as pe}from"node:child_process";import{basename as R,dirname as z,isAbsolute as me,join as B,relative as he,resolve as V,sep as H,win32 as ge}from"node:path";import{closeSync as _e,cpSync as ve,createWriteStream as ye,existsSync as U,lstatSync as be,mkdirSync as W,mkdtempSync as xe,openSync as Se,readFileSync as G,readSync as Ce,readdirSync as K,readlinkSync as we,realpathSync as Te,rmSync as q,rmdirSync as Ee,statSync as De,writeFileSync as J}from"node:fs";import{arch as Oe,freemem as ke,homedir as Y,hostname as Ae,platform as je,release as Me,tmpdir as Ne,totalmem as Pe,type as Fe,uptime as Ie}from"node:os";import{readFile as Le,readdir as Re,stat as ze}from"node:fs/promises";import{createHash as Be}from"node:crypto";function Ve(e,t){let n=t.map(e=>[F(e),e]);for(let t of e){let e=F(t);if(e===null)continue;let r=n.find(([t])=>t===e);if(r!==void 0)return r[1]}}function He(e){let{override:t,storedPreference:n,preferenceList:r,supportedLocales:i}=e,a=e.autoDetectableLocales??i;if(t!==void 0){let e=Ve([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=Ve(r,a);return o===void 0?{locale:`en`,source:`fallback`}:{locale:o,source:`system`}}function Ue(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 We=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`audit`,`deinit`,`auth`]);function Ge(e,t,n=D){if(e!==void 0&&!We.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ke=null;function qe(e){Ke=e}function Je(){return Ke??process.cwd()}const Ye=`Open Knowledge`;function Xe(e={}){let t=e.platformName??process.platform,n=e.productName??h().productName;return L(t).join(ae({...e,platformName:t}),n)}function Ze(e={}){let t=e.platformName??process.platform,n=e.home??Y(),r=e.env??process.env,i=L(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,`${h().packageName.replaceAll(`/`,``)}-updater`)}function Qe(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 $e(e){let t=B(e,`state.json`);if(!U(t))return[];let n;try{n=JSON.parse(G(t,`utf-8`))}catch{return[]}return Qe(n)??[]}function et(e){let t=B(e,`state.json`);if(!U(t))return!1;try{return Qe(JSON.parse(G(t,`utf-8`)))!==null}catch{return!1}}const tt=8192;function nt(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 rt(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const it=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function at(e){return e.replace(it,`$1"[REDACTED-DEVICE-ID]"`)}function ot(e){return at(rt(e))}const st=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function ct(e){if(typeof e!=`string`)return null;let t=st.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 lt(e){let t=Se(e,`r`);try{let e=Buffer.alloc(tt),n=0,r=!1;for(;n<tt;){let i=Ce(t,e,n,tt-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{_e(t)}}function ut(e){try{let t=lt(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:ct(a)}}catch{return{kind:`unreadable`}}}function dt(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function ft(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=K(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=B(e,t.name),r;try{r=De(n).mtimeMs}catch{continue}if(r<i)continue;let c=ut(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!dt(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`}}const pt=`state/os-termination-evidence.json`,mt=6048e5,ht=/openknowledge/i,gt=Object.values(f).map(g);function _t(e={}){return(t,n)=>new Promise(r=>{try{de(t,n,{encoding:`utf8`,timeout:e.timeoutMs??15e3,maxBuffer:e.maxBuffer??16777216,windowsHide:!0},(e,t,n)=>{r({...vt(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function vt(e){return e===null?{status:0}:typeof e.code==`string`?{status:null,errorCode:e.code}:typeof e.code==`number`?{status:e.code}:e.killed===!0?{status:null,errorCode:`ETIMEDOUT`}:e.signal?{status:null,signal:e.signal}:{status:null}}function yt(e){if(e.errorCode!==void 0)return e.errorCode;if(e.signal!==void 0)return`signal ${e.signal}`;let t=(e.stderr.trim().split(`
2
+ `)[0]??``).replace(/\S*\/journal\/\S*/g,`<journal path>`).replace(/\b[0-9a-f]{32}\b/gi,`<id>`);return`exit ${e.status}${t===``?``:`: ${t}`}`}function bt(e,t,n){return{schemaVersion:1,platform:e,source:t,outcome:`none-in-window`,readFrom:n,windowDays:7,foreignIgnored:0,unparseable:0,droppedOverCap:0,events:[]}}function xt(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function St(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function Ct(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function wt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Tt(e,t){let n=t.indexOf(`
3
+ `);if(n===-1)return null;let r,i;try{r=wt(JSON.parse(t.slice(0,n))),i=wt(JSON.parse(t.slice(n+1)))}catch{return null}if(r===null||i===null||!Array.isArray(i.processes))return null;let a=[];for(let e of i.processes){let t=wt(e);t===null||typeof t.name!=`string`||!dt(t.name)||a.push({name:t.name,pid:Ct(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:Ct(t.rpages),lifetimeMaxPages:Ct(t.lifetimeMax)})}let o=ct(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:Ct(wt(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`&&dt(i.largestProcess),ownedProcesses:a}}async function Et(e,t){let n=bt(`darwin`,`macos-jetsam`,[B(e,`JetsamEvent-*.ips`)]),r;try{r=await Re(e)}catch(e){return xt(n,e.code??`unknown`)}let i=t.getTime()-mt,a=[];for(let t of r)if(/^JetsamEvent-.*\.ips$/.test(t))try{let{mtimeMs:n}=await ze(B(e,t));n>=i&&a.push({file:t,mtimeMs:n})}catch{n.unparseable+=1}a.sort((e,t)=>t.mtimeMs-e.mtimeMs),n.droppedOverCap=Math.max(0,a.length-50);for(let{file:t}of a.slice(0,50)){let r=null;try{r=Tt(t,await Le(B(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return St(n)}const Dt=[`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Out of memory|oom-kill|Killed process|Killed /|memory pressure`,`_TRANSPORT=kernel`,`+`,`_SYSTEMD_UNIT=systemd-oomd.service`],Ot=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/;function kt(e,t){if(e===`systemd-oomd`){let e=/^Killed (\S+)/.exec(t);if(e===null)return null;let n=e[1]?.split(`/`).pop()??``;return{origin:`systemd-oomd`,action:`oomd-kill`,pid:null,processName:null,unit:ht.test(n)?n:null,trigger:/swap used/.test(t)?`swap`:/memory pressure/.test(t)?`memory-pressure`:null}}if(e!==`kernel`)return null;let n=/Killed process (\d+) \(([^)]+)\)/.exec(t);if(n!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(n[1]),processName:n[2]??null,unit:null,trigger:null};let r=/task=([^,]+),pid=(\d+)/.exec(t);if(r!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(r[2]),processName:r[1]??null,unit:null,trigger:null};let i=/^(\S+) invoked oom-killer/.exec(t);return i===null?null:{origin:`kernel`,action:`oom-invoked`,pid:null,processName:i[1]??null,unit:null,trigger:null}}function At(e){let t=[],n=0,r=0;for(let i of e.split(`
4
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=Ot.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!ht.test(s)){n+=1;continue}let c=kt(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}async function jt(e){let t=bt(`linux`,`linux-journal`,[`journalctl ${Dt.join(` `)}`]),n=await e(`journalctl`,[...Dt]),r=n.status===1&&/^-- No entries --$/m.test(n.stdout);if(n.status!==0&&!r)return xt(t,yt(n));let i=At(n.stdout);return t.droppedOverCap=Math.max(0,i.events.length-50),t.events.push(...i.events.slice(-50)),t.foreignIgnored=i.foreignIgnored,t.unparseable=i.unparseable,/not seeing messages from other users/i.test(`${n.stdout}\n${n.stderr}`)&&(t.restrictedToCurrentUser=!0),St(t)}const Mt={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},Nt={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function Pt(e){return e===`System`?Mt:Nt}function Ft(e){let t=`System[(${Object.keys(Pt(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${mt}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${gt.map(e=>`Data='${e}'`).join(` or `)}]]`}function It(e){return[`qe`,e,`/q:${Ft(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function Lt(e){return ge.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function Rt(e){return e.replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}function zt(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function Bt(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>Rt(e[1]??``).trim())}function Vt(e,t){let n=Pt(e),r=[],i=0,a=0;for(let o of t.match(/<Event[\s>][\s\S]*?<\/Event>/g)??[]){let t=/<Provider\s+Name=['"]([^'"]+)['"]/.exec(o)?.[1],s=Number(/<EventID[^>]*>(\d+)<\/EventID>/.exec(o)?.[1]),c=/<TimeCreated\s+SystemTime=['"]([^'"]+)['"]/.exec(o)?.[1];if(t===void 0||!Number.isInteger(s)||c===void 0){a+=1;continue}if(n[s]!==t){i+=1;continue}let l=Bt(o,`Data`),u=Bt(o,`Name`),d=[...l,...u].some(e=>ht.test(e));if(e===`Application`&&!d){i+=1;continue}r.push({kind:`windows-event`,at:c,log:e,provider:t,eventId:s,mentionsOpenKnowledge:d,data:e===`Application`?l.filter(e=>e!==``&&!zt(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function Ht(e,t){let n=Lt(t),r=[`System`,`Application`],i=bt(`win32`,`windows-event-log`,r.map(e=>`${n} ${It(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,It(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${yt(t)}`);continue}let n=Vt(e,t.stdout);i.droppedOverCap+=Math.max(0,n.events.length-50),i.events.push(...n.events.slice(0,50)),i.foreignIgnored+=n.foreignIgnored,i.unparseable+=n.unparseable}return o.length===r.length?xt(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:St(i)}async function Ut(e={}){let t=e.platform??process.platform,n=e.runCommand??_t(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return Et(e.macosReportsDir??`/Library/Logs/DiagnosticReports`,r);case`linux`:return jt(n);case`win32`:return Ht(n,e.systemRoot??process.env.SystemRoot);default:return{...bt(t,null,[]),outcome:`unsupported`}}}const Wt={schemaVersion:1,outcome:`not-collected`};function Gt(e){return`${JSON.stringify(e??Wt,null,2)}\n`}const Kt={"macos-jetsam":`macOS low-memory reports`,"linux-journal":`system journal`,"windows-event-log":`Windows event logs`};function qt(e){let t=[`${e.windowDays}d`,`${e.events.length} kept`,`${e.foreignIgnored} other-process record(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&t.push(`${e.droppedOverCap} older dropped over cap`);let n=e.source?` from ${Kt[e.source]}`:``,r=e.unavailableReason?`, ${e.unavailableReason}`:``;return`${e.outcome}${n}${r} (${t.join(`; `)})`}function Jt(){return B(x(),`bug-reports`)}function Yt(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Jt(),r=`${t}-bugreport`,i=B(n,`${r}.zip`);for(let e=2;U(i);e+=1)i=B(n,`${r}-${e}.zip`);return i}function Xt(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function Zt(e,t){let n=B(e,`.ok`,`config.yml`);if(U(n))try{let e=G(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 U(B(e,`.ok`))?Be(`sha256`).update(V(e)).digest(`hex`).slice(0,12):null}function Qt(){let e={timestamp:new Date().toISOString(),platform:je(),osType:Fe(),osRelease:Me(),hostname:`[redacted]`,uptime:Ie(),freeMem:ke(),totalMem:Pe(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=fe(`sw_vers -productVersion 2>/dev/null`,v({encoding:`utf8`})).trim()}catch{}try{let t=B(__dirname,`..`,`..`,`package.json`);U(t)&&(e.okVersion=JSON.parse(G(t,`utf8`)).version)}catch{}return e}const $t=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function en(e){let t=R(e);return $t.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function tn(e,t){return on(e,t).files}const nn=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function rn(e,t=oe){let n=B(e,`${t}.ShipIt`);if(!U(n))return[];let r;try{r=K(n)}catch{return[]}return nn.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=>B(n,e.entry)))}function an(e){if(!U(e))return[];try{let t=new Map;for(let n of K(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=>B(e,t))}catch{return[]}}function on(e,t){if(!U(t))return{files:[],excludedByProjectSlug:0};let n=K(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>B(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(en),i=[],a=r.filter(t=>{try{return G(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=>!en(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function sn(e){let t=B(e,`.ok`,`local`);return U(t)?{files:[`server.lock`,`last-spawn-error.log`,i,o].map(e=>B(t,e)).filter(e=>U(e))}:{files:[]}}function cn(e){let t=B(e,`.ok`,`local`,`logs`);return U(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>B(t,e)).filter(e=>U(e))}:{files:[]}}function ln(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#${Be(`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 un(e){let t=e.revealDocNames?e.content:ln(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=G(t,`utf8`);un({zipfile:e.zipfile,name:`${e.prefix}/${R(t)}`,content:t.endsWith(`.ips`)?ot(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 dn(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??B(x(),`logs`),s=t.projectDir?Zt(t.projectDir,i):null;W(z(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=Qt();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=on(s,o),{files:d}=t.projectDir?sn(t.projectDir):{files:[]},{files:f}=t.projectDir?cn(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=G(e.sourcePath),n=`extra/${e.zipName??R(e.sourcePath)}`;v.addBuffer(t,n),g.push(n);let r=Xt(e,n);r!==null&&h.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&un({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/${R(e)}`)),b=g.filter(e=>y.has(e)),S=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:nt(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${S}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`),un({zipfile:v,name:pt,content:Gt(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:g,redactions:h});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/${R(e)}`)),D=g.filter(e=>E.has(e)),O=new Set((t.bugReportLedgerFiles??[]).map(e=>`${te}/${R(e)}`)),k=g.filter(e=>O.has(e)),A=s?g.filter(e=>e.startsWith(`logs/`)&&!en(e)&&!E.has(e)):[],j=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.`]:[],M=j.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...j]:[`Redaction was disabled for this bundle; file contents are unmodified.`],N=[`# Bug Report Bundle`,``,`Generated: ${w.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${w.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...A.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:`,...A.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}`),``]:[],...(t.osTerminationEvidence?.events.length??0)>0?[`Termination records: read from the operating system rather than written`,`by OpenKnowledge, covering the last 7 days, to explain an exit the app`,`could not record itself. On macOS: the memory-pressure (jetsam) reports`,`that list processes of this app, with each one's memory use and whether`,`it was killed. On Linux: kernel and systemd-oomd out-of-memory kills of`,`this app, as structured fields with the machine name, cgroup paths and`,`user id left out. On Windows: crash and hang records for this app with`,`file paths left out, plus the time of every shutdown, restart, power`,`loss and low-memory warning on the machine, whatever caused it:`,`- ${pt}`,``]:[],...k.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:`,...k.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.`,...j,``,`This bundle is safe to attach to a GitHub issue.`]:M].join(`
5
+ `);v.addBuffer(Buffer.from(N,`utf8`),`README.md`),v.end();let P=ye(r);return v.outputStream.pipe(P),await new Promise((e,t)=>{P.on(`close`,e),P.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 fn=s(),pn=e(ie(),1),Z=e(ce(),1);function mn(e){let t=j(`user`,e,e);return O({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function hn({home:e=Y(),env:t=process.env}={}){let r=mn(e),{override:i,preferenceList:a}=N(t),{locale:o,source:s}=He({override:i,storedPreference:r,supportedLocales:_,preferenceList:a,autoDetectableLocales:n});return{preference:r,locale:o,source:s,systemLanguages:a}}function gn(e){let t=new Set([e]);try{t.add(Te.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 _n(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yn(e,t){if(typeof e==`string`)return _n(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>yn(e,t));if(!vn(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=yn(i,t);return n}function bn(e,t){let n=G(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
6
+ `),i=n.split(`
7
+ `),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=yn(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
8
+ `)}\n`:a.join(`
9
+ `);J(e,o)}function xn(e,t){let n=G(e,`utf-8`);if(n.trim().length!==0)try{let r=yn(JSON.parse(n),t),i=n.endsWith(`
10
+ `)?`
11
+ `:``;J(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=_n(n,t.contentDirSpellings);r!==n&&J(e,r)}}function Sn(e,t){let n=G(e,`utf-8`),r=_n(n,t.contentDirSpellings);r!==n&&J(e,r)}function Cn(e){try{return K(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>B(e,t.name))}catch{return[]}}const wn=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function Tn(e){return/\.log\.\d+$/.test(e)}function En(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||Tn(e)}const Dn=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function On(e){let t={contentDirSpellings:gn(e.contentDir)};for(let n of Dn)for(let r of Cn(B(e.stagingDir,n)))En(r)?bn(r,t):r.endsWith(`.json`)?xn(r,t):Sn(r,t);for(let n of Cn(B(e.stagingDir,`state`))){let e=R(n);n.endsWith(`.jsonl`)?bn(n,t):wn.has(e)?xn(n,t):Sn(n,t)}}const kn=[`.ok`,`local`,`telemetry`],An=[`.ok`,`local`,`logs`],jn=[`.ok`,`local`,`loss-capture`],Mn=`spans-current.jsonl`,Nn=`spans-prev.jsonl`,Pn=`server-current.jsonl`,Fn=`server-prev.jsonl`,In=`loss-current.jsonl`,Ln=`loss-prev.jsonl`;function Rn(e){return B(e,...kn,Mn)}function zn(e){return B(e,...kn,Nn)}function Bn(e){return B(e,...An,Pn)}function Vn(e){return B(e,...An,Fn)}function Hn(e){return B(e,...jn,In)}function Un(e){return B(e,...jn,Ln)}const Wn=1e3;async function Gn(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(Wn)});return t.ok?await t.text():null}catch{return null}}async function Kn(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(Wn)});return t.ok?await t.text():null}catch{return null}}async function qn(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(Wn)});return t.ok?await t.text():null}catch{return null}}function Jn(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(`
12
+ `)}\n`:null}catch{return null}}function Yn(e){let t=B(e,`.git`,`ok`);if(!U(t))return null;let n=pe(`git`,[`-C`,t,`log`,`--oneline`,`-50`],v({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Xn(e){let t=B(e,`.git`,`ok`);if(!U(t))return null;let n=pe(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],v({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Zn(){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 Qn(){return{nodeVersion:process.version,platform:je(),arch:Oe()}}function $n(){return process.env.OTEL_SDK_DISABLED===`false`}function er(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tr(e){if(!U(e))return{};let t;try{t=(0,fn.parse)(G(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(!er(t))return{};let n=t.telemetry;if(!er(n))return{};let r=n.localSink;return er(r)?r:{}}function nr(e){return typeof e==`boolean`?e:void 0}function rr(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function ir(e){if(er(e))return rr(e.maxBytes)}function ar(e){let t=tr(j(`project`,e)),n=tr(j(`project-local`,e));return{enabled:nr(n.enabled)??nr(t.enabled)??!0,spansMaxBytes:ir(n.spans)??ir(t.spans)??52428800,logsMaxBytes:ir(n.logs)??ir(t.logs)??26214400}}function or(e){return Be(`sha256`).update(e).digest(`hex`)}function sr(e){let t=G(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const cr=[`"doc.name"`,`"docName"`];function lr(e){let t=G(e,`utf-8`),n=0;for(let e of cr){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Q(e,t){if(!U(e))return!1;try{return W(z(t),{recursive:!0}),e.endsWith(`.ips`)?J(t,ot(G(e,`utf-8`))):ve(e,t),!0}catch{return!1}}function ur(e){let t=[],n=e=>{let r=K(e,{withFileTypes:!0});for(let i of r){let r=B(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const dr=new Set([`.jsonl`]);function fr(e){let t=e.lastIndexOf(`.`);return t!==-1&&dr.has(e.slice(t))}const pr=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function mr(e){if(Tn(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&pr.has(e.slice(t))}function hr(e){let t=[];for(let n of ur(e)){let r=gr(e,n);if(!mr(r))continue;let{redacted:i,patterns:a,lineCount:o}=u(G(n,`utf-8`));a.length!==0&&(J(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function gr(e,t){return he(e,t).split(H).join(`/`)}async function _r(e){let t=V(e.contentDir),n=V(e.projectDir??e.contentDir),r=e.deps??{},s=r.fetchAgentPresence??Gn,c=r.fetchAgentEffects??Kn,l=r.fetchWatcherRecent??qn,u=r.readShadowHead??Yn,d=r.readCheckpointRefs??Xn,f=r.now??(()=>new Date),p=r.okVersion??(()=>ue),m=r.readDesktopEnv??Zn,ee=r.readLanguage??hn,h=r.readRuntime??Qn,g=r.isOtlpPushEnabled??$n,_=xe(B(Ne(),`ok-bundle-`));try{W(B(_,`telemetry`),{recursive:!0}),W(B(_,`logs`),{recursive:!0}),W(B(_,`state`),{recursive:!0}),Q(Rn(n),B(_,`telemetry`,Mn)),Q(zn(n),B(_,`telemetry`,Nn)),Q(Bn(n),B(_,`logs`,Pn)),Q(Vn(n),B(_,`logs`,Fn));for(let t of e.userLogFiles??[])Q(t,B(_,`logs`,R(t)));for(let t of e.userStateFiles??[])Q(t,B(_,te,R(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Q(t,B(_,`diagnostic-reports`,R(t)))&&(v+=1);let y=B(n,`.ok`,`local`),b=B(y,`server.lock`),x=`not-running`,S=`no server.lock`,C=null;if(U(b)){Q(b,B(_,`state`,`server.lock`));try{let e=G(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 s(C);e===null?S=`agent-presence endpoint at :${C} unreachable`:(J(B(_,`state`,`agent-presence.json`),e),x=`running`,S=``);let t=await c(C);t!==null&&J(B(_,`state`,`agent-effects.json`),t);let n=await l(C);if(n!==null){let e=Jn(n);e!==null&&J(B(_,`state`,`watcher-recent.jsonl`),e)}}let w=u(t);w!==null&&J(B(_,`state`,`shadow-head.txt`),w);let T=d(t);T!==null&&J(B(_,`state`,`checkpoint-refs.txt`),T),Q(Hn(n),B(_,`state`,In)),Q(Un(n),B(_,`state`,Ln)),Q(B(y,`last-spawn-error.log`),B(_,`state`,`last-spawn-error.log`)),Q(B(y,a),B(_,`state`,a)),Q(B(y,i),B(_,`state`,i)),Q(B(y,o),B(_,`state`,o));let E=h(),D=m(),O=ee(),k={ok:{version:p(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O}};J(B(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let A=x===`running`?`running
13
+ `:`not-running (${S})\n`;J(B(_,`state`,`server-status.txt`),A);let j=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:nt(e.diagnosticReports,v);if(J(B(_,`state`,`diagnostic-reports-status.txt`),`${j}\n`),J(B(_,pt),Gt(e.osTerminationEvidence)),e.processDir&&U(e.processDir)){let t=B(_,`process`);W(t,{recursive:!0}),ve(e.processDir,t,{recursive:!0})}let M=e.redact===!0;M&&On({stagingDir:_,contentDir:t}),e.note&&J(B(_,`note.txt`),e.note);let N=null;e.scrubSecrets===!0&&(N=hr(_));for(let t of e.extraFiles??[]){let e=t.zipName??R(t.sourcePath);if(!Q(t.sourcePath,B(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=Xt(t,`extra/${e}`);n!==null&&(N??={redactions:[],redactedLineCount:0},N.redactions.push(n),N.redactedLineCount+=n.lineCount)}let P=ar(n),ne=ur(_),F=[],re=0,ie=0;for(let e of ne){let t=gr(_,e),n=De(e).size,r=fr(t)?sr(e):0;F.push({path:t,bytes:n,lines:r}),re+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(ie+=lr(e))}let I={applied:M};N!==null&&(I.secretScrub=N);let L={schemaVersion:2,createdAt:f().toISOString(),ok:{version:p(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O},contentDir:{pathSha256:or(t),absolutePath:M?`<CONTENT_DIR>`:t},telemetry:{localSink:P,otlpPushEnabled:g()},redaction:I,serverStatus:x,files:F};J(B(_,`manifest.json`),`${JSON.stringify(L,null,2)}\n`);let ae=gn(t),oe=ne.some(e=>{try{let t=G(e,`utf-8`);return ae.some(e=>t.includes(e))}catch{return!1}}),se={stagedDiagnosticReports:v,totalBytes:re,fileCount:F.length,docNameCount:ie,contentDirVisible:oe,redacted:M},ce=!1;return{stagingDir:_,manifest:L,summary:se,cleanup:()=>{ce||(ce=!0,q(_,{recursive:!0,force:!0}))}}}catch(e){throw q(_,{recursive:!0,force:!0}),e}}async function vr(e){let{collected:t,outputPath:n}=e,r=z(n);if(!U(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new pn.ZipFile,a=ur(t.stagingDir);for(let e of a){let n=gr(t.stagingDir,e);i.addFile(e,n)}i.end();let o=ye(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 yr(e,t){let n=B(e,`.ok`,`config.yml`);if(U(n))try{let t=(0,fn.parse)(G(n,`utf-8`)),r=le(t)?t.content:void 0,i=le(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return V(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 V(e)}async function br(e,t,n,r,i,a){let o=Zt(t,e.logger),s=await _r({contentDir:yr(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...tn(o,e.userLogsDir??B(x(),`logs`)),...rn(e.cachesDir??B(Y(),`Library`,`Caches`))],userStateFiles:an(e.bugReportsDir??Jt()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{W(z(e.outputPath),{recursive:!0}),await vr({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function xr(e){let{projectDir:t}=e,n=e.readDesktopEnv??Zn,r=e.readLanguage??hn,i=()=>ft(e.diagnosticReportsDir??B(Y(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return br(e,t,n,r,i(),await Ut(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await dn({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:rn(e.cachesDir??B(Y(),`Library`,`Caches`)),bugReportLedgerFiles:an(e.bugReportsDir??Jt()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await Ut(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=re(e,t),i;try{i=G(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??ne()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??Ae());if(!a||typeof a!=`object`||!E(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??T)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function Sr(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 Cr(e){return e.replace(/:\d+$/,``)}function wr(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Cr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Cr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Cr(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 Tr=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function Er(e){return l(d(),e)}function Dr(){return c(d())}function Or(){let e=d();if(e===`stable`)return Tr;let t=r(e);return RegExp(`^# >>> ${t} >>>\\n[\\s\\S]*?^# <<< ${t} <<<\\n?`,`m`)}const kr={existsSync:e=>U(e),readFileSync:(e,t)=>G(e,t),lstatSync:e=>be(e),readlinkSync:e=>we(e)};function Ar(e,t=kr){let n=Er(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 jr(e){let t=e.replace(Or(),``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function Mr(e,t,n=kr){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const Nr=[{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`}],Pr=[...k.map(e=>A[e]),`open-knowledge`];function Fr(e){if(!me(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=V(e);if(t===H||z(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function Ir(e,t){let n=he(e,t);if(n.startsWith(`..`)||me(n))return!1;let r=e;for(let e of n.split(H)){r=B(r,e);try{if(!be(r).isDirectory())return!1}catch{return!1}}return!0}function Lr(e,t){try{return K(e).every(n=>t.has(B(e,n)))}catch{return!1}}function Rr(e){let t=Fr(e),n=[],r=[],i=new Set;for(let e of Nr){let a=B(t,e.hostDir,`skills`);if(!Ir(t,a))continue;let o=Pr.map(e=>B(a,e)).filter(e=>U(e));n.push(...o);for(let e of o)i.add(e);let s=B(t,e.pruneRoot),c=a;for(;Lr(c,i)&&(r.push(c),i.add(c),c!==s);){let e=z(c);if(e===c||e===t||!e.startsWith(t+H))break;c=e}}return{skillDirs:n,emptyDirs:r}}function zr(e){try{if(!be(e).isDirectory())return!1;let t=K(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function Br(e){let t=new Set,n=new Set;for(let r of Nr){let i=B(e,r.hostDir,`skills`);for(let e of Pr)t.add(B(i,e));let a=B(e,r.pruneRoot),o=i;for(;n.add(o),o!==a;){let t=z(o);if(t===o||t===e||!t.startsWith(e+H))break;o=t}}return{skillDirs:t,emptyDirs:n}}function Vr(e,t){let n=Fr(e),r=Br(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(Ir(n,e)&&zr(e))try{q(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Ir(n,e))try{Ee(e),a.push(e)}catch{}return a}function Hr(e){let n=Fr(e),r=[];for(let e of k){let i=A[e];r.push({path:B(n,`.agents`,`skills`,i),bundleId:e,scope:`central`});for(let a of t)r.push({path:B(n,a.skillsRoot,i),bundleId:e,scope:`host`,hostDir:a.hostDir})}return r}function Ur(e,t){let n=[];for(let r of Hr(e))if(r.bundleId===t)try{q(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 Wr(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Gr(e,t=Date.now()){if(e===null)return`—`;let n=Ue(e,t);return n===`unknown`?`—`:n}function Kr(e){let t=z(e);return R(e)===`local`&&R(t)===`.ok`?z(t):R(e)===`.ok`?t:null}function qr(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:Kr(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`&&w(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:M(n),command:n,isDesktop:Wr(n)}}function Jr(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 Yr=new Set([`running`,`desktop`,`foreign`,`unverified`]);function Xr(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 Zr(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Qr(e){return`${Zr(e.server.usage)} | ${Zr(e.ui?.usage??null)}`}function $r(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function ei(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??`—`,$r(e),Qr(e),Jr(e),String(e.server.pid),Gr(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=Xr(Jr(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(`
14
+ `)}async function ti(e={}){let t=e.discover??C,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??b,a=e.resolveUsage??y,o=await t(),s=[];for(let e of o){let t=n(e),r=qr(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:Jr(e)}));r(JSON.stringify(e,null,2));return}r(ei(e.all?s:s.filter(e=>Yr.has(Jr(e)))))}function ni(){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 ti({all:t.all===!0||e===`all`,json:t.json===!0})})}async function ri(e,t=se()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=P(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 ii(e,t={}){return{targets:si(e,t.isAlive??T)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function ai(e){try{return d()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function oi(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??ri,o=e.logger??se(),s=t(),c=ii(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??ai(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 si(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function ci(e,t=T){let n=await C(),r=null;for(let i of n){let n=$(i,`server`);if(si(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}async function li(e,t){let n=await oi({lockDir:e,force:t});return(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1),n}function ui(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 di(e){let t=await C(),n=0;for(let r of t)r!==e&&si($(r,`server`),T)&&n++;return n}function fi(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=S(process.cwd()),n=await oi({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 di(t);console.log(ui(process.cwd(),e,{listingFollows:e>0})),e>0&&await ti({})}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)si($(n,`server`),T)&&(await li(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 ci(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await li(t,r);return}let a=V(Je(),i),o=S(a),s=[],c=await oi({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(ui(a,await di(o)))})}export{$e as A,Ut as C,Ye as D,nt as E,Je as M,qe as N,Ze as O,Ge as P,Jt as S,ft as T,$ as _,Vr as a,vr as b,Hr as c,Er as d,Dr as f,Sr as g,wr as h,ni as i,et as j,Xe as k,Tr as l,jr as m,oi as n,Rr as o,Ar as p,fi as r,Ur as s,ri as t,Mr as u,xr as v,qt as w,Yt as x,_r as y};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-CuKuFQ68.mjs";import"./src-CHPaqKmY.mjs";import"./init-Ds2rWcU4.mjs";import"./registry-probes-MsEZ-ooi.mjs";import"./start-CiROTLiG.mjs";import{n as e}from"./loader-qjb32th5.mjs";import"./preview-8YAHDBa9.mjs";import"./repair-mcp-configs-2k3OjTM7.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-BCovADrd.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-Bm4pqoc3.mjs";import{n as F}from"./constants-BYOV-C2G.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-DSzqhiSN.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-CrXvLHAP.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{F as e,Qu as t,S as n,X as r,Z as i,i as a,ol as o}from"./md-manager-BGnqyqi1-CuKuFQ68.mjs";import{Ni as s,_i as c,es as l,k as u,ns as d,oi as f,ps as p,xi as m}from"./dist-B5T_Ng2N.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-Ds2rWcU4.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-MsEZ-ooi.mjs";import{n as F}from"./constants-BgiJo9Qd.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){p(`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&&p(`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 p(`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 n=>{if(n.pathId===void 0)return Y();let r=t(n.pathId);if(r===null||r.kind===`central-skill-store`)return Y();switch(r.kind){case`editor-user-config`:return ye(r.editor,e,n.desired);case`editor-project-config`:return be(r.editor,e,n.desired);case`editor-project-skill-root`:return Se(r.editor,e,n.desired);case`editor-user-skill-root`:return xe(r.editor,e,n.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 ${u}* 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 ${u}* 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:c}=await import(`node:fs`),{basename:l,dirname:u,resolve:d}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:x}=await import(`./dist-BECizC_o.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?s(e.singleFile).canonicalFilePath:void 0,E=w?u(w):void 0,D=w?l(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(d(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&&!f(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-2k3OjTM7.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-BMWk1OGD.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)&&(c(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=()=>l({absPath:d(`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(t,o){let s=Le(t,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=r(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=n(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=i(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=i(n(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:e(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-BECizC_o.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,m)){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-Br_Sqq7L.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:c(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,n){let r=t.ServerLockCollisionError;if(r!==void 0&&e instanceof r)return!0;let i=t.ServerAuthorityCollisionError;if(i===void 0||!(e instanceof i))return!1;try{return e.existing.scope.kind===`tree`&&ne.native(n)===e.existing.projectDir}catch{return!1}}function Ge(e,t,n){let r=n.ServerAuthorityCollisionError;if(r!==void 0&&e instanceof r)return e.message;let i=n.ServerAuthorityRegistryError;if(i!==void 0&&e instanceof i)return e.message;let a=n.ServerLockCollisionError;if(a===void 0||!(e instanceof a))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-CiROTLiG.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.1",
3
+ "version": "0.83.2",
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.1",
69
- "@inkeep/open-knowledge-core": "0.83.1",
68
+ "@inkeep/open-knowledge-app": "0.83.2",
69
+ "@inkeep/open-knowledge-core": "0.83.2",
70
70
  "@inkeep/open-knowledge-native-config": "0.0.0",
71
- "@inkeep/open-knowledge-server": "0.83.1",
71
+ "@inkeep/open-knowledge-server": "0.83.2",
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.1`;const t=`config.yml`,n=e;export{n,t};