@inkeep/open-knowledge 0.89.10-beta.0 → 0.89.10-beta.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 (156) hide show
  1. package/dist/{cli-DuTQpnfi.mjs → cli-BnM1FTDH.mjs} +39 -39
  2. package/dist/cli.mjs +1 -1
  3. package/dist/constants-naktyCmW.mjs +1 -0
  4. package/dist/{dist-CLk9BDyE.mjs → dist-B8fZrH3f.mjs} +521 -521
  5. package/dist/dist-SdORgRtG.mjs +1 -0
  6. package/dist/index.mjs +12 -12
  7. package/dist/{init-CXy1X9eP.mjs → init-DJpguwtL.mjs} +14 -14
  8. package/dist/init-Dczju_5i.mjs +1 -0
  9. package/dist/{launch-json-removal-B7vVCFBV.mjs → launch-json-removal-CIZKpvKa.mjs} +1 -1
  10. package/dist/{loader-BHK1kqxP.mjs → loader-Bmw0zjIb.mjs} +1 -1
  11. package/dist/loader-Cdc5oVnE.mjs +1 -0
  12. package/dist/{open-browser-DzU6eS0X.mjs → open-browser-shNCq6Jg.mjs} +1 -1
  13. package/dist/preview-BUx9kg8i.mjs +1 -0
  14. package/dist/{preview-DEG83Uxb.mjs → preview-Blybr0dr.mjs} +1 -1
  15. package/dist/public/assets/{AboutSection-Wga6ljal.js → AboutSection-PYOotN54.js} +1 -1
  16. package/dist/public/assets/{AccountSection-BqL4s6YP.js → AccountSection-BRDw6CDt.js} +1 -1
  17. package/dist/public/assets/{ActivityModeContent-C42kiKB-.js → ActivityModeContent-CKsbEQva.js} +1 -1
  18. package/dist/public/assets/{ActivityPanelDiffView-Btj__TNB.js → ActivityPanelDiffView-Drnt3eYg.js} +1 -1
  19. package/dist/public/assets/{AddPropertiesButton-D4OE9whB.js → AddPropertiesButton-DZRrywnM.js} +2 -2
  20. package/dist/public/assets/{AgentConnectionsSection-DL5G9vDr.js → AgentConnectionsSection-CHHCm3U2.js} +1 -1
  21. package/dist/public/assets/{AgentDiffPane-CDc5mtZ-.js → AgentDiffPane-Bye03tzm.js} +2 -2
  22. package/dist/public/assets/{AttachmentsSection-CRY017gc.js → AttachmentsSection-CaDpV2y1.js} +1 -1
  23. package/dist/public/assets/{AuthModal-BqAFZ5VD.js → AuthModal-DK7kzx8-.js} +1 -1
  24. package/dist/public/assets/{CodeMirrorEditor-UCMRAMCV-BjEQv2x_.js → CodeMirrorEditor-UCMRAMCV-JkGHBVVc.js} +1 -1
  25. package/dist/public/assets/{CodeMirrorPropInput-B3ERDnwN.js → CodeMirrorPropInput-Cmp5Nj4G.js} +75 -75
  26. package/dist/public/assets/{ConsentDialogBody-B20jtW8L.js → ConsentDialogBody-CvSKtIAi.js} +1 -1
  27. package/dist/public/assets/{ContentRulesSection-BZZ0uRpp.js → ContentRulesSection-XkfMUBZh.js} +1 -1
  28. package/dist/public/assets/{DiffViewBoundary-BCb7uBFd.js → DiffViewBoundary-Bpy3dZ0r.js} +1 -1
  29. package/dist/public/assets/DocumentContext-Wb9BCFqj.js +110 -0
  30. package/dist/public/assets/{EditorModeToggle-DTSzp44_.js → EditorModeToggle-DR-niAdL.js} +1 -1
  31. package/dist/public/assets/{ExcalidrawDocEditor-CEo-k4K-.js → ExcalidrawDocEditor-DJY9eTS-.js} +1 -1
  32. package/dist/public/assets/FeedbackForm-DeDUOHCF.js +1 -0
  33. package/dist/public/assets/{GraphPanel-epDsGADf.js → GraphPanel-an3G7Esa.js} +1 -1
  34. package/dist/public/assets/{HotkeysSection-DrZRSXKK.js → HotkeysSection-o4i2U9Lo.js} +1 -1
  35. package/dist/public/assets/{ImportSkillDialog-CyHoUxuA.js → ImportSkillDialog-CR2KplKg.js} +1 -1
  36. package/dist/public/assets/{InstallInClaudeDesktopDialog-C_RQYp3V.js → InstallInClaudeDesktopDialog-D4VEpFPf.js} +1 -1
  37. package/dist/public/assets/{IntegrationsSection-gn7Gi9_7.js → IntegrationsSection-DCIbejNW.js} +1 -1
  38. package/dist/public/assets/{LinkPreviewsSection-CO7oBdpg.js → LinkPreviewsSection-lEWtD5nf.js} +1 -1
  39. package/dist/public/assets/{LintConfigEditor-BLMM0YXw.js → LintConfigEditor-Cn47RFTz.js} +1 -1
  40. package/dist/public/assets/{LintingSection-CHxHEOFS.js → LintingSection-72S0YZjO.js} +1 -1
  41. package/dist/public/assets/ManagedArtifactProperties-BRgU2Iry.js +1 -0
  42. package/dist/public/assets/{ManagedArtifactProperties-CAW43s3B.js → ManagedArtifactProperties-Gc49zvuT.js} +1 -1
  43. package/dist/public/assets/{Mermaid-BcowK1bP.js → Mermaid-BiYl2hf6.js} +1 -1
  44. package/dist/public/assets/{MermaidDocEditor-w4VlJz4i.js → MermaidDocEditor-DbtN9U8A.js} +1 -1
  45. package/dist/public/assets/{MultiFileDiff-BsuBGl7q.js → MultiFileDiff-B2a-fkjz.js} +1 -1
  46. package/dist/public/assets/{NetworkAccessSection-sT8H1jm9.js → NetworkAccessSection-DLKSkggc.js} +1 -1
  47. package/dist/public/assets/{OkignoreSection-BfbduXqI.js → OkignoreSection-BsF3GbXc.js} +1 -1
  48. package/dist/public/assets/{PageListContext-DpKyZSYI.js → PageListContext-DG07q00l.js} +1 -1
  49. package/dist/public/assets/{ProjectTemplatesSection-D7kiwJKw.js → ProjectTemplatesSection-B6gvHBKM.js} +1 -1
  50. package/dist/public/assets/{PropertyDisplayRow-CR3oGERe.js → PropertyDisplayRow-DZZE9YrT.js} +1 -1
  51. package/dist/public/assets/{PublishToGitHubDialog-D5vpuxK-.js → PublishToGitHubDialog-CSba5_xA.js} +1 -1
  52. package/dist/public/assets/{SchemaConfigEditor-Bq_G5vOn.js → SchemaConfigEditor-Bf9lTi_e.js} +1 -1
  53. package/dist/public/assets/{SearchSection-DP2To-By.js → SearchSection-CXVxOouf.js} +1 -1
  54. package/dist/public/assets/{SessionsHost-CiBXwe8A.js → SessionsHost-BZm5V5lI.js} +2 -2
  55. package/dist/public/assets/{SettingsDialogBody-Wm7ffqsk.js → SettingsDialogBody-sklRpbsm.js} +2 -2
  56. package/dist/public/assets/{SettingsSectionHeader-DoDCqZE9.js → SettingsSectionHeader-EhpZ2oo5.js} +1 -1
  57. package/dist/public/assets/{ShareReceiveMissDialog-Biq8DZrB.js → ShareReceiveMissDialog-BIFE0grG.js} +1 -1
  58. package/dist/public/assets/{SharingSection-CmvBaP1e.js → SharingSection-DDRWca95.js} +1 -1
  59. package/dist/public/assets/{SkillForkDialog-3Q4qiLGp.js → SkillForkDialog-rG4DERkO.js} +1 -1
  60. package/dist/public/assets/{SkillInstallMenu-CgZ6TUtX.js → SkillInstallMenu-BNaUPGis.js} +1 -1
  61. package/dist/public/assets/{SkillOriginInline-XucbICfa.js → SkillOriginInline-ezRE9UzK.js} +2 -2
  62. package/dist/public/assets/{SkillPluginBundleDialog-9gvF1DrZ.js → SkillPluginBundleDialog-CQB8MF78.js} +1 -1
  63. package/dist/public/assets/{SkillToolbarControls-BUHQ4HKP.js → SkillToolbarControls-B_fHbGu4.js} +1 -1
  64. package/dist/public/assets/{SkillUpdateConflictDialog-BRuajj8h.js → SkillUpdateConflictDialog-CtyW6wPA.js} +1 -1
  65. package/dist/public/assets/{SkillsManagerSection-BKfHEWsE.js → SkillsManagerSection-DBEG1i7w.js} +1 -1
  66. package/dist/public/assets/{SlidesPluginSection-BpeI6naA.js → SlidesPluginSection-DqdmgP6_.js} +1 -1
  67. package/dist/public/assets/{SourceEditor-CYABPG6-.js → SourceEditor-Vu66CETo.js} +1 -1
  68. package/dist/public/assets/{SyncSection-B55HJey_.js → SyncSection-Coa6lFiE.js} +1 -1
  69. package/dist/public/assets/{SyncStatusBadge-D92whmoD.js → SyncStatusBadge-BW0YVl2z.js} +1 -1
  70. package/dist/public/assets/{TerminalPanel-CZqgzugj.js → TerminalPanel-CYqHKI2E.js} +3 -3
  71. package/dist/public/assets/{TerminalSection-Cot3kZ1b.js → TerminalSection-DaO8owbQ.js} +1 -1
  72. package/dist/public/assets/{TerminalWindowApp-Bk3GZdT3.js → TerminalWindowApp-BkoTZoiV.js} +1 -1
  73. package/dist/public/assets/{TextDocEditor-Cmjge0ed.js → TextDocEditor-C1S2Awhi.js} +1 -1
  74. package/dist/public/assets/{ThemePluginSection-CwqUh1BX.js → ThemePluginSection-CCAFe0bO.js} +1 -1
  75. package/dist/public/assets/{ThreadView-BdsRBXxP.js → ThreadView-BXAVZ8nY.js} +4 -4
  76. package/dist/public/assets/{TimelineDiffPane-Cmp2spQg.js → TimelineDiffPane-VOZs0FvZ.js} +2 -2
  77. package/dist/public/assets/{chunk-BO2N2NFS-Dl8M8LuR.js → chunk-BO2N2NFS-BEuwRDxJ.js} +4 -4
  78. package/dist/public/assets/{client-version-A-GxukuD.js → client-version-bdpMlJIw.js} +1 -1
  79. package/dist/public/assets/cm-theme-Cfku0s0U.js +3 -0
  80. package/dist/public/assets/{code-highlighter-impl-DAaUGe7G.js → code-highlighter-impl-B8pGTITV.js} +1 -1
  81. package/dist/public/assets/{comment-chips-CHaOUkXI.js → comment-chips-B_y1sjFe.js} +1 -1
  82. package/dist/public/assets/{config-provider-VNO-8pnC.js → config-provider-CIXp9Q30.js} +1 -1
  83. package/dist/public/assets/{dist-CUgGmlsn.js → dist-BLBhO77H.js} +1 -1
  84. package/dist/public/assets/{dist-DQuOA3vR.js → dist-Bz0NdQrJ.js} +1 -1
  85. package/dist/public/assets/{dist-CitzgyZk.js → dist-C8wn7WIc.js} +1 -1
  86. package/dist/public/assets/{dist-XOMICCBT.js → dist-Cqrno4UK.js} +1 -1
  87. package/dist/public/assets/{dist-R7QC_kjf.js → dist-D4SA-mVq.js} +1 -1
  88. package/dist/public/assets/{dist-CDI_AHNY2.js → dist-DkkpJ2aw.js} +1 -1
  89. package/dist/public/assets/{dist-DlTJY48Q.js → dist-dtIrts84.js} +1 -1
  90. package/dist/public/assets/{dist-LtbcyjB7.js → dist-wKKrgsd0.js} +1 -1
  91. package/dist/public/assets/{dist-oYievw6e.js → dist-yM-JiFXV2.js} +1 -1
  92. package/dist/public/assets/{doc-undo-manager-BKTm511k.js → doc-undo-manager-CmjnLvcY.js} +1 -1
  93. package/dist/public/assets/{engine-compile-BKhUOp9O.js → engine-compile-DCXqaKj1.js} +1 -1
  94. package/dist/public/assets/external-link-CV9ONfls.js +1 -0
  95. package/dist/public/assets/{highlighted-body-OFNGDK62-DsFROhgi.js → highlighted-body-OFNGDK62-BQg91IZ5.js} +1 -1
  96. package/dist/public/assets/{ime-composition-4cqEjrpI.js → ime-composition-B8fpGInz.js} +1 -1
  97. package/dist/public/assets/{index-C1ZPNUde.js → index-BusCRx2S.js} +8 -8
  98. package/dist/public/assets/{lib-CNBaznYe.js → lib-BFwLNStM.js} +1 -1
  99. package/dist/public/assets/{lint-plugins-B2-SsSEw.js → lint-plugins-CD7RVi0l.js} +1 -1
  100. package/dist/public/assets/{markdownlint-rule-browser-Ccvw_f-J.js → markdownlint-rule-browser-BH2pUfXz.js} +1 -1
  101. package/dist/public/assets/mermaid-GHXKKRXX-CTQTYtGv.js +1 -0
  102. package/dist/public/assets/{pending-receive-nav-store-dpOE8895.js → pending-receive-nav-store-4BSbHH4p.js} +1 -1
  103. package/dist/public/assets/{pierre-theme-Og_zQBPD.js → pierre-theme-bTg6dZWN.js} +1 -1
  104. package/dist/public/assets/{preferred-session-events-Hghttr98.js → preferred-session-events-ohIKavc3.js} +1 -1
  105. package/dist/public/assets/{prod-CxmLlnTC.js → prod-BYmgqcPA.js} +2 -2
  106. package/dist/public/assets/{progress-CZuFzG86.js → progress-lvv6PjMw.js} +1 -1
  107. package/dist/public/assets/{project-paths-DjS_hY_q.js → project-paths-BVP8z0Qv.js} +1 -1
  108. package/dist/public/assets/{schema-section-DDYszxnQ.js → schema-section-7rwc4iOl.js} +1 -1
  109. package/dist/public/assets/{selection-context-x0Smfuvg.js → selection-context-Ckxz0S9i.js} +1 -1
  110. package/dist/public/assets/{src-DbOdApPx.js → src-CRiK-e1l.js} +1 -1
  111. package/dist/public/assets/{tag-pill-input-C6vxVbIh.js → tag-pill-input-CAQxdwNs.js} +1 -1
  112. package/dist/public/assets/{telemetry-impl-BvyaF4rq.js → telemetry-impl-D8FtB48W.js} +1 -1
  113. package/dist/public/assets/{telemetry-startup-D9H-pijT.js → telemetry-startup-ROFmei1a.js} +1 -1
  114. package/dist/public/assets/{text-viewer-languages-5aC_46ro.js → text-viewer-languages-B5vCLX2f.js} +2 -2
  115. package/dist/public/assets/{typing-burst-detector-OTRAtOce.js → typing-burst-detector-DPuYxxMx.js} +1 -1
  116. package/dist/public/assets/{use-activity-panel-D_1FtfiY.js → use-activity-panel-Dyahk3Lt.js} +1 -1
  117. package/dist/public/assets/{use-open-skill-DJfSnwuI.js → use-open-skill-BhvW1NOZ.js} +1 -1
  118. package/dist/public/assets/{use-skill-origin-NWSdADZr.js → use-skill-origin-BsQ6pqNb.js} +1 -1
  119. package/dist/public/assets/{use-skill-targets-UEhNy--n.js → use-skill-targets-DdhJK0_S.js} +1 -1
  120. package/dist/public/assets/{use-terminal-enabled-BjIU3d8F.js → use-terminal-enabled-DDfs8VwB.js} +1 -1
  121. package/dist/public/assets/{use-timeline-entry-diff-DvwEPALr.js → use-timeline-entry-diff-BMLS3VzF.js} +1 -1
  122. package/dist/public/index.html +50 -50
  123. package/dist/{registry-probes-zHczfZFZ.mjs → registry-probes-D2Fcqx88.mjs} +7 -7
  124. package/dist/{removal-file-path-7-MdAEIS.mjs → removal-file-path-Dteeix7c.mjs} +1 -1
  125. package/dist/{repair-launch-json-BOfweiWp.mjs → repair-launch-json-CsiQ-Oie.mjs} +1 -1
  126. package/dist/{repair-mcp-configs-DIXgisAC.mjs → repair-mcp-configs-BsZ99LDP.mjs} +1 -1
  127. package/dist/src-22rYneLM.mjs +1 -0
  128. package/dist/src-CW3RhKEZ.mjs +16 -0
  129. package/dist/start-C1ERNfPu.mjs +5 -0
  130. package/dist/start-D90bHzUZ.mjs +1 -0
  131. package/package.json +4 -4
  132. package/dist/constants-C3jlSnWU.mjs +0 -1
  133. package/dist/dist-BNdZzjgr.mjs +0 -1
  134. package/dist/init-Bh7tibtK.mjs +0 -1
  135. package/dist/loader-CQOeIQS4.mjs +0 -1
  136. package/dist/preview-CBEyzv-I.mjs +0 -1
  137. package/dist/public/assets/DocumentContext-tjCBs5iM.js +0 -110
  138. package/dist/public/assets/FeedbackForm-JgP998Pr.js +0 -1
  139. package/dist/public/assets/ManagedArtifactProperties-CohT34HK.js +0 -1
  140. package/dist/public/assets/cm-theme-DHJ4FCK8.js +0 -3
  141. package/dist/public/assets/external-link-C6hldklD.js +0 -1
  142. package/dist/public/assets/mermaid-GHXKKRXX-CTq-e8f7.js +0 -1
  143. package/dist/src-CrS-edQZ.mjs +0 -16
  144. package/dist/src-k7CfDLlv.mjs +0 -1
  145. package/dist/start-CLJRdzjn.mjs +0 -5
  146. package/dist/start-CN8XT_VE.mjs +0 -1
  147. /package/dist/public/assets/{desktop-bridge-Btg3qpKV.js → desktop-bridge-bSzKDe_w.js} +0 -0
  148. /package/dist/public/assets/{dist-qfZ4Zkay.js → dist-BFBWje6D.js} +0 -0
  149. /package/dist/public/assets/{dist-B3l4eYse.js → dist-DJ9i_e8X.js} +0 -0
  150. /package/dist/public/assets/{dist-McVxqaQr.js → dist-yBmUFswj.js} +0 -0
  151. /package/dist/public/assets/{documents-fetch-aXwpCEvh.js → documents-fetch-BNA2S_EX.js} +0 -0
  152. /package/dist/public/assets/{lib-AgCVC0Wn.js → lib-C_jEl4A5.js} +0 -0
  153. /package/dist/public/assets/{page-list-cache-tOaID4O4.js → page-list-cache-BJpuIApf.js} +0 -0
  154. /package/dist/public/assets/{skills-api-MxDmjydw.js → skills-api-CcgOY0Iy.js} +0 -0
  155. /package/dist/public/assets/{startup-marks-iW0WPaQZ.js → startup-marks-D6zprGWE.js} +0 -0
  156. /package/dist/public/assets/{stex-BzLRGzOW.js → stex-7eUHyf61.js} +0 -0
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-DPpTSio4.mjs";import"./libesm-CSMdpGMF.mjs";import"./chunk-B74TABJS-DAm9lxFL.mjs";import"./chunk-R6VWJ2ZL-Cu1kOJ3f.mjs";import"./chunk-CWQS3NFK-Dma10iZG.mjs";import"./chunk-DXB73IDG-MLBj3lvC.mjs";import"./chunk-5QMZ5MUS-B37CnsNb.mjs";import"./chunk-A5O5YHGN-2_dxLAd1.mjs";import"./chunk-24IMIIXA-CZ-UxWg_.mjs";import{createRequire as a}from"node:module";import{execFile as o,execFileSync as s,execSync as c,spawnSync as l}from"node:child_process";import{access as u,accessSync as d,closeSync as f,constants as p,copyFileSync as m,cpSync as h,createWriteStream as g,existsSync as _,lstatSync as v,mkdirSync as y,mkdtempSync as b,openSync as x,readFile as S,readFileSync as C,readSync as w,readdirSync as T,readlinkSync as E,realpathSync as D,renameSync as O,rmSync as k,rmdirSync as A,statSync as ee,unlinkSync as te,writeFileSync as j}from"node:fs";import M,{basename as ne,dirname as N,extname as P,isAbsolute as re,join as F,normalize as ie,posix as I,relative as L,resolve as ae,sep as oe,win32 as se}from"node:path";import{EOL as ce,arch as R,availableParallelism as le,freemem as ue,homedir as de,hostname as fe,platform as pe,release as me,tmpdir as he,totalmem as ge,type as _e,uptime as ve}from"node:os";import{createHash as ye,randomUUID as be}from"node:crypto";import{mkdir as xe,readFile as Se,readdir as Ce,realpath as we,rename as Te,stat as Ee,writeFile as De}from"node:fs/promises";import Oe from"node:process";import{fileURLToPath as ke,fileURLToPath as Ae}from"node:url";import{isDeepStrictEqual as je,promisify as Me}from"node:util";import{Readable as Ne,Writable as Pe}from"node:stream";import Fe from"crypto";import"node:events";import"node:worker_threads";import{Readable as Ie}from"stream";import{setTimeout as Le}from"node:timers/promises";import{AsyncLocalStorage as Re}from"node:async_hooks";import"yjs";import{lookup as ze}from"node:dns";import{Http2ServerRequest as Be}from"node:http2";import{spawn as Ve}from"child_process";import"node:stream/promises";const He=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],Ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function We(e,t={}){let{login:n}=t,r=t._exec??s,i=Ge(t._fileExists??_),a=e?[`--hostname`,e]:[];if(n){let e=Ke(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=Ke(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function Ge(e){return[`gh`,...He.filter(e)]}function Ke(e,t,n){for(let r of t)try{let t=e(r,n,Ue).toString().trim();if(t.length>0)return t}catch{}}function qe(e,t={}){let n=t._exec??s,r=Ge(t._fileExists??_),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=Ke(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=Ye(a,e);if(t)return t}let o=Ke(n,r,i);if(o!==void 0){let e=et(o);if(e.length>0)return e}}function Je(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Ye(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=Je(Je(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=Je(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 Xe=/Logged in to \S+ account (\S+) \(/,Ze=/(?:Failed to log in to|Timeout trying to log in to) \S+/,Qe=/^\s*-\s*Active account:\s*true\s*$/,$e=/\u001b\[[0-9;]*m/g;function et(e){let t=[],n;for(let r of e.split(`
1
+ import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-DPpTSio4.mjs";import"./libesm-CSMdpGMF.mjs";import"./chunk-B74TABJS-DAm9lxFL.mjs";import"./chunk-R6VWJ2ZL-Cu1kOJ3f.mjs";import"./chunk-CWQS3NFK-Dma10iZG.mjs";import"./chunk-DXB73IDG-MLBj3lvC.mjs";import"./chunk-5QMZ5MUS-B37CnsNb.mjs";import"./chunk-A5O5YHGN-2_dxLAd1.mjs";import"./chunk-24IMIIXA-CZ-UxWg_.mjs";import{createRequire as a}from"node:module";import{execFile as o,execFileSync as s,execSync as c,spawnSync as l}from"node:child_process";import{access as u,accessSync as d,closeSync as f,constants as p,copyFileSync as m,cpSync as h,createWriteStream as g,existsSync as _,lstatSync as v,mkdirSync as y,mkdtempSync as b,openSync as x,readFile as S,readFileSync as C,readSync as w,readdirSync as T,readlinkSync as E,realpathSync as D,renameSync as O,rmSync as k,rmdirSync as A,statSync as ee,unlinkSync as te,writeFileSync as j}from"node:fs";import M,{basename as ne,dirname as N,extname as P,isAbsolute as re,join as F,normalize as ie,posix as I,relative as L,resolve as ae,sep as oe,win32 as se}from"node:path";import{EOL as ce,arch as R,availableParallelism as le,freemem as ue,homedir as de,hostname as fe,platform as pe,release as me,tmpdir as he,totalmem as ge,type as _e,uptime as ve}from"node:os";import{createHash as ye,randomUUID as be}from"node:crypto";import{mkdir as xe,readFile as Se,readdir as Ce,realpath as we,rename as Te,stat as Ee,writeFile as De}from"node:fs/promises";import Oe from"node:process";import{fileURLToPath as ke,fileURLToPath as Ae}from"node:url";import{isDeepStrictEqual as je,promisify as Me}from"node:util";import{Readable as Ne,Writable as Pe}from"node:stream";import Fe from"crypto";import{Readable as Ie}from"stream";import"node:events";import"node:worker_threads";import{setTimeout as Le}from"node:timers/promises";import{AsyncLocalStorage as Re}from"node:async_hooks";import"yjs";import{lookup as ze}from"node:dns";import{Http2ServerRequest as Be}from"node:http2";import{spawn as Ve}from"child_process";import"node:stream/promises";const He=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],Ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function We(e,t={}){let{login:n}=t,r=t._exec??s,i=Ge(t._fileExists??_),a=e?[`--hostname`,e]:[];if(n){let e=Ke(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=Ke(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function Ge(e){return[`gh`,...He.filter(e)]}function Ke(e,t,n){for(let r of t)try{let t=e(r,n,Ue).toString().trim();if(t.length>0)return t}catch{}}function qe(e,t={}){let n=t._exec??s,r=Ge(t._fileExists??_),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=Ke(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=Ye(a,e);if(t)return t}let o=Ke(n,r,i);if(o!==void 0){let e=et(o);if(e.length>0)return e}}function Je(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Ye(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=Je(Je(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=Je(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 Xe=/Logged in to \S+ account (\S+) \(/,Ze=/(?:Failed to log in to|Timeout trying to log in to) \S+/,Qe=/^\s*-\s*Active account:\s*true\s*$/,$e=/\u001b\[[0-9;]*m/g;function et(e){let t=[],n;for(let r of e.split(`
2
2
  `)){let e=r.replace($e,``),i=Xe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(Ze.test(e)){n=void 0;continue}n&&Qe.test(e)&&(n.active=!0)}return t}const tt={stable:{appId:`com.inkeep.open-knowledge`,productName:`OpenKnowledge`,packageName:`@inkeep/open-knowledge-desktop`,linuxExecutableName:`openknowledge`,protocolScheme:`openknowledge`,linuxPackageNames:{deb:`openknowledge`,rpm:`openknowledge`},retiredLinuxPackageNames:{deb:[],rpm:[`OpenKnowledge`]},cliCommandNames:[`ok`,`open-knowledge`],mcpServerName:`open-knowledge`,mcpChainTag:``,npmDistTag:`latest`,userHomeDirName:`.ok`,keyringService:`open-knowledge`},beta:{appId:`com.inkeep.open-knowledge.beta`,productName:`OpenKnowledge Beta`,packageName:`openknowledge-beta-desktop`,linuxExecutableName:`openknowledge-beta`,protocolScheme:`openknowledge-beta`,linuxPackageNames:{deb:`openknowledge-beta`,rpm:`openknowledge-beta`},retiredLinuxPackageNames:{deb:[`openknowledge-beta-desktop`],rpm:[`openknowledge-beta-desktop`]},cliCommandNames:[`ok-beta`,`open-knowledge-beta`],mcpServerName:`open-knowledge-beta`,mcpChainTag:`-beta`,npmDistTag:`beta`,userHomeDirName:`.ok-beta`,keyringService:`open-knowledge-beta`},dev:{appId:`com.inkeep.open-knowledge.dev`,productName:`OpenKnowledge Dev`,packageName:`openknowledge-dev-desktop`,linuxExecutableName:`openknowledge-dev`,protocolScheme:`openknowledge-dev`,linuxPackageNames:{deb:`openknowledge-dev`,rpm:`openknowledge-dev`},retiredLinuxPackageNames:{deb:[],rpm:[]},cliCommandNames:[`ok-dev`,`open-knowledge-dev`],mcpServerName:`open-knowledge-dev`,mcpChainTag:`-dev`,npmDistTag:`latest`,userHomeDirName:`.ok-dev`,keyringService:`open-knowledge-dev`}},nt=[`stable`,`beta`];function rt(e){return`${e.productName}.exe`}const it=tt.stable.productName,at=`OK_CHANNEL`;function ot(e){return Object.hasOwn(tt,e)}function st(e){return e.OK_CHANNEL?.trim().toLowerCase()||void 0}function ct(e=globalThis.process?.env??{}){return st(e)===`dev`}function eee(e){return e===`stable`?`${it} (Stable)`:ot(e)?tt[e].productName:`${it} (${e})`}function tee(e){return(e.split(/[\\/]/).pop()??``).replace(/\.exe$/i,``)}function lt(e=globalThis.process?.env??{},t=globalThis.process?.execPath??``){let n=st(e);if(n){if(ot(n))return n;throw Error(`Unsupported ${at}=${JSON.stringify(n)}. Expected ${Object.keys(tt).join(` or `)}.`)}let r=tee(t);for(let e of nt){if(e===`stable`)continue;let t=tt[e];if(r===t.linuxExecutableName||r===t.productName||r.startsWith(`${t.productName} `))return e}return`stable`}function ut(){return tt[lt()]}function dt(){return ut().mcpServerName}function ft(){return ut().cliCommandNames[0]}const pt=`node <checkout>/packages/cli/dist/cli.mjs`;function nee(e,...t){return[`~`,e.userHomeDirName,...t].join(`/`)}const mt=`local`,ht=[`principal.json`,`state.json`,`server.lock`,`ui.lock`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],gt=`auth.yml`,ree=[gt,`secrets.yml`],_t=[mt,`worktrees`],vt=[..._t,`cache`,`tmp`],yt=new Set(_t),bt=vt.filter(e=>!yt.has(e));function xt(...e){return nee(ut(),...e)}function St(e=de()){return F(e,ut().userHomeDirName)}const Ct=`.tmp.`,wt=[8,4,4,4,12];function iee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const aee=wt.map(e=>`[0-9a-f]`.repeat(e)).join(`-`),oee=wt.map(e=>`[0-9a-f]{${e}}`).join(`-`);`${aee}`,RegExp(`${iee(Ct)}${oee}$`);function see(e){return`${e}${Ct}${be()}`}function cee(e){try{let t=N(e),n=`${ne(e)}${Ct}`,r=Date.now()-3e4;for(let e of T(t)){if(!e.startsWith(n))continue;let i=F(t,e);try{ee(i).mtimeMs<r&&te(i)}catch{}}}catch{}}function Tt(e,t,n={}){cee(e);let r=see(e);try{j(r,t,{encoding:`utf-8`,mode:n.mode??420}),O(r,e)}catch(e){try{te(r)}catch{}throw e}}var Et=i((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Dt=i((e=>{var t=Et();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Ot=i((e=>{var t=Et(),n=Dt();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
3
3
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),kt=i((e=>{var t=Et(),n=Dt();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),At=i((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),jt=i((e=>{var t=Et();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),Mt=i((e=>{var t=At(),n=Et(),r=jt();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),Nt=i((e=>{var t=kt(),n=Dt(),r=Et(),i=Mt(),a=jt(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=s(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),Pt=i((e=>{var t=Et(),n=Mt(),r=jt();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),Ft=i((e=>{var t=Nt(),n=Et(),r=Pt();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),It=i((e=>{var t=Ft(),n=Et(),r=Mt();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),Lt=i((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
4
4
  `)?n(r,t):r.includes(`
@@ -1190,19 +1190,19 @@ n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(
1190
1190
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
1191
1191
  `)+`\r
1192
1192
  \r
1193
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));SIe(),S6(),C6(),T6(),wIe(),hf(),new Set(Mee);const E6={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(E6));const TIe=Object.keys(E6),EIe={discovery:`user`,project:`project`,"write-skill":`user`},D6=TIe.filter(e=>EIe[e]===`user`);new Set(D6.map(e=>E6[e]));const O6=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function k6(e){return new URL(e).pathname.endsWith(`.ts`)}function DIe(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??de(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(F(`/Applications`,O6,e)),(!s||n.home!==void 0)&&o.push(F(a,`Applications`,O6,e))),k6(t)?(o.push(ke(new URL(`../assets/skills/${e}`,t))),o):(o.push(ke(new URL(`../dist/assets/skills/${e}`,t))),o.push(ke(new URL(`../assets/skills/${e}`,t))),o.push(ke(new URL(`./assets/skills/${e}`,t))),o)}function OIe(e,t,n){let r=k6(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function A6(e,t={}){let n=DIe(e,import.meta.url,t);for(let e of n)if(_(e))return e;throw Error(OIe(e,import.meta.url,n))}function j6(e){let t=P(e).toLowerCase();return iu.includes(t)}function kIe(e){let t=e.toLowerCase();for(let n of iu)if(t.endsWith(n))return e.slice(0,-n.length);return e}const AIe={reconcileCount:0,conflictCount:0,reconcileInsertDedupSkipped:0,reconcileCheckFailed:0,reconcileConstructCheckSkipped:0,reconcileBothKept:0,reconcileBothKeptBlocks:0,reconcileKeptLive:0,mergeHistoryCheckpointCreated:0,mergeHistoryCheckpointFailures:0,mergeHistoryUnavailable:0,staleExternalWriteRefused:0,concurrentOverwriteRefused:0,batchCount:0,upstreamImportCount:0,persistenceStoreRemovedDocCount:0,persistenceStoreSupersededCount:0,rescueBufferCount:0,rescueCheckpointWriteFailures:0,rescueBufferWriteFailures:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,persistenceStalenessDetected:0,persistenceStalenessForcedStores:0,persistenceStalenessStoodDown:0,persistenceStalenessForceStoreTimeouts:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,shadowExcludeIndexEntriesDropped:0,shadowExcludeIndexSweepFailures:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,agentSessionEvictions:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceMemoHits:0,mapDrivenSpliceMemoSkips:{},mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,observerAResidualMergeSpliceLanded:0,observerAResidualMergeSpliceBlockedLossy:0,observerAResidualMergeSpliceUnavailable:{},observerADuplicationRederives:0,observerADuplicationCheckpointCreated:0,observerAApplyLoss:0,observerAApplyLossCheckpointCreated:0,deriveTimingDeferForceResolved:0,persistenceDeferHold:0,persistenceReconcileLoss:0,persistenceReconcileLossCheckpointCreated:0,persistenceReconcileLossDeduped:0,persistenceDuplicationReset:0,persistenceDuplicationResetCheckpointCreated:0,persistenceDuplicationResetDeduped:0,persistenceDuplicationSpared:0,persistenceDuplicationBaselineMissing:0,persistenceDuplicationBaselineRefusals:0,storeDiskCompare:{},storeDiskCompareReadRetries:0,storeRestatRefused:0,receiptIntakeSkip:{},receiptAtLoad:{},receiptPersistFailures:0,receiptRecordsUnreadable:0,receiptRecordsOtherVersion:0,receiptLogRefused:0,managedArtifactReconcile:0,managedArtifactReconcileCheckpointCreated:0,managedArtifactReconcileDeduped:0,managedArtifactMerge:{},enginelessStore:{},enginelessIntake:{},configOutsideChange:{},noEngineHistoryCheckpointCreated:0,noEngineHistoryCheckpointFailures:0,heldSaves:0,heldSaveRetries:0,heldSaveRetryFailures:0,displacedVersionBackups:0,displacedVersionBackupFailures:0,reDeriveBackstopTripped:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,diskAuthoritativeIngestCount:0,diskAuthoritativeIngestApplyFailures:0,diskAuthoritativeIngestUnrescuedCount:0,inFlightFlushExpired:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0,freshnessPasses:0,freshnessPassesIncomplete:0,freshnessFinds:0,freshnessFilesHashed:0,freshnessCarryOver:0,watcherErrors:0,watcherResubscribes:0,watcherRootMissing:0,watcherUnreadableEntries:0,inPlaceSkillRescanFailures:0,watcherResubscribesAbandoned:0,vanishPending:0,vanishPairedIdentity:0,vanishPairedHash:0,vanishRecreated:0,vanishDeleted:0,vanishShutdown:0,vanishUnconfirmed:0,outsideRenameRecordFailures:0,outsideRenameClaimFailures:0,branchSwitchRecheckShortfalls:0};function jIe(){AIe.inPlaceSkillRescanFailures++}function MIe(e){return e===`__system__`}const NIe=new Set(Zoe);function PIe(e){return NIe.has(e)}function FIe(e){return Qoe(e)}function IIe(e){return MIe(e)||PIe(e)||FIe(e)}const LIe=new Set;function M6(e){LIe.add(e)}function RIe(){return mf.getTracer(`open-knowledge-server`)}async function zIe(e,t,n){return RIe().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:uf.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}const BIe={stdio:[`ignore`,`pipe`,`pipe`]};function N6(e){return{...e,windowsHide:!0}}function VIe(e=ae(N(ke(import.meta.url)),`..`,`package.json`)){try{let t=JSON.parse(C(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}VIe();function HIe(e,t,n){let[r,i,a,...o]=process.argv.slice(1);(r===void 0||i===void 0||a===void 0)&&(process.stderr.write(`ok-browser relay: missing the folder, files or command argument
1193
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));SIe(),S6(),C6(),T6(),wIe(),hf();const TIe=new Set;function E6(e){TIe.add(e)}function EIe(){return mf.getTracer(`open-knowledge-server`)}async function DIe(e,t,n){return EIe().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:uf.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}const D6=W({name:z(),version:z().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});Ho([U(D6),G(z(),D6).transform(e=>Object.values(e))]).pipe(sae([D6])),new Set(Mee);const O6={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(O6));const OIe=Object.keys(O6),kIe={discovery:`user`,project:`project`,"write-skill":`user`},k6=OIe.filter(e=>kIe[e]===`user`);new Set(k6.map(e=>O6[e]));const A6=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function j6(e){return new URL(e).pathname.endsWith(`.ts`)}function AIe(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??de(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(F(`/Applications`,A6,e)),(!s||n.home!==void 0)&&o.push(F(a,`Applications`,A6,e))),j6(t)?(o.push(ke(new URL(`../assets/skills/${e}`,t))),o):(o.push(ke(new URL(`../dist/assets/skills/${e}`,t))),o.push(ke(new URL(`../assets/skills/${e}`,t))),o.push(ke(new URL(`./assets/skills/${e}`,t))),o)}function jIe(e,t,n){let r=j6(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function M6(e,t={}){let n=AIe(e,import.meta.url,t);for(let e of n)if(_(e))return e;throw Error(jIe(e,import.meta.url,n))}function N6(e){let t=P(e).toLowerCase();return iu.includes(t)}function MIe(e){let t=e.toLowerCase();for(let n of iu)if(t.endsWith(n))return e.slice(0,-n.length);return e}const NIe={reconcileCount:0,conflictCount:0,reconcileInsertDedupSkipped:0,reconcileCheckFailed:0,reconcileConstructCheckSkipped:0,reconcileBothKept:0,reconcileBothKeptBlocks:0,reconcileKeptLive:0,mergeHistoryCheckpointCreated:0,mergeHistoryCheckpointFailures:0,mergeHistoryUnavailable:0,staleExternalWriteRefused:0,concurrentOverwriteRefused:0,batchCount:0,upstreamImportCount:0,persistenceStoreRemovedDocCount:0,persistenceStoreSupersededCount:0,rescueBufferCount:0,rescueCheckpointWriteFailures:0,rescueBufferWriteFailures:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,persistenceStalenessDetected:0,persistenceStalenessForcedStores:0,persistenceStalenessStoodDown:0,persistenceStalenessForceStoreTimeouts:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,shadowExcludeIndexEntriesDropped:0,shadowExcludeIndexSweepFailures:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,agentSessionEvictions:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceMemoHits:0,mapDrivenSpliceMemoSkips:{},mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,observerAResidualMergeSpliceLanded:0,observerAResidualMergeSpliceBlockedLossy:0,observerAResidualMergeSpliceUnavailable:{},observerADuplicationRederives:0,observerADuplicationCheckpointCreated:0,observerAApplyLoss:0,observerAApplyLossCheckpointCreated:0,deriveTimingDeferForceResolved:0,persistenceDeferHold:0,persistenceReconcileLoss:0,persistenceReconcileLossCheckpointCreated:0,persistenceReconcileLossDeduped:0,persistenceDuplicationReset:0,persistenceDuplicationResetCheckpointCreated:0,persistenceDuplicationResetDeduped:0,persistenceDuplicationSpared:0,persistenceDuplicationBaselineMissing:0,persistenceDuplicationBaselineRefusals:0,storeDiskCompare:{},storeDiskCompareReadRetries:0,storeRestatRefused:0,receiptIntakeSkip:{},receiptAtLoad:{},receiptPersistFailures:0,receiptRecordsUnreadable:0,receiptRecordsOtherVersion:0,receiptLogRefused:0,managedArtifactReconcile:0,managedArtifactReconcileCheckpointCreated:0,managedArtifactReconcileDeduped:0,managedArtifactMerge:{},enginelessStore:{},enginelessIntake:{},configOutsideChange:{},noEngineHistoryCheckpointCreated:0,noEngineHistoryCheckpointFailures:0,heldSaves:0,heldSaveRetries:0,heldSaveRetryFailures:0,displacedVersionBackups:0,displacedVersionBackupFailures:0,reDeriveBackstopTripped:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,diskAuthoritativeIngestCount:0,diskAuthoritativeIngestApplyFailures:0,diskAuthoritativeIngestUnrescuedCount:0,inFlightFlushExpired:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0,freshnessPasses:0,freshnessPassesIncomplete:0,freshnessFinds:0,freshnessFilesHashed:0,freshnessCarryOver:0,watcherErrors:0,watcherResubscribes:0,watcherRootMissing:0,watcherUnreadableEntries:0,inPlaceSkillRescanFailures:0,watcherResubscribesAbandoned:0,vanishPending:0,vanishPairedIdentity:0,vanishPairedHash:0,vanishRecreated:0,vanishDeleted:0,vanishShutdown:0,vanishUnconfirmed:0,outsideRenameRecordFailures:0,outsideRenameClaimFailures:0,branchSwitchRecheckShortfalls:0};function PIe(){NIe.inPlaceSkillRescanFailures++}function FIe(e){return e===`__system__`}const IIe=new Set(Zoe);function LIe(e){return IIe.has(e)}function RIe(e){return Qoe(e)}function zIe(e){return FIe(e)||LIe(e)||RIe(e)}const BIe={stdio:[`ignore`,`pipe`,`pipe`]};function P6(e){return{...e,windowsHide:!0}}function VIe(e=ae(N(ke(import.meta.url)),`..`,`package.json`)){try{let t=JSON.parse(C(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}VIe();function HIe(e,t,n){let[r,i,a,...o]=process.argv.slice(1);(r===void 0||i===void 0||a===void 0)&&(process.stderr.write(`ok-browser relay: missing the folder, files or command argument
1194
1194
  `),process.exit(2));let s=new Set(n),c={roots:[{uri:t.pathToFileURL(i).href,name:`chat files`}]},l=e.spawn(a,o,{cwd:r,stdio:[`pipe`,`pipe`,`inherit`],windowsHide:!0}),u=l.stdin,d=l.stdout;(u===null||d===null)&&(process.stderr.write(`ok-browser relay: the browser server has no pipes
1195
1195
  `),process.exit(1));let f=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,p=e=>{u.write(`${JSON.stringify(e)}\n`)},m=e=>{process.stdout.write(`${JSON.stringify(e)}\n`)},h=(e,t)=>{process.stderr.write(`ok-browser relay: dropped a ${e} line that ${t}\n`)},g=(e,t,n)=>{if(e.trim()===``)return null;let r;try{r=JSON.parse(e)}catch{return h(t,`is not JSON`),null}let i=f(r);if(i!==null)return i;if(Array.isArray(r))for(let e of r){let t=f(e);t?.method!==void 0&&t.id!==void 0&&n({jsonrpc:`2.0`,id:t.id,error:{code:-32600,message:`Batched messages are not supported`}})}return h(t,`is not a single JSON-RPC message`),null},_=e=>{let t=g(e,`client`,m);if(t===null||t.method===`notifications/roots/list_changed`)return null;let n=f(t.params),r=n?.name;return t.method===`tools/call`&&(typeof r!=`string`||!s.has(r))?(t.id!==void 0&&m({jsonrpc:`2.0`,id:t.id,error:{code:-32602,message:`Tool ${String(r)} is not available`}}),null):(t.method===`initialize`&&n!==null&&(n.capabilities={...f(n.capabilities),roots:{listChanged:!1}}),JSON.stringify(t))},v=e=>{let t=g(e,`server`,p);if(t===null)return null;if(t.method===`roots/list`)return t.id!==void 0&&p({jsonrpc:`2.0`,id:t.id,result:c}),null;let n=f(t.result),r=n?.tools;if(n===null||!Array.isArray(r))return e;let i=r.filter(e=>{let t=f(e)?.name;return typeof t==`string`&&s.has(t)});for(let e of i){let t=f(f(e)?.annotations);t!==null&&(t.readOnlyHint=!1)}return n.tools=i,JSON.stringify(t)},y=(e,t,n,r)=>{let i=``,a=e=>{let r=n(e);r!==null&&t.write(`${r}\n`)};e.setEncoding(`utf8`),e.on(`data`,e=>{i+=String(e);let t=i.indexOf(`
1196
1196
  `);for(;t!==-1;)a(i.slice(0,t)),i=i.slice(t+1),t=i.indexOf(`
1197
- `)}),e.on(`end`,()=>{i!==``&&a(i),r&&t.end()})};u.on(`error`,()=>{}),y(process.stdin,u,_,!0),y(d,process.stdout,v,!1);for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process.on(e,()=>l.kill());l.on(`error`,e=>{process.stderr.write(`${e.message}\n`),process.exit(1)}),l.on(`close`,e=>{process.exitCode=e??1,process.stdin.destroy()})}const P6=W({name:z(),version:z().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});Ho([U(P6),G(z(),P6).transform(e=>Object.values(e))]).pipe(sae([P6])),`${HIe.toString()}${JSON.stringify([`browser_click`,`browser_close`,`browser_console_messages`,`browser_drag`,`browser_drop`,`browser_emulate_media`,`browser_evaluate`,`browser_file_upload`,`browser_fill_form`,`browser_find`,`browser_handle_dialog`,`browser_hover`,`browser_navigate`,`browser_navigate_back`,`browser_network_request`,`browser_network_requests`,`browser_press_key`,`browser_resize`,`browser_select_option`,`browser_snapshot`,`browser_tabs`,`browser_take_screenshot`,`browser_type`,`browser_wait_for`])}`;function F6(e){return e.replace(/\\/g,`/`)}function UIe(e,t={isAbsolute:re}){let n=F6(e);return n===`..`||n.startsWith(`../`)||t.isAbsolute(e)}function WIe(e){return ye(`sha256`).update(e).digest(`hex`)}_Y(`disk-receipts`),_Y(`directory-root`);const I6=_Y(`content-filter`);Me(o);const L6=[`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`],R6=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,...L6,`Library`,`Applications`,`.Trash`]),z6=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,...L6]),B6=new Set([`worktrees`,`local`]);function V6(e){return R6.has(e)||z6.has(e.toLowerCase())}const GIe=/^\.+(?:\/|$)/;function H6(e){return GIe.test(e)}function U6(e){return UIe(e)||H6(e)}function W6(e){let t=rd(e);if(!od(t))throw Error(`Invalid attachment folder path`);if(t===`./`)return{kind:`sibling`};if(t===`/`||t===`.`)return{kind:`content-root`};let n=t.startsWith(`./`),r=(n?t.slice(2):t).split(`/`).filter(e=>e!==``&&e!==`.`).map(hoe);return r.length===0?n?{kind:`sibling`}:{kind:`content-root`}:{kind:n?`doc-relative`:`fixed`,segments:r}}function G6(e,t,n){return n.every((n,r)=>n(e[t+r]??``))}function KIe(e){throw Error(`[AttachmentFolderShape] unhandled variant: ${JSON.stringify(e)}`)}function qIe(e,t,n){let r=P(e).slice(1).toLowerCase();if(!yu.has(r)||t.kind===`sibling`)return!1;let i=e.lastIndexOf(`/`),a=i===-1?``:e.slice(0,i);if(t.kind===`content-root`)return a===``;let o=a===``?[]:a.split(`/`);if(t.kind===`fixed`)return o.length>=t.segments.length&&G6(o,0,t.segments);if(t.kind===`doc-relative`){for(let e=0;e<=o.length-t.segments.length;e++)if(G6(o,e,t.segments)&&n(o.slice(0,e).join(`/`)))return!0;return!1}return KIe(t)}function K6(e,t){let n=e.split(`/`);for(let e=0;e<n.length;e++){let r=n[e].toLowerCase();if(z6.has(r)&&!(t&&r===`.ok`&&!B6.has((n[e+1]??``).toLowerCase())))return!0}return!1}function JIe(e){return K6(e)||e8(e)}function q6(e,t){return JIe(e.slice(t.length+1))}function J6(e){return e.startsWith(`.ok/skills/`)&&!q6(e,`.ok/skills`)}function YIe(e){return e===`.ok`||e===`.ok/skills`||J6(e)}const Y6=new Set([`.ok`,...L6]),XIe=new Set([...R6].filter(e=>!Y6.has(e))),ZIe=[`.git`,`node_modules`,`.ok/local`,`.ok/worktrees`].flatMap(e=>[e,`${e}/**`,`**/${e}`,`**/${e}/**`]);function QIe(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);return t.includes(`..`)?!1:t.some(e=>XIe.has(e))?!0:t.some((e,n)=>e.toLowerCase()===`.ok`&&B6.has((t[n+1]??``).toLowerCase()))}const $Ie=[`.gitignore`,`.ok`,`.ok/config.yml`,`.ok/.gitignore`,`.ok/schemas/frontmatter.json`,`.ok/templates/example.md`,`.ok/skills/example/SKILL.md`,`docs/.ok`,`docs/.ok/frontmatter.yml`,`docs/.ok/templates/example.md`,...L6.flatMap(e=>[e,`${e}/skills/example/SKILL.md`])];function eLe(e){let t=e.trim();if(!t||t.startsWith(`!`)||t.startsWith(`#`))return!1;let n=t.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);if(n.includes(`..`))return!0;if(QIe(t))return!1;if(n.some(e=>Y6.has(e)))return!0;try{let e=(0,AQ.default)().add(t);return $Ie.some(t=>e.ignores(t))}catch{return!0}}function tLe(e){let t=e.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!eLe(e));return[...new Set([...t,...ZIe])]}function X6(e,t){for(let n=0;n<t;n++)if(V6(e[n]))return!0;return!1}function Z6(e){let t=e.split(`/`),n=t.length;return n<3||t[n-3]!==`.ok`||t[n-2]!==`templates`||P(t[n-1])!==`.md`?!1:!X6(t,n-3)}function Q6(e){let t=e.split(`/`),n=t.length;return t[n-1]===`.ok`?!X6(t,n-1):n>=2&&t[n-1]===`templates`&&t[n-2]===`.ok`&&!X6(t,n-2)}function nLe(e){let t=e.split(`/`),n=t.length;return t[0]===`.ok`&&(n===2&&(t[1]===`config.yml`||t[1]===`.gitignore`)||n===3&&t[1]===`schemas`&&t[2].toLowerCase().endsWith(`.json`))||Z6(e)?!0:n>=2&&t[n-1]===`frontmatter.yml`&&t[n-2]===`.ok`&&!X6(t,n-2)}function rLe(e){return e===`.ok`||e===`.ok/schemas`||Q6(e)}function iLe(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}function $6(e,t){if(t.size===0)return!1;for(let n of t)if(e.startsWith(`${n}/`)&&!q6(e,n))return!0;return!1}function aLe(e,t){if(t.size===0)return!1;for(let n of t)if(n===e||n.startsWith(`${e}/`)||e.startsWith(`${n}/`)&&!q6(e,n))return!0;return!1}const oLe=new Set([`.ds_store`,`.localized`,`thumbs.db`,`desktop.ini`,`.directory`]);function e8(e){return oLe.has(e.slice(e.lastIndexOf(`/`)+1).toLowerCase())}const sLe=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function t8(e){for(let t of e.split(`/`))if(sLe.has(t.toLowerCase()))return!0;return!1}const cLe=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),lLe=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function n8(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||cLe.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of lLe)if(t.endsWith(e))return!0;return!1}function uLe(e,t){return t===e||t.startsWith(`${e}/`)}function dLe(e,t,n,r){let i=n===void 0,a=new Map;function o(e){let t=a.get(e);if(t!==void 0)return t;let n;try{n=vY(e)}catch{return!1}return a.set(e,n),n}return{isInside(n,a){if(!i||n===``)return!1;let s=a?.pathBase===`project`?e:t;if(r?.(ae(s,n)))return!0;let c=s;for(let e of n.split(`/`))if(c=F(c,e),o(c))return!0;return!1},reset(){a.clear()}}}const r8=[`.gitignore`,`.okignore`];function fLe(e,t){let n=pLe(e);if(n===null)return[];let r=[];i8(F(n,`info`,`exclude`),t,r,`info/exclude`);let i=mLe(e);return i&&i8(i,t,r,`global excludesfile`),r}function pLe(e){let t=l(`git`,[`rev-parse`,`--git-common-dir`],N6({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||!t.stdout?null:ae(e,t.stdout.trim())}function mLe(e){let t=l(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],N6({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return hLe()}function hLe(){let e=process.env.XDG_CONFIG_HOME?.trim(),t=e&&e.length>0?e:F(de(),`.config`);return F(t,`git`,`ignore`)}function i8(e,t,n,r){if(_(e))try{let r=C(e,`utf-8`);t.value+=r.length,n.push(...o8(r))}catch(t){I6.warn({path:e,err:t},`Failed to read ${r} at ${e}`)}}function gLe(){let e=!1;return{failed(t){jIe(),!e&&(e=!0,I6.warn({err:t},`in-place skill re-scan failed; the previous allow-list stays until a re-scan succeeds, and further failures are only counted`))},succeeded(){e&&(e=!1,I6.info({},`in-place skill re-scan works again`))}}}function _Le(e){let{projectDir:t,contentDir:n,onAfterRebuild:r,singleDocRelPath:i}=e,a=e.inPlaceSkillDirs??new Set,o=gLe(),s=W6(e.attachmentFolderPath??`./{{filename}}.assets`),c=e.skillRootPaths??new Set,l=dLe(t,n,i,e.isContentScopeExcluded),u=F6(L(t,n)),d=U6(u),f,p,m,h,g=0,v=0,y=0;function b(){let e=(0,AQ.default)(),r=(0,AQ.default)();e.add(`.git`);let i=[],a=0,o=0;for(let n of r8){let o=F(t,n);if(_(o))try{let t=C(o,`utf-8`);a+=t.length;let s=o8(t);i.push(...s),e.add(s),n===`.okignore`&&r.add(s)}catch(e){I6.warn({path:o,err:e},`Failed to read ${n} at ${o}`)}}if(u&&!d)for(let t of r8){let i=F(n,t);if(_(i))try{let n=C(i,`utf-8`);a+=n.length,o++;let s=o8(n).map(e=>s8(e,u));e.add(s),t===`.okignore`&&r.add(s)}catch(e){I6.warn({path:i,err:e},`Failed to read ${t} at ${i}`)}}let s={value:a};o+=c8(n,t,e,r,s),a=s.value;let c=fLe(t,s);a=s.value,c.length>0&&(i.push(...c),e.add(c));let l=tLe(i);return f=e,p=r,m=i,h=l,g=i.length,v=o,y=a,{patternCount:g,nestedFileCount:v,bytes:y}}b();let x=new Map;function S(e,t){if(d&&t?.pathBase!==`project`)return!1;let n=t?.pathBase===`project`||!u?e:`${u}/${e}`;return!H6(n)&&f.ignores(n)}function w(e,t){return t.pathBase===`project`||!u?e:`${u}/${e}`}function T(e){if(d)return!1;let t=u?`${u}/${e}`:e;return!H6(t)&&p.ignores(t)}let E=()=>{i===void 0&&a8(n,``,S,x)};E();function D(e){return IIe(kIe(e))}function O(e){for(let t of e.split(`/`))if(V6(t))return!0;return!d&&S(e)}let k=null,A=null;return{isExcluded(e,t){if(D(e)||n8(e)||t8(e)||l.isInside(e,t?.syncScope)||!t?.bypassFilters&&iLe(e,c)&&!$6(e,a))return!0;if(!t?.bypassFilters&&(J6(e)||$6(e,a)&&!S(e))){if(i!==void 0)return e!==i;if(j6(e))return!1;let t=P(e).slice(1).toLowerCase();return!yu.has(t)}if(!t?.bypassFilters&&Z6(e)||!t?.bypassFilters&&t?.syncScope!==void 0&&nLe(w(e,t.syncScope))&&!S(e,t.syncScope))return i!==void 0&&e!==i;if(K6(e,t?.showOk)||e8(e))return!0;if(i!==void 0)return e!==i;if(t?.bypassFilters)return t.respectOkignore===!0&&T(e);if(O(e))return!0;if(j6(e)||qIe(e,s,e=>(x.get(e)??0)>0))return!1;let n=P(e).slice(1).toLowerCase();if(yu.has(n)){let t=N(e),n=t===`.`?``:t;if((x.get(n)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t8(e)||l.isInside(e,t?.syncScope))return!0;if(!t?.bypassFilters&&(YIe(e)||Q6(e)||t?.syncScope!==void 0&&rLe(w(e,t.syncScope))||aLe(e,a)))return!1;if(K6(e,t?.showOk))return!0;if(i!==void 0)return!uLe(e,i);if(t?.bypassFilters)return t.respectOkignore===!0&&(T(e)||T(`${e}/`));for(let t of e.split(`/`))if(V6(t))return!0;return d?!1:S(e,t?.syncScope)||S(`${e}/`,t?.syncScope)},isPathIgnored(e,t){return D(e)||n8(e)||t8(e)?!0:J6(e)||$6(e,a)&&!S(e)||Z6(e)?!1:K6(e)||e8(e)?!0:!t?.bypassFilters&&O(e)},isExcludedByIgnoreFiles(e){return e.split(`/`).some(V6)||d?!1:S(e)},getWatcherIgnoreGlobs(){return h},incrementMdDir(e){let t=e===`.`?``:e;x.set(t,(x.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=x.get(t)??0;n<=1?x.delete(t):x.set(t,n-1)},rebuildDirCount(){let e=new Map(x);x.clear();try{E()}catch(t){for(let[t,n]of e)x.set(t,n);I6.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},setAttachmentFolderPath(e){s=W6(e)},refreshInPlaceSkillDirs(){if(e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a),o.succeeded()}catch(e){o.failed(e)}},inPlaceSkillDirsFingerprint(){return[...a].sort().join(`
1197
+ `)}),e.on(`end`,()=>{i!==``&&a(i),r&&t.end()})};u.on(`error`,()=>{}),y(process.stdin,u,_,!0),y(d,process.stdout,v,!1);for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process.on(e,()=>l.kill());l.on(`error`,e=>{process.stderr.write(`${e.message}\n`),process.exit(1)}),l.on(`close`,e=>{process.exitCode=e??1,process.stdin.destroy()})}`${HIe.toString()}${JSON.stringify([`browser_click`,`browser_close`,`browser_console_messages`,`browser_drag`,`browser_drop`,`browser_emulate_media`,`browser_evaluate`,`browser_file_upload`,`browser_fill_form`,`browser_find`,`browser_handle_dialog`,`browser_hover`,`browser_navigate`,`browser_navigate_back`,`browser_network_request`,`browser_network_requests`,`browser_press_key`,`browser_resize`,`browser_select_option`,`browser_snapshot`,`browser_tabs`,`browser_take_screenshot`,`browser_type`,`browser_wait_for`])}`;function F6(e){return e.replace(/\\/g,`/`)}function UIe(e,t={isAbsolute:re}){let n=F6(e);return n===`..`||n.startsWith(`../`)||t.isAbsolute(e)}function WIe(e){return ye(`sha256`).update(e).digest(`hex`)}_Y(`disk-receipts`),_Y(`directory-root`);const I6=_Y(`content-filter`);Me(o);const L6=[`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`],R6=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,...L6,`Library`,`Applications`,`.Trash`]),z6=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,...L6]),B6=new Set([`worktrees`,`local`]);function V6(e){return R6.has(e)||z6.has(e.toLowerCase())}const GIe=/^\.+(?:\/|$)/;function H6(e){return GIe.test(e)}function U6(e){return UIe(e)||H6(e)}function W6(e){let t=rd(e);if(!od(t))throw Error(`Invalid attachment folder path`);if(t===`./`)return{kind:`sibling`};if(t===`/`||t===`.`)return{kind:`content-root`};let n=t.startsWith(`./`),r=(n?t.slice(2):t).split(`/`).filter(e=>e!==``&&e!==`.`).map(hoe);return r.length===0?n?{kind:`sibling`}:{kind:`content-root`}:{kind:n?`doc-relative`:`fixed`,segments:r}}function G6(e,t,n){return n.every((n,r)=>n(e[t+r]??``))}function KIe(e){throw Error(`[AttachmentFolderShape] unhandled variant: ${JSON.stringify(e)}`)}function qIe(e,t,n){let r=P(e).slice(1).toLowerCase();if(!yu.has(r)||t.kind===`sibling`)return!1;let i=e.lastIndexOf(`/`),a=i===-1?``:e.slice(0,i);if(t.kind===`content-root`)return a===``;let o=a===``?[]:a.split(`/`);if(t.kind===`fixed`)return o.length>=t.segments.length&&G6(o,0,t.segments);if(t.kind===`doc-relative`){for(let e=0;e<=o.length-t.segments.length;e++)if(G6(o,e,t.segments)&&n(o.slice(0,e).join(`/`)))return!0;return!1}return KIe(t)}function K6(e,t){let n=e.split(`/`);for(let e=0;e<n.length;e++){let r=n[e].toLowerCase();if(z6.has(r)&&!(t&&r===`.ok`&&!B6.has((n[e+1]??``).toLowerCase())))return!0}return!1}function JIe(e){return K6(e)||e8(e)}function q6(e,t){return JIe(e.slice(t.length+1))}function J6(e){return e.startsWith(`.ok/skills/`)&&!q6(e,`.ok/skills`)}function YIe(e){return e===`.ok`||e===`.ok/skills`||J6(e)}const Y6=new Set([`.ok`,...L6]),XIe=new Set([...R6].filter(e=>!Y6.has(e))),ZIe=[`.git`,`node_modules`,`.ok/local`,`.ok/worktrees`].flatMap(e=>[e,`${e}/**`,`**/${e}`,`**/${e}/**`]);function QIe(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);return t.includes(`..`)?!1:t.some(e=>XIe.has(e))?!0:t.some((e,n)=>e.toLowerCase()===`.ok`&&B6.has((t[n+1]??``).toLowerCase()))}const $Ie=[`.gitignore`,`.ok`,`.ok/config.yml`,`.ok/.gitignore`,`.ok/schemas/frontmatter.json`,`.ok/templates/example.md`,`.ok/skills/example/SKILL.md`,`docs/.ok`,`docs/.ok/frontmatter.yml`,`docs/.ok/templates/example.md`,...L6.flatMap(e=>[e,`${e}/skills/example/SKILL.md`])];function eLe(e){let t=e.trim();if(!t||t.startsWith(`!`)||t.startsWith(`#`))return!1;let n=t.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);if(n.includes(`..`))return!0;if(QIe(t))return!1;if(n.some(e=>Y6.has(e)))return!0;try{let e=(0,AQ.default)().add(t);return $Ie.some(t=>e.ignores(t))}catch{return!0}}function tLe(e){let t=e.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!eLe(e));return[...new Set([...t,...ZIe])]}function X6(e,t){for(let n=0;n<t;n++)if(V6(e[n]))return!0;return!1}function Z6(e){let t=e.split(`/`),n=t.length;return n<3||t[n-3]!==`.ok`||t[n-2]!==`templates`||P(t[n-1])!==`.md`?!1:!X6(t,n-3)}function Q6(e){let t=e.split(`/`),n=t.length;return t[n-1]===`.ok`?!X6(t,n-1):n>=2&&t[n-1]===`templates`&&t[n-2]===`.ok`&&!X6(t,n-2)}function nLe(e){let t=e.split(`/`),n=t.length;return t[0]===`.ok`&&(n===2&&(t[1]===`config.yml`||t[1]===`.gitignore`)||n===3&&t[1]===`schemas`&&t[2].toLowerCase().endsWith(`.json`))||Z6(e)?!0:n>=2&&t[n-1]===`frontmatter.yml`&&t[n-2]===`.ok`&&!X6(t,n-2)}function rLe(e){return e===`.ok`||e===`.ok/schemas`||Q6(e)}function iLe(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}function $6(e,t){if(t.size===0)return!1;for(let n of t)if(e.startsWith(`${n}/`)&&!q6(e,n))return!0;return!1}function aLe(e,t){if(t.size===0)return!1;for(let n of t)if(n===e||n.startsWith(`${e}/`)||e.startsWith(`${n}/`)&&!q6(e,n))return!0;return!1}const oLe=new Set([`.ds_store`,`.localized`,`thumbs.db`,`desktop.ini`,`.directory`]);function e8(e){return oLe.has(e.slice(e.lastIndexOf(`/`)+1).toLowerCase())}const sLe=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function t8(e){for(let t of e.split(`/`))if(sLe.has(t.toLowerCase()))return!0;return!1}const cLe=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),lLe=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function n8(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||cLe.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of lLe)if(t.endsWith(e))return!0;return!1}function uLe(e,t){return t===e||t.startsWith(`${e}/`)}function dLe(e,t,n,r){let i=n===void 0,a=new Map;function o(e){let t=a.get(e);if(t!==void 0)return t;let n;try{n=vY(e)}catch{return!1}return a.set(e,n),n}return{isInside(n,a){if(!i||n===``)return!1;let s=a?.pathBase===`project`?e:t;if(r?.(ae(s,n)))return!0;let c=s;for(let e of n.split(`/`))if(c=F(c,e),o(c))return!0;return!1},reset(){a.clear()}}}const r8=[`.gitignore`,`.okignore`];function fLe(e,t){let n=pLe(e);if(n===null)return[];let r=[];i8(F(n,`info`,`exclude`),t,r,`info/exclude`);let i=mLe(e);return i&&i8(i,t,r,`global excludesfile`),r}function pLe(e){let t=l(`git`,[`rev-parse`,`--git-common-dir`],P6({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||!t.stdout?null:ae(e,t.stdout.trim())}function mLe(e){let t=l(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],P6({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return hLe()}function hLe(){let e=process.env.XDG_CONFIG_HOME?.trim(),t=e&&e.length>0?e:F(de(),`.config`);return F(t,`git`,`ignore`)}function i8(e,t,n,r){if(_(e))try{let r=C(e,`utf-8`);t.value+=r.length,n.push(...o8(r))}catch(t){I6.warn({path:e,err:t},`Failed to read ${r} at ${e}`)}}function gLe(){let e=!1;return{failed(t){PIe(),!e&&(e=!0,I6.warn({err:t},`in-place skill re-scan failed; the previous allow-list stays until a re-scan succeeds, and further failures are only counted`))},succeeded(){e&&(e=!1,I6.info({},`in-place skill re-scan works again`))}}}function _Le(e){let{projectDir:t,contentDir:n,onAfterRebuild:r,singleDocRelPath:i}=e,a=e.inPlaceSkillDirs??new Set,o=gLe(),s=W6(e.attachmentFolderPath??`./{{filename}}.assets`),c=e.skillRootPaths??new Set,l=dLe(t,n,i,e.isContentScopeExcluded),u=F6(L(t,n)),d=U6(u),f,p,m,h,g=0,v=0,y=0;function b(){let e=(0,AQ.default)(),r=(0,AQ.default)();e.add(`.git`);let i=[],a=0,o=0;for(let n of r8){let o=F(t,n);if(_(o))try{let t=C(o,`utf-8`);a+=t.length;let s=o8(t);i.push(...s),e.add(s),n===`.okignore`&&r.add(s)}catch(e){I6.warn({path:o,err:e},`Failed to read ${n} at ${o}`)}}if(u&&!d)for(let t of r8){let i=F(n,t);if(_(i))try{let n=C(i,`utf-8`);a+=n.length,o++;let s=o8(n).map(e=>s8(e,u));e.add(s),t===`.okignore`&&r.add(s)}catch(e){I6.warn({path:i,err:e},`Failed to read ${t} at ${i}`)}}let s={value:a};o+=c8(n,t,e,r,s),a=s.value;let c=fLe(t,s);a=s.value,c.length>0&&(i.push(...c),e.add(c));let l=tLe(i);return f=e,p=r,m=i,h=l,g=i.length,v=o,y=a,{patternCount:g,nestedFileCount:v,bytes:y}}b();let x=new Map;function S(e,t){if(d&&t?.pathBase!==`project`)return!1;let n=t?.pathBase===`project`||!u?e:`${u}/${e}`;return!H6(n)&&f.ignores(n)}function w(e,t){return t.pathBase===`project`||!u?e:`${u}/${e}`}function T(e){if(d)return!1;let t=u?`${u}/${e}`:e;return!H6(t)&&p.ignores(t)}let E=()=>{i===void 0&&a8(n,``,S,x)};E();function D(e){return zIe(MIe(e))}function O(e){for(let t of e.split(`/`))if(V6(t))return!0;return!d&&S(e)}let k=null,A=null;return{isExcluded(e,t){if(D(e)||n8(e)||t8(e)||l.isInside(e,t?.syncScope)||!t?.bypassFilters&&iLe(e,c)&&!$6(e,a))return!0;if(!t?.bypassFilters&&(J6(e)||$6(e,a)&&!S(e))){if(i!==void 0)return e!==i;if(N6(e))return!1;let t=P(e).slice(1).toLowerCase();return!yu.has(t)}if(!t?.bypassFilters&&Z6(e)||!t?.bypassFilters&&t?.syncScope!==void 0&&nLe(w(e,t.syncScope))&&!S(e,t.syncScope))return i!==void 0&&e!==i;if(K6(e,t?.showOk)||e8(e))return!0;if(i!==void 0)return e!==i;if(t?.bypassFilters)return t.respectOkignore===!0&&T(e);if(O(e))return!0;if(N6(e)||qIe(e,s,e=>(x.get(e)??0)>0))return!1;let n=P(e).slice(1).toLowerCase();if(yu.has(n)){let t=N(e),n=t===`.`?``:t;if((x.get(n)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t8(e)||l.isInside(e,t?.syncScope))return!0;if(!t?.bypassFilters&&(YIe(e)||Q6(e)||t?.syncScope!==void 0&&rLe(w(e,t.syncScope))||aLe(e,a)))return!1;if(K6(e,t?.showOk))return!0;if(i!==void 0)return!uLe(e,i);if(t?.bypassFilters)return t.respectOkignore===!0&&(T(e)||T(`${e}/`));for(let t of e.split(`/`))if(V6(t))return!0;return d?!1:S(e,t?.syncScope)||S(`${e}/`,t?.syncScope)},isPathIgnored(e,t){return D(e)||n8(e)||t8(e)?!0:J6(e)||$6(e,a)&&!S(e)||Z6(e)?!1:K6(e)||e8(e)?!0:!t?.bypassFilters&&O(e)},isExcludedByIgnoreFiles(e){return e.split(`/`).some(V6)||d?!1:S(e)},getWatcherIgnoreGlobs(){return h},incrementMdDir(e){let t=e===`.`?``:e;x.set(t,(x.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=x.get(t)??0;n<=1?x.delete(t):x.set(t,n-1)},rebuildDirCount(){let e=new Map(x);x.clear();try{E()}catch(t){for(let[t,n]of e)x.set(t,n);I6.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},setAttachmentFolderPath(e){s=W6(e)},refreshInPlaceSkillDirs(){if(e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a),o.succeeded()}catch(e){o.failed(e)}},inPlaceSkillDirsFingerprint(){return[...a].sort().join(`
1198
1198
  `)},peekFreshInPlaceSkillDirsFingerprint(){if(!e.rescanInPlaceSkillDirs)return[...a].sort().join(`
1199
1199
  `);try{return[...e.rescanInPlaceSkillDirs(a)].sort().join(`
1200
1200
  `)}catch{return[...a].sort().join(`
1201
- `)}},async rebuildIgnorePatterns(){let t=e=>(k=e().finally(()=>{k=null}),k),s=async()=>{if(l.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a),o.succeeded()}catch(e){o.failed(e)}let t=f,s=p,c=m,u=h,d=g,_=v,C=y,w=Date.now();return zIe(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=b();x.clear(),i===void 0&&await vLe(n,S,x);let a=Date.now()-w;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),I6.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){I6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a}}catch(e){f=t,p=s,m=c,h=u,g=d,v=_,y=C,x.clear();try{E()}catch(e){I6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let n=e instanceof Error?e.message:String(e);return I6.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return k===null?t(s):(A===null&&(A=k.catch(()=>null).then(()=>(A=null,t(s)))),A)}}}async function vLe(e,t,n){let r=[{dir:e,relPath:``}],i=0;for(;r.length>0;){let{dir:e,relPath:a}=r.pop();i+=1,i>=50&&(i=0,await new Promise(e=>setImmediate(e)));let o;try{o=T(e,{withFileTypes:!0})}catch(t){I6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);continue}for(let i of o){let o=a?`${a}/${i.name}`:i.name;if(i.isDirectory()){if(V6(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:F(e,i.name),relPath:o})}else i.isFile()&&j6(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function a8(e,t,n,r){let i;try{i=T(e,{withFileTypes:!0})}catch(t){I6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(V6(a.name)||n(i)||n(`${i}/`))continue;a8(F(e,a.name),i,n,r)}else a.isFile()&&j6(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function o8(e){return e.split(`
1201
+ `)}},async rebuildIgnorePatterns(){let t=e=>(k=e().finally(()=>{k=null}),k),s=async()=>{if(l.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a),o.succeeded()}catch(e){o.failed(e)}let t=f,s=p,c=m,u=h,d=g,_=v,C=y,w=Date.now();return DIe(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=b();x.clear(),i===void 0&&await vLe(n,S,x);let a=Date.now()-w;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),I6.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){I6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a}}catch(e){f=t,p=s,m=c,h=u,g=d,v=_,y=C,x.clear();try{E()}catch(e){I6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let n=e instanceof Error?e.message:String(e);return I6.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return k===null?t(s):(A===null&&(A=k.catch(()=>null).then(()=>(A=null,t(s)))),A)}}}async function vLe(e,t,n){let r=[{dir:e,relPath:``}],i=0;for(;r.length>0;){let{dir:e,relPath:a}=r.pop();i+=1,i>=50&&(i=0,await new Promise(e=>setImmediate(e)));let o;try{o=T(e,{withFileTypes:!0})}catch(t){I6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);continue}for(let i of o){let o=a?`${a}/${i.name}`:i.name;if(i.isDirectory()){if(V6(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:F(e,i.name),relPath:o})}else i.isFile()&&N6(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function a8(e,t,n,r){let i;try{i=T(e,{withFileTypes:!0})}catch(t){I6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(V6(a.name)||n(i)||n(`${i}/`))continue;a8(F(e,a.name),i,n,r)}else a.isFile()&&N6(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function o8(e){return e.split(`
1202
1202
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function s8(e,t){let n=e.startsWith(`!`),r=n?e.slice(1):e,i=r.startsWith(`/`)?r.slice(1):r,a=i.endsWith(`/`)?i.slice(0,-1):i,o=r.startsWith(`/`)||a.includes(`/`)?`${t}/${i}`:`${t}/**/${i}`;return n?`!${o}`:o}function c8(e,t,n,r,i){let a;try{a=T(e,{withFileTypes:!0})}catch(t){return I6.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||V6(s.name))continue;let a=F(e,s.name),c=F6(L(t,a));if(!U6(c)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of r8){let t=F(a,e);if(_(t))try{let a=C(t,`utf-8`);i.value+=a.length;let s=o8(a).map(e=>s8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){I6.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=c8(a,t,n,r,i)}}return o}new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};const yLe=/[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu;function l8(e){return e.replace(yLe,``).normalize(`NFC`).toUpperCase().toLowerCase().normalize(`NFC`)}function u8(e){let t=l8(e);for(let e=0;e<4;e++){let e=l8(t);if(e===t)break;t=e}return t.replace(/[. ]+$/u,(e,t)=>t===0?e:``)}const bLe=new Set([`.ok`,`.open-knowledge`,`.openknowledge`,...Object.values(tt).map(({userHomeDirName:e})=>e)].map(u8));new Set([...vt,...ht,...ree].map(u8));function xLe(e){let t=new Set;for(let n of e){let e=n.replace(/^\.+/u,``);if(!/^[a-z0-9-]+$/u.test(e))throw Error(`cannot derive 8.3 short names for config dir "${n}"`);e.length<=2?t.add(`${e}[0-9a-f]{4}`):(t.add(e.slice(0,6)),t.add(`${e.slice(0,2)}[0-9a-f]{4}`))}return RegExp(`^(?:${[...t].join(`|`)})~\\d+$`,`u`)}xLe(bLe);const d8=z().min(1).refine(e=>!e.includes(`\0`)&&re(e)&&ie(e)===e);Uo(`kind`,[W({kind:q(`file`),path:d8}),W({kind:q(`tree`),path:d8,excluded:U(d8)}).refine(({path:e,excluded:t})=>t.every(t=>L(e,t)!==``&&SLe(e,t)))]),W({server_instance_id:z().min(1),owner_token:jo(),pid:B().int().positive(),lease_protocol:z().min(1),project_dir:d8,scope_json:z(),started_at:vs()});function SLe(e,t){let n=L(e,t);return n===``||n!==`..`&&!n.startsWith(`..${oe}`)&&!re(n)}const CLe=String.raw`(?![\p{L}\p{M}\p{N}_])`;RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})${CLe}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),_Y(`loss-capture`),W({ts:B(),schemaVersion:B(),seq:B(),event:z(),docName:z(),writerId:z().nullable(),site:z().optional(),direction:z().optional(),lostLen:B().optional(),digest:z().optional(),checkpointSha:z().optional(),which:z().optional(),witnessAvailable:V().optional(),connections:B().optional()}),_Y(`checkpoint-chain`);function f8(e){try{return D.native(e)}catch{return e}}`${bt.map(e=>`${e}/`).join(`
1203
1203
  `)}${ht.join(`
1204
- `)}`;function wLe(e){try{return process.kill(e,0),`signalable`}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`?`foreign`:`absent`}}function p8(e){return wLe(e)!==`absent`}function TLe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const ELe=/^[A-Za-z0-9-]{8,64}$/;let m8=null;function h8(e){return F(e??de(),`.ok`,`machine-id`)}function DLe(e){if(e===void 0&&m8!==null)return m8;let t=h8(e),n=null;try{let e=C(t,`utf-8`).trim();ELe.test(e)&&(n=e)}catch{}if(n===null){n=be();try{y(N(t),{recursive:!0}),j(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){_Y(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(m8=n),n}const OLe=_Y(`process-identity`),g8=5e3,kLe=/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/,_8=Symbol.for(`@inkeep/open-knowledge/native-process-start-reader`),v8=globalThis;let y8,b8,x8=!1;function S8(e){return Number.isSafeInteger(e)&&e>0&&e<=4294967295}function C8(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function w8(e){return typeof e==`string`&&e.length>0&&e.length<=64}function T8(e){return C(e,`utf8`)}function ALe(e,t={}){if(!S8(e))return null;let n=t.env??process.env,r=t.run??s,i=N6({encoding:`utf8`,...BIe,timeout:g8,env:{...n,LC_ALL:`C`,TZ:`UTC0`}});try{let t=r(`ps`,[`-p`,String(e),`-o`,`lstart=`],i).trim();if(!kLe.test(t))return null;let n=Date.parse(`${t} UTC`);return Number.isFinite(n)?n:null}catch{return null}}function jLe(e){return v8[_8]=e,()=>{v8[_8]===e&&(delete v8[_8],x8=!1)}}function MLe(e){let t=e.lastIndexOf(`)`);if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];if(n===void 0||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)?r:null}function NLe(e){let t=/^btime\s+(\d+)\s*$/m.exec(e);if(!t?.[1])return null;let n=Number(t[1]);return Number.isSafeInteger(n)?n:null}function PLe(e){let t=e===T8;if(t&&b8!==void 0)return b8;let n;try{n=e(`/proc/sys/kernel/random/boot_id`).trim()}catch{return}if(w8(n))return t&&(b8=n),n}function FLe(e,t){let n=MLe(t(`/proc/${e}/stat`));if(n===null)return null;let r=NLe(t(`/proc/stat`));if(r===null)return null;let i={startedAtMs:r*1e3+n*10,clock:`boot-derived`,startTicks:n},a=PLe(t);return a===void 0?i:{...i,bootId:a}}function ILe(e,t){let n=t??v8[_8];if(n===void 0)return x8||(x8=!0,OLe.warn({event:`process-start-reader-missing`},`[process-identity] no Windows process-start reader is registered, so lock holders cannot be verified; later reads are not recorded again while it stays missing`)),null;let r=n(e);return C8(r)?{startedAtMs:r,clock:`creation`}:null}function LLe(e,t,n,r){try{if(t===`linux`)return FLe(e,n);if(t===`darwin`){let t=ALe(e);return t===null?null:{startedAtMs:t,clock:`creation`}}return t===`win32`?ILe(e,r):null}catch{return null}}function E8(e,t={}){if(!S8(e))return null;let n=t.platform===void 0&&t.readFile===void 0&&t.readNative===void 0;if(n&&e===process.pid&&y8!==void 0)return y8;let r=LLe(e,t.platform??process.platform,t.readFile??T8,t.readNative);return n&&e===process.pid&&r!==null&&(y8=r),r}function RLe(e){let t=e.read??E8,n=e.now??(()=>performance.now()),r=Math.max(e.maxAgeMs,g8),i=new Map;return a=>{let o=n();for(let[e,t]of i)o>=t.expiresAtMs&&i.delete(e);let s=i.get(a);if(s!==void 0)return s.start;let c=t(a),l=c===null?r:e.maxAgeMs;return i.set(a,{expiresAtMs:n()+l,start:c}),c}}function D8(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let{bootId:t,startTicks:n,startedAtMs:r}=e;if(w8(t)&&C8(n))return{bootId:t,startTicks:n};if(C8(r))return{startedAtMs:r}}function O8(e){return typeof e.machineId==`string`||typeof e.hostname==`string`}function k8(e,t={}){return typeof e.machineId==`string`?e.machineId===(t.machineId??DLe()):typeof e.hostname==`string`&&e.hostname===(t.host??fe())}const A8={verdict:`unverified`,cause:`process-start-incomparable`},j8={verdict:`unverified`,cause:`process-start-mismatch`},zLe={verdict:`unverified`,cause:`recorded-start-in-future`},BLe={verdict:`unverified`,cause:`writer-identity-unrecorded`},VLe={verdict:`unverified`,cause:`process-started-after-lock`};function HLe(e,t,n){let r=typeof e==`string`?Date.parse(e):NaN;if(!Number.isFinite(r))return A8;let i=t.clock===`creation`?1e4:3e5;if(r-Date.now()>i)return zLe;let a=t.startedAtMs-r;return a>i?{verdict:`replaced`}:n&&a>0?VLe:{verdict:`writer`}}function ULe(e,t,n){if(t===null)return{verdict:`unverified`,cause:`process-start-unreadable`};let r=D8(e.processStart);if(r===void 0)return HLe(e.startedAt,t,n);if(`bootId`in r)return t.bootId===void 0||t.startTicks===void 0?A8:r.bootId===t.bootId?t.startTicks===r.startTicks?{verdict:`writer`}:t.startTicks>r.startTicks?{verdict:`replaced`}:j8:{verdict:`replaced`};if(t.clock!==`creation`)return A8;let i=t.startedAtMs-r.startedAtMs;return Math.abs(i)<=1e3?{verdict:`writer`}:i>0?{verdict:`replaced`}:j8}function WLe(e=Date.now(),t=ve){try{let n=t();return!Number.isFinite(n)||n<=0?null:e-Math.round(n*1e3)}catch{return null}}function GLe(e){let t=D8(e.processStart),n=[t!==void 0&&`startedAtMs`in t?t.startedAtMs:NaN,typeof e.startedAt==`string`?Date.parse(e.startedAt):NaN].filter(Number.isFinite);return n.length===0?null:Math.max(...n)}function KLe(e,t){let n=GLe(e);if(n===null)return!1;let r=t();return r!==null&&r-n>3e5}function M8(e){return D8(e.processStart)!==void 0}function N8(e,t={}){let n=t.isAlive??p8;if(!n(e.pid))return{verdict:`gone`};let r=t.sameMachine??k8(e);if(!r&&!O8(e))return{verdict:`unverified`,cause:`unverified-owner`};let i=(t.readProcessStart??E8)(e.pid);if(i===null&&!n(e.pid))return{verdict:`gone`};if(i===null&&r&&(t.platform??process.platform)===`win32`&&KLe(e,t.readBootInstant??(()=>WLe())))return{verdict:`replaced`};let a=ULe(e,i,t.refuseHolderStartedAfterLock??!1);return r?a.verdict===`writer`&&(t.formatRecordsMachineId??!0)&&!M8(e)&&typeof e.machineId!=`string`?BLe:a:a.verdict===`writer`&&M8(e)?a:{verdict:`unverified`,cause:`foreign-host`}}_Y(`shadow-lock`),_Y(`shadow-op-gate`),_Y(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const qLe=vt.map(e=>`.ok/${e}/`),JLe=ht.map(e=>`.ok/${e}`);[...qLe.map(e=>`**/${e}`),...JLe.map(e=>`**/${e}`)],qK.fileSystem,qK.gitUpstream,qK.service,qK.generator,_Y(`bridge-loss-detector`),_Y(`checkpoint`),RegExp(`<(${$K.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const YLe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,XLe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,P8=String.raw`([^\]\n]*)`,F8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,I8=e=>RegExp(`(!?)${YLe}`,e),L8=(e,t)=>RegExp(`(!?)\\[${e}\\]${XLe}`,t);I8(`y`),I8(`g`),L8(P8,`y`),L8(F8,`y`),L8(P8,`g`),L8(F8,`g`);const ZLe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(ZLe,`y`),_Y(`watcher-freshness`),_Y(`file-watcher`),_Y(`conflict-authority`),_Y(`parse-pool`),Math.max(1,Math.min(4,le()-1)),M6(()=>{}),_Y(`bridge-watchdog`),M6(()=>{}),_Y(`server-observers`),_Y(`server-observers`),_Y(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)QLe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function QLe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}Me(S),_Y(`agent-registry-apply`),_Y(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),Rf.cursor,Rf.codex,Rf[`claude-desktop`],M6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),_Y(`external-change-attribution`),_Y(`mermaid-validator`),_Y(`rename-log`),_Y(`history`),W({docName:z().min(1),file:z().min(1),markdown:z(),extension:K(iu).optional(),agentId:z().optional(),agentName:z().optional(),clientName:z().optional()}).strict(),W({...sp,timestamp:z().min(1)}).strict();function R8(e){return Vn.filter(t=>_(F(e,t.hostDir)))}function z8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}z8(In,YS),[...z8(Ln,YS)].sort((e,t)=>{let n=DQ.indexOf(e.editor),r=DQ.indexOf(t.editor);return(n===-1?DQ.length:n)-(r===-1?DQ.length:r)||e.editor.localeCompare(t.editor)}),_Y(`installed-skills-marker`),_Y(`skill-import`),_Y(`backlinks`),_Y(`local-target-inventory`),_Y(`tag-index`),BP(),_Y(`derived-document-index`);const B8={start:B().int().nonnegative().optional(),end:B().int().nonnegative().optional(),quote:z().min(1).optional(),prefix:z().max(1e3).optional(),suffix:z().max(1e3).optional()};W({docName:z().min(1),...B8,propertyKey:z().min(1).optional(),propertyPath:U(Ho([z(),B().int().nonnegative()])).optional(),body:z(),queue:V().optional(),summary:z().optional()});const V8=jo();Uo(`action`,[W({action:q(`edit`),id:V8,body:z(),summary:z().optional()}),W({action:q(`resolve`),id:V8,summary:z().optional()}),W({action:q(`reopen`),id:V8,summary:z().optional()}),W({action:q(`replace`),id:V8,...B8,summary:z().optional()}),W({action:q(`queue`),id:V8,summary:z().optional()}),W({action:q(`unqueue`),id:V8,summary:z().optional()}),W({action:q(`dispatch-prepare`),id:V8,summary:z().optional()}),W({action:q(`dispatch-complete`),id:V8,summary:z().optional()}),W({action:q(`dispatch-prepare-batch`),ids:U(V8).min(1).max(200),summary:z().optional()}),W({action:q(`dispatch-complete-batch`),ids:U(V8).min(1).max(200),summary:z().optional()})]),_Y(`embeddings`),_Y(`embeddings`);function H8(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}H8(Yu),H8(Yu),_Y(`embeddings`),_Y(`embeddings`),_Y(`process-lock`);function $Le(e,t){return ae(e,`${t}.lock`)}RLe({maxAgeMs:1e3});function eRe(e){let{processStart:t,...n}=e,r=D8(t);return{...n,...r!==void 0&&{processStart:r}}}function tRe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function nRe(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=tRe(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}_Y(`asset-references`),_Y(`upload-streaming`),Object.assign(cPe,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`}),_Y(`file-ops`);const U8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,W8=`Canonical ids: ${$we().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`;z().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),z().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),z().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),z().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),z().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const rRe=W({value:z(),truncatedFrom:B().optional(),hint:z().optional()}).describe(`Normalized change-note summary, when one was recorded.`),iRe=U(G(z(),H()));G(z(),H()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),U(mp).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),gp.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),rRe.optional(),U(fp).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),U(W({name:z(),description:z().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const aRe=z().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function G8(e){return{text:aRe,...e}}function oRe(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}oRe(`the server`);function sRe(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}sRe(`the server`),_Y(`git-checkout`),_Y(`git-worktree-status`),_Y(`edit-backups`),_Y(`managed-artifact-persistence`),_Y(`timeline`),_Y(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),_Y(`git-context`),_Y(`clone-flow`),Me(o),E6.project,Object.fromEntries(Object.entries(XS).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
1205
- `),_Y(`skills-leaderboard`),_Y(`handoff-dispatch`),W({target:K(Object.keys({"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}})),url:z().min(1).max(4096),workspacePath:z().optional()}),W({}).loose(),_Y(`github-permissions`),_Y(`github-reference`),_Y(`github-reference`),_Y(`link-preview.guarded-fetch`),_Y(`link-preview.cache`),_Y(`saved-themes`),W({enabled:V(),active:V(),git:W({state:K([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:K([`open-knowledge`,`existing`]).optional()}),applied:V().optional(),reason:K([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),W({enabled:V()}).strict(),_Y(`managed-rename`),_Y(`reconcile`),_Y(`search`),_Y(`skill-install`),_Y(`write-advisory`),_Y(`api`),W({principalId:z().optional(),tabSessionId:z().optional(),expectedServerInstanceId:z().optional(),expectedBranch:z().optional(),expectedDocLineageEpoch:z().optional(),clientProtocolVersion:B().optional(),clientRuntimeVersion:z().optional(),clientKind:z().optional()}).loose(),new Re,M6(()=>{}),[...Dse],["Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.","ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.",`Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.`,`Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.`,"Large project scans can exceed host or transport timeouts. If a scan times out, narrow `path` to a file or folder and retry.",`Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.`].join(`
1204
+ `)}`;function wLe(e){try{return process.kill(e,0),`signalable`}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`?`foreign`:`absent`}}function p8(e){return wLe(e)!==`absent`}function TLe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const ELe=/^[A-Za-z0-9-]{8,64}$/;let m8=null;function h8(e){return F(e??de(),`.ok`,`machine-id`)}function DLe(e){if(e===void 0&&m8!==null)return m8;let t=h8(e),n=null;try{let e=C(t,`utf-8`).trim();ELe.test(e)&&(n=e)}catch{}if(n===null){n=be();try{y(N(t),{recursive:!0}),j(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){_Y(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(m8=n),n}const OLe=_Y(`process-identity`),g8=5e3,kLe=/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/,_8=Symbol.for(`@inkeep/open-knowledge/native-process-start-reader`),v8=globalThis;let y8,b8,x8=!1;function S8(e){return Number.isSafeInteger(e)&&e>0&&e<=4294967295}function C8(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function w8(e){return typeof e==`string`&&e.length>0&&e.length<=64}function T8(e){return C(e,`utf8`)}function ALe(e,t={}){if(!S8(e))return null;let n=t.env??process.env,r=t.run??s,i=P6({encoding:`utf8`,...BIe,timeout:g8,env:{...n,LC_ALL:`C`,TZ:`UTC0`}});try{let t=r(`ps`,[`-p`,String(e),`-o`,`lstart=`],i).trim();if(!kLe.test(t))return null;let n=Date.parse(`${t} UTC`);return Number.isFinite(n)?n:null}catch{return null}}function jLe(e){return v8[_8]=e,()=>{v8[_8]===e&&(delete v8[_8],x8=!1)}}function MLe(e){let t=e.lastIndexOf(`)`);if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];if(n===void 0||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)?r:null}function NLe(e){let t=/^btime\s+(\d+)\s*$/m.exec(e);if(!t?.[1])return null;let n=Number(t[1]);return Number.isSafeInteger(n)?n:null}function PLe(e){let t=e===T8;if(t&&b8!==void 0)return b8;let n;try{n=e(`/proc/sys/kernel/random/boot_id`).trim()}catch{return}if(w8(n))return t&&(b8=n),n}function FLe(e,t){let n=MLe(t(`/proc/${e}/stat`));if(n===null)return null;let r=NLe(t(`/proc/stat`));if(r===null)return null;let i={startedAtMs:r*1e3+n*10,clock:`boot-derived`,startTicks:n},a=PLe(t);return a===void 0?i:{...i,bootId:a}}function ILe(e,t){let n=t??v8[_8];if(n===void 0)return x8||(x8=!0,OLe.warn({event:`process-start-reader-missing`},`[process-identity] no Windows process-start reader is registered, so lock holders cannot be verified; later reads are not recorded again while it stays missing`)),null;let r=n(e);return C8(r)?{startedAtMs:r,clock:`creation`}:null}function LLe(e,t,n,r){try{if(t===`linux`)return FLe(e,n);if(t===`darwin`){let t=ALe(e);return t===null?null:{startedAtMs:t,clock:`creation`}}return t===`win32`?ILe(e,r):null}catch{return null}}function E8(e,t={}){if(!S8(e))return null;let n=t.platform===void 0&&t.readFile===void 0&&t.readNative===void 0;if(n&&e===process.pid&&y8!==void 0)return y8;let r=LLe(e,t.platform??process.platform,t.readFile??T8,t.readNative);return n&&e===process.pid&&r!==null&&(y8=r),r}function RLe(e){let t=e.read??E8,n=e.now??(()=>performance.now()),r=Math.max(e.maxAgeMs,g8),i=new Map;return a=>{let o=n();for(let[e,t]of i)o>=t.expiresAtMs&&i.delete(e);let s=i.get(a);if(s!==void 0)return s.start;let c=t(a),l=c===null?r:e.maxAgeMs;return i.set(a,{expiresAtMs:n()+l,start:c}),c}}function D8(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let{bootId:t,startTicks:n,startedAtMs:r}=e;if(w8(t)&&C8(n))return{bootId:t,startTicks:n};if(C8(r))return{startedAtMs:r}}function O8(e){return typeof e.machineId==`string`||typeof e.hostname==`string`}function k8(e,t={}){return typeof e.machineId==`string`?e.machineId===(t.machineId??DLe()):typeof e.hostname==`string`&&e.hostname===(t.host??fe())}const A8={verdict:`unverified`,cause:`process-start-incomparable`},j8={verdict:`unverified`,cause:`process-start-mismatch`},zLe={verdict:`unverified`,cause:`recorded-start-in-future`},BLe={verdict:`unverified`,cause:`writer-identity-unrecorded`},VLe={verdict:`unverified`,cause:`process-started-after-lock`};function HLe(e,t,n){let r=typeof e==`string`?Date.parse(e):NaN;if(!Number.isFinite(r))return A8;let i=t.clock===`creation`?1e4:3e5;if(r-Date.now()>i)return zLe;let a=t.startedAtMs-r;return a>i?{verdict:`replaced`}:n&&a>0?VLe:{verdict:`writer`}}function ULe(e,t,n){if(t===null)return{verdict:`unverified`,cause:`process-start-unreadable`};let r=D8(e.processStart);if(r===void 0)return HLe(e.startedAt,t,n);if(`bootId`in r)return t.bootId===void 0||t.startTicks===void 0?A8:r.bootId===t.bootId?t.startTicks===r.startTicks?{verdict:`writer`}:t.startTicks>r.startTicks?{verdict:`replaced`}:j8:{verdict:`replaced`};if(t.clock!==`creation`)return A8;let i=t.startedAtMs-r.startedAtMs;return Math.abs(i)<=1e3?{verdict:`writer`}:i>0?{verdict:`replaced`}:j8}function WLe(e=Date.now(),t=ve){try{let n=t();return!Number.isFinite(n)||n<=0?null:e-Math.round(n*1e3)}catch{return null}}function GLe(e){let t=D8(e.processStart),n=[t!==void 0&&`startedAtMs`in t?t.startedAtMs:NaN,typeof e.startedAt==`string`?Date.parse(e.startedAt):NaN].filter(Number.isFinite);return n.length===0?null:Math.max(...n)}function KLe(e,t){let n=GLe(e);if(n===null)return!1;let r=t();return r!==null&&r-n>3e5}function M8(e){return D8(e.processStart)!==void 0}function N8(e,t={}){let n=t.isAlive??p8;if(!n(e.pid))return{verdict:`gone`};let r=t.sameMachine??k8(e);if(!r&&!O8(e))return{verdict:`unverified`,cause:`unverified-owner`};let i=(t.readProcessStart??E8)(e.pid);if(i===null&&!n(e.pid))return{verdict:`gone`};if(i===null&&r&&(t.platform??process.platform)===`win32`&&KLe(e,t.readBootInstant??(()=>WLe())))return{verdict:`replaced`};let a=ULe(e,i,t.refuseHolderStartedAfterLock??!1);return r?a.verdict===`writer`&&(t.formatRecordsMachineId??!0)&&!M8(e)&&typeof e.machineId!=`string`?BLe:a:a.verdict===`writer`&&M8(e)?a:{verdict:`unverified`,cause:`foreign-host`}}_Y(`shadow-lock`),_Y(`shadow-op-gate`),_Y(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const qLe=vt.map(e=>`.ok/${e}/`),JLe=ht.map(e=>`.ok/${e}`);[...qLe.map(e=>`**/${e}`),...JLe.map(e=>`**/${e}`)],qK.fileSystem,qK.gitUpstream,qK.service,qK.generator,_Y(`bridge-loss-detector`),_Y(`checkpoint`),RegExp(`<(${$K.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const YLe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,XLe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,P8=String.raw`([^\]\n]*)`,F8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,I8=e=>RegExp(`(!?)${YLe}`,e),L8=(e,t)=>RegExp(`(!?)\\[${e}\\]${XLe}`,t);I8(`y`),I8(`g`),L8(P8,`y`),L8(F8,`y`),L8(P8,`g`),L8(F8,`g`);const ZLe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(ZLe,`y`),_Y(`watcher-freshness`),_Y(`file-watcher`),_Y(`conflict-authority`),_Y(`parse-pool`),Math.max(1,Math.min(4,le()-1)),E6(()=>{}),_Y(`bridge-watchdog`),E6(()=>{}),_Y(`server-observers`),_Y(`server-observers`),_Y(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)QLe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function QLe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}Me(S),_Y(`agent-registry-apply`),_Y(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),Rf.cursor,Rf.codex,Rf[`claude-desktop`],E6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),_Y(`external-change-attribution`),_Y(`mermaid-validator`),_Y(`rename-log`),_Y(`history`),W({docName:z().min(1),file:z().min(1),markdown:z(),extension:K(iu).optional(),agentId:z().optional(),agentName:z().optional(),clientName:z().optional()}).strict(),W({...sp,timestamp:z().min(1)}).strict();function R8(e){return Vn.filter(t=>_(F(e,t.hostDir)))}function z8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}z8(In,YS),[...z8(Ln,YS)].sort((e,t)=>{let n=DQ.indexOf(e.editor),r=DQ.indexOf(t.editor);return(n===-1?DQ.length:n)-(r===-1?DQ.length:r)||e.editor.localeCompare(t.editor)}),_Y(`installed-skills-marker`),_Y(`skill-import`),_Y(`backlinks`),_Y(`local-target-inventory`),_Y(`tag-index`),BP(),_Y(`derived-document-index`);const B8={start:B().int().nonnegative().optional(),end:B().int().nonnegative().optional(),quote:z().min(1).optional(),prefix:z().max(1e3).optional(),suffix:z().max(1e3).optional()};W({docName:z().min(1),...B8,propertyKey:z().min(1).optional(),propertyPath:U(Ho([z(),B().int().nonnegative()])).optional(),body:z(),queue:V().optional(),summary:z().optional()});const V8=jo();Uo(`action`,[W({action:q(`edit`),id:V8,body:z(),summary:z().optional()}),W({action:q(`resolve`),id:V8,summary:z().optional()}),W({action:q(`reopen`),id:V8,summary:z().optional()}),W({action:q(`replace`),id:V8,...B8,summary:z().optional()}),W({action:q(`queue`),id:V8,summary:z().optional()}),W({action:q(`unqueue`),id:V8,summary:z().optional()}),W({action:q(`dispatch-prepare`),id:V8,summary:z().optional()}),W({action:q(`dispatch-complete`),id:V8,summary:z().optional()}),W({action:q(`dispatch-prepare-batch`),ids:U(V8).min(1).max(200),summary:z().optional()}),W({action:q(`dispatch-complete-batch`),ids:U(V8).min(1).max(200),summary:z().optional()})]),_Y(`embeddings`),_Y(`embeddings`);function H8(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}H8(Yu),H8(Yu),_Y(`embeddings`),_Y(`embeddings`),_Y(`process-lock`);function $Le(e,t){return ae(e,`${t}.lock`)}RLe({maxAgeMs:1e3});function eRe(e){let{processStart:t,...n}=e,r=D8(t);return{...n,...r!==void 0&&{processStart:r}}}function tRe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function nRe(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=tRe(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}_Y(`asset-references`),_Y(`upload-streaming`),Object.assign(cPe,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`}),_Y(`file-ops`);const U8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,W8=`Canonical ids: ${$we().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`;z().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),z().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),z().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),z().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),z().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const rRe=W({value:z(),truncatedFrom:B().optional(),hint:z().optional()}).describe(`Normalized change-note summary, when one was recorded.`),iRe=U(G(z(),H()));G(z(),H()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),U(mp).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),gp.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),rRe.optional(),U(fp).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),U(W({name:z(),description:z().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const aRe=z().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function G8(e){return{text:aRe,...e}}function oRe(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}oRe(`the server`);function sRe(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}sRe(`the server`),_Y(`git-checkout`),_Y(`git-worktree-status`),_Y(`edit-backups`),_Y(`managed-artifact-persistence`),_Y(`timeline`),_Y(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),_Y(`git-context`),_Y(`clone-flow`),Me(o),O6.project,Object.fromEntries(Object.entries(XS).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
1205
+ `),_Y(`skills-leaderboard`),_Y(`handoff-dispatch`),W({target:K(Object.keys({"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}})),url:z().min(1).max(4096),workspacePath:z().optional()}),W({}).loose(),_Y(`github-permissions`),_Y(`github-reference`),_Y(`github-reference`),_Y(`link-preview.guarded-fetch`),_Y(`link-preview.cache`),_Y(`saved-themes`),W({enabled:V(),active:V(),git:W({state:K([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:K([`open-knowledge`,`existing`]).optional()}),applied:V().optional(),reason:K([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),W({enabled:V()}).strict(),_Y(`managed-rename`),_Y(`reconcile`),_Y(`search`),_Y(`skill-install`),_Y(`write-advisory`),_Y(`api`),W({principalId:z().optional(),tabSessionId:z().optional(),expectedServerInstanceId:z().optional(),expectedBranch:z().optional(),expectedDocLineageEpoch:z().optional(),clientProtocolVersion:B().optional(),clientRuntimeVersion:z().optional(),clientKind:z().optional()}).loose(),new Re,E6(()=>{}),[...Dse],["Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.","ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.",`Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.`,`Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.`,"Large project scans can exceed host or transport timeouts. If a scan times out, narrow `path` to a file or folder and retry.",`Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.`].join(`
1206
1206
  `),[`Save a project-wide checkpoint of every document. Requires the Hocuspocus server. Optional summary ≤80 chars defaults to "Checkpoint version"; avoid secrets or PII because it persists in git history. Returns version (40-char SHA). Find it with history and restore one doc with restore_version({document,version}).`].join(`
1207
1207
  `),[`Read effective config merged defaults → user → project; no running OK server needed. Optional key is a dotted path (content, appearance.theme); omit for the full config. All fields are readable. Re-read after disk changes or before relying on an old value.`,"Removed server.*, mcp.*, github.*, preview.baseUrl and preview.scriptSrc return exists:false; appearance.preview.autoOpen remains live. This is a pure read. Use `install` skillFolders for folder topology."].join(`
1208
1208
  `),z().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),z().optional().describe(U8),G8({value:H().describe(`Resolved config value at the requested path (or full config).`),exists:V().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:z().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});const cRe=[`lock`],lRe=Ho([Kc,Io()]);Uc(Ho([z(),B(),V(),U(H()),G(z(),H()),Io()])).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))lRe.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),K([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),K(iu).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`."),K(Lf).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`);function K8(e){return Object.entries(e).map(([e,t])=>`\`${e}\`: ${t}`).join(`; `)}K(xse).optional().describe(`What happened to this write, present on every write result the server answered, success or not. ${K8(Cse)}. A value this tool version does not know is reported as merged-first when saved, else refused, with nextStep re-read.`),V().optional().describe("Whether the write's bytes were in the document's file when the server answered. Not the same as the move result's `committed` (git history)."),K(Sse).optional().describe(`What to do next about this write. ${K8(wse)}. Never retry a write whose outcome is merged-first, both-kept or projection-held: it landed.`),new Set(NK),[`Delete exactly one document, folder, template, skill or asset. Requires the Hocuspocus server. Irreversible; deleting a doc leaves inbound redlinks. Call links({kind:'backlinks',document}) BEFORE deleting.`,`document: path or paths array; folder: recursive folder path; template: {path:'<folder>/<name>'}; asset: {path:'<folder>/<file.ext>'}. skill: {name} deletes the whole bundle, or {name,files:['references/x.md']} deletes selected files. Template/skill deletion is attributed and cleans empty .ok/ directories.`].join(`
@@ -1221,7 +1221,7 @@ n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(
1221
1221
  `),z().describe(`Search query — title, path, or body terms.`),K([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),U(K([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),B().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),V().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),z().optional().describe(U8);const dRe=W({kind:K([`page`,`folder`,`file`]),path:z(),docName:z(),title:z().nullable(),score:B(),signals:W({lexical:B(),fullText:B(),recency:B(),vector:B().optional()}),snippet:z().optional(),previewUrl:z().nullable(),previewUrlSource:K(cRe).optional()});G8({cwd:z(),query:z(),intent:z(),resultCount:B().int(),results:U(dRe),elapsedMs:B().nullable(),semantic:GK.optional(),ready:q(!1).optional()}),[`Build a shareable GitHub-substrate URL for a teammate to receive a doc/folder subtree in OpenKnowledge, pinned to current branch. Requires the Hocuspocus server. Read-only, no commits/pushes/fetch. Publishing is a user act: agents do NOT publish; a missing remote returns Share-wizard guidance.`,"`path` is content-relative, docs accept .md/.mdx, empty string means root folder. `kind` doc/folder is optional for auto-probe (.mdx → .md → directory); REQUIRED when `path` is empty (use folder). Optional `cwd` selects project. Requires a named branch, GitHub/GH Enterprise origin, and branch already pushed."].join(`
1222
1222
  `),G8({ok:V().describe(`Success discriminator.`),shareUrl:z().optional().describe(`Marketing share URL (success only).`),sharedUrl:z().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:z().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:K([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:Yf.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:K([...Jf.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:z().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:z().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:z().optional().describe(`Internal: preview-URL provenance.`)});const q8="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",fRe=W({id:z().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:z().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:K([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, refreshed from the source on watcher/startup sync while unedited (hand edits fork it); symlink = live link to the source.`),audience:U(z()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:V().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});W({name:z().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:K([`project`,`global`]).describe(q8),description:z().optional().describe(`The skill's one-line description (when present).`),installed:V().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:U(z()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:U(fRe).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:K([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:U(z()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const pRe=W({path:z().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:K([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});W({name:z().describe(`Skill name (its identity).`),scope:K([`project`,`global`]).describe(q8),description:z().describe(`The skill's one-line description (empty if none).`),body:z().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:U(pRe).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),W({path:z().describe(`Skill-relative path read.`),kind:K([`reference`,`script`]).describe("`reference` or `script`."),text:z().describe(`Full text of the bundle file.`)}),W({name:z().describe("Skill name to pass as `skill` to `import`."),source:z().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:z().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:B().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:z().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),[`Read-only skill discovery. Requires the Hocuspocus server. query searches the skills.sh marketplace and returns import-ready name/source/description/publisher/install-count rows. Import a chosen row with import({source,skill:name}); external rows are not managed or active editor content until imported/projected.`,`Omit name to list Project and Global managed skills with scope/description/hosts. name reads description/body plus a bundle files list (path/kind, no inline text); name+file reads one reference/script/bundle file. Optional scope; name-only prefers Project. Address skills by name/scope, never raw .ok/ paths or native cat.`,`Built-in open-knowledge* runtime skills are already in your skill list; do not fetch them here. Use write/edit/delete/move/install for changes.`].join(`
1223
1223
  `),["Create/replace exactly one `document`, `folder`, `template`, `skill`, or `asset`; use `documents` for an ordered batch. Requires the Hocuspocus server.","Nested paths such as `guides/overview` can be documents; put all requested blocks in one `document.content`. Use `folder` only for separate pages.","`document: {path, content|template, frontmatter?, position?}`: content and template are exclusive. Existing docs require position: replace/append/prepend; new docs default replace. frontmatter with literal content forces replace, even with append/prepend. Recent edits by another writer can refuse replace; follow the recovery response; append/prepend/edit bypass this refusal. Peers are per MCP connection; own writes and writers sharing a connection do not refuse each other; connected editors can. No agentId is needed.","`folder: {path, frontmatter?}` creates NEW folders; edit existing ones. `template: {path: '<folder>/<name>', content, frontmatter: {title, description?, tags?}}` creates reusable doc templates.","`skill: {name, description, body, scope?}` writes agent guidance; lowercase letters/digits/hyphens name is identity, description is when to use it. New skills use the default skill home; existing ones keep their real folder. Use install for editors.","`asset: {path, content|source}` uploads binary image/file: base64 content or local source path. `documents` takes document specs and reports each result.",`Optional summary: one-line outcome ≤80 chars, persisted to git history; avoid secrets or PII. Batches need per-entry summary; top-level is ignored.`,`Follow nextStep: retry|re-read|none. Outcomes merged-first, both-kept, projection-held landed: never retry. mermaid-parse-error: fix the fence.`,W8].join(`
1224
- `),new Set(Object.values(Bf)),_Y(`config-persistence`),_Y(`generated-index-git-attributes`),_Y(`doc-notices`),W({branch:z().min(1),notice:wK}),W({version:q(1),notices:U(H())}),_Y(`document-refresh`),_Y(`head-watcher`),_Y(`shadow-gc`),_Y(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),_Y(`mermaid-persistence`),_Y(`persistence`),_Y(`store-compare`);const J8={"pending-unreadable":`its file could not be read for the compare before the write`,"pending-exhausted":`its file kept changing while it was being saved`,"pending-base-moved":`its acknowledged version kept moving while it was being saved`,"pending-no-intake":`its file changed and this persistence has no intake to merge it`,"pending-intake-failed":`its file changed and merging the outside version into it failed`,"pending-intake-failed-no-base":`its file changed and taking the outside version in failed, with no agreed version to merge against`,"pending-conflict":`its file changed and could not be merged, so a conflict was raised`};J8[`pending-unreadable`],J8[`pending-exhausted`],_Y(`persistence-staleness`),cd.pick({skills:!0}),_Y(`recovered-file-target`),_Y(`removed-docs-journal`),_Y(`server-observers`),_Y(`github-account`),_Y(`sync-engine`),Me(o),new Set(Iwe);const Y8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(Y8),[...Y8],WIe(``),(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let X8=null;M6(()=>{X8?.disable(),X8=null}),_Y(`skill-migrate`);function Z8(e){return[{host:`agents`,root:YS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=DQ.indexOf(e.host),r=DQ.indexOf(t.host);return(n===-1?DQ.length:n)-(r===-1?DQ.length:r)||e.host.localeCompare(t.host)})}Z8(In),Z8(Ln),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const mRe=cd;Me(o),_Y(`project-git`);var Q8=i((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),$8=i((e=>{let{InvalidArgumentError:t}=Q8();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),e5=i((e=>{let{humanReadableArgName:t}=$8();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
1224
+ `),new Set(Object.values(Bf)),_Y(`config-persistence`),_Y(`generated-index-git-attributes`),_Y(`doc-notices`),W({branch:z().min(1),notice:wK}),W({version:q(1),notices:U(H())}),_Y(`document-refresh`),_Y(`head-watcher`),_Y(`shadow-gc`),_Y(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),_Y(`mermaid-persistence`),_Y(`persistence`),_Y(`store-compare`);const J8={"pending-unreadable":`its file could not be read for the compare before the write`,"pending-exhausted":`its file kept changing while it was being saved`,"pending-base-moved":`its acknowledged version kept moving while it was being saved`,"pending-no-intake":`its file changed and this persistence has no intake to merge it`,"pending-intake-failed":`its file changed and merging the outside version into it failed`,"pending-intake-failed-no-base":`its file changed and taking the outside version in failed, with no agreed version to merge against`,"pending-conflict":`its file changed and could not be merged, so a conflict was raised`};J8[`pending-unreadable`],J8[`pending-exhausted`],_Y(`persistence-staleness`),cd.pick({skills:!0}),_Y(`recovered-file-target`),_Y(`removed-docs-journal`),_Y(`server-observers`),_Y(`github-account`),_Y(`sync-engine`),Me(o),new Set(Iwe);const Y8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(Y8),[...Y8],WIe(``),(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let X8=null;E6(()=>{X8?.disable(),X8=null}),_Y(`skill-migrate`);function Z8(e){return[{host:`agents`,root:YS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=DQ.indexOf(e.host),r=DQ.indexOf(t.host);return(n===-1?DQ.length:n)-(r===-1?DQ.length:r)||e.host.localeCompare(t.host)})}Z8(In),Z8(Ln),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const mRe=cd;Me(o),_Y(`project-git`);var Q8=i((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),$8=i((e=>{let{InvalidArgumentError:t}=Q8();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),e5=i((e=>{let{humanReadableArgName:t}=$8();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
1225
1225
  `)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
1226
1226
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
1227
1227
  `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),t5=i((e=>{let{InvalidArgumentError:t}=Q8();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
@@ -1582,14 +1582,14 @@ export default function okBridge(pi: {
1582
1582
  }
1583
1583
  });
1584
1584
  }
1585
- `}function jRe(e,t){let n=L(f8(t),f8(e));return n.length>0&&!n.startsWith(`..`)&&!re(n)}const MRe=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],N6({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function NRe(e,t={}){let n=t.homeDir??de(),r=t.gitTopLevel??MRe,i=ae(e),a;try{a=D(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(vY(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=N(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&jRe(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}function i5(e,t){let n=N(t),r=_(t)?`overwritten`:`written`;if(r===`written`&&_(n))throw Error(`Refusing to replace ${n}: it exists but holds no SKILL.md, so it is not a bundle OpenKnowledge wrote. Move it aside and try again.`);return k(n,{recursive:!0,force:!0}),y(N(n),{recursive:!0}),a5(e,n),r}function a5(e,t){y(t,{recursive:!0});for(let n of T(e,{withFileTypes:!0})){let r=F(e,n.name),i=F(t,n.name);n.isDirectory()?a5(r,i):m(r,i)}}var o5=class extends Error{name=`ProjectPathSafetyError`;code=`PROJECT_PATH_SAFETY`};function s5(e,t){let n;try{n=v(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw new o5(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);c5(e,t)}function PRe(e,t){c5(e,t)}function c5(e,t){l5(e,t)}function l5(e,t){let n=t,r;try{r=D(n)}catch{r=ae(n)}let i=N(e);for(;i.length>1&&i!==oe;){let t;try{t=D(i)}catch(e){if(e.code===`ENOENT`){i=N(i);continue}throw e}let n=L(r,t);if(n===``||!n.startsWith(`..`)&&!re(n))return;throw new o5(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${r}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function u5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d5(e,t,n){try{if(ee(n).size>10485760)return!1}catch{return!1}let r;try{r=C(n,`utf-8`)}catch{return!1}let i=[],a=aPe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!u5(a))return!1;let o=a[e.topLevelKey];if(!u5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!u5(s))return!1;let c=s[e.serverName(t)];return u5(c)&&c.enabled===!1?!1:Yq(c)||PTe(c)}function FRe(e){let t=kc[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:Us(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:sJ[n.editor]??null}function IRe(e,t,n={}){if(!jee.includes(e.id))return!0;let r=FRe(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&d5(r,t,i))return!0;try{return d5(e,t,e.configPath(t,n.home))}catch{return!1}}function LRe(e){let t=new Set(Rn.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function RRe(e,t){if(LRe(t).length===0)return null;let n=F(e,YS,Bn,`SKILL.md`);try{let t=A6(`project`,{checkDesktop:!0});return s5(N(n),e),{editorId:`agents`,label:`.agents hub`,action:i5(t,n),path:n}}catch(e){return{editorId:`agents`,label:`.agents hub`,action:`failed`,path:n,error:e instanceof Error?e.message:String(e)}}}function f5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!IRe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=A6(`project`,{checkDesktop:!0});s5(N(r),t);let i=i5(n,r);return{editorId:e.id,label:e.label,action:i,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function zRe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=N(n);return _(n)?(PRe(r,t),k(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function BRe(){let e=Sq();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function VRe(e){let t=e,n=new Set;for(;;){let r;try{r=v(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=E(t)}catch(t){return xq(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=re(i)?i:F(N(t),i)}}let p5;function HRe(){return p5===void 0&&(p5=BRe()),p5}function m5(e,t=HRe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){xq(`resolveSymlinkWritePath threw`,e)}return VRe(e)}const h5=`**/.ok/*`,g5=`!**/.ok/skills/`;function _5(e){let t=[`.ok/`,`.okignore`];for(let n of Eq){let r=sJ[n];r.projectConfigPath&&t.push(XRe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function v5(e){let t=F(e,...Kwe);if(!_(t))return[];try{let e=Xwe(C(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=In[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function URe(e,t){let n=y5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:b5(n)};let r=x5(e);if(r.kind!==`ok`)return r.result;let i=_(r.path)?C(r.path,`utf-8`):``,a=new Set(v5(e)),o=[],s=a.size===0?i:i.split(`
1585
+ `}function jRe(e,t){let n=L(f8(t),f8(e));return n.length>0&&!n.startsWith(`..`)&&!re(n)}const MRe=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],P6({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function NRe(e,t={}){let n=t.homeDir??de(),r=t.gitTopLevel??MRe,i=ae(e),a;try{a=D(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(vY(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=N(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&jRe(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}function i5(e,t){let n=N(t),r=_(t)?`overwritten`:`written`;if(r===`written`&&_(n))throw Error(`Refusing to replace ${n}: it exists but holds no SKILL.md, so it is not a bundle OpenKnowledge wrote. Move it aside and try again.`);return k(n,{recursive:!0,force:!0}),y(N(n),{recursive:!0}),a5(e,n),r}function a5(e,t){y(t,{recursive:!0});for(let n of T(e,{withFileTypes:!0})){let r=F(e,n.name),i=F(t,n.name);n.isDirectory()?a5(r,i):m(r,i)}}var o5=class extends Error{name=`ProjectPathSafetyError`;code=`PROJECT_PATH_SAFETY`};function s5(e,t){let n;try{n=v(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw new o5(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);c5(e,t)}function PRe(e,t){c5(e,t)}function c5(e,t){l5(e,t)}function l5(e,t){let n=t,r;try{r=D(n)}catch{r=ae(n)}let i=N(e);for(;i.length>1&&i!==oe;){let t;try{t=D(i)}catch(e){if(e.code===`ENOENT`){i=N(i);continue}throw e}let n=L(r,t);if(n===``||!n.startsWith(`..`)&&!re(n))return;throw new o5(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${r}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function u5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d5(e,t,n){try{if(ee(n).size>10485760)return!1}catch{return!1}let r;try{r=C(n,`utf-8`)}catch{return!1}let i=[],a=aPe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!u5(a))return!1;let o=a[e.topLevelKey];if(!u5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!u5(s))return!1;let c=s[e.serverName(t)];return u5(c)&&c.enabled===!1?!1:Yq(c)||PTe(c)}function FRe(e){let t=kc[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:Us(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:sJ[n.editor]??null}function IRe(e,t,n={}){if(!jee.includes(e.id))return!0;let r=FRe(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&d5(r,t,i))return!0;try{return d5(e,t,e.configPath(t,n.home))}catch{return!1}}function LRe(e){let t=new Set(Rn.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function RRe(e,t){if(LRe(t).length===0)return null;let n=F(e,YS,Bn,`SKILL.md`);try{let t=M6(`project`,{checkDesktop:!0});return s5(N(n),e),{editorId:`agents`,label:`.agents hub`,action:i5(t,n),path:n}}catch(e){return{editorId:`agents`,label:`.agents hub`,action:`failed`,path:n,error:e instanceof Error?e.message:String(e)}}}function f5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!IRe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=M6(`project`,{checkDesktop:!0});s5(N(r),t);let i=i5(n,r);return{editorId:e.id,label:e.label,action:i,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function zRe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=N(n);return _(n)?(PRe(r,t),k(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function BRe(){let e=Sq();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function VRe(e){let t=e,n=new Set;for(;;){let r;try{r=v(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=E(t)}catch(t){return xq(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=re(i)?i:F(N(t),i)}}let p5;function HRe(){return p5===void 0&&(p5=BRe()),p5}function m5(e,t=HRe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){xq(`resolveSymlinkWritePath threw`,e)}return VRe(e)}const h5=`**/.ok/*`,g5=`!**/.ok/skills/`;function _5(e){let t=[`.ok/`,`.okignore`];for(let n of Eq){let r=sJ[n];r.projectConfigPath&&t.push(XRe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function v5(e){let t=F(e,...Kwe);if(!_(t))return[];try{let e=Xwe(C(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=In[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function URe(e,t){let n=y5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:b5(n)};let r=x5(e);if(r.kind!==`ok`)return r.result;let i=_(r.path)?C(r.path,`utf-8`):``,a=new Set(v5(e)),o=[],s=a.size===0?i:i.split(`
1586
1586
  `).filter(e=>{let t=e.trim();return!a.has(t)||(o.push(t),!1)}).join(`
1587
1587
  `),c=w5(s),l=[],u=[];for(let e of t)C5(c,e)?u.push(e):l.push(e);if(l.length===0&&o.length===0)return{kind:`updated`,appended:l,alreadyPresent:u,removed:[]};let d=l.length===0||s.length===0||s.endsWith(`
1588
1588
  `)?``:`
1589
1589
  `,f=l.length===0?``:`${l.join(`
1590
1590
  `)}\n`;try{j(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function WRe(e,t){let n=x5(e);if(n.kind!==`ok`)return n.result;if(!_(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>S5(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(h5),i.add(g5);for(let t of v5(e))i.add(t);let a;try{a=C(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
1591
1591
  `),s=new Set,c=[];for(let e of o){let t=e.trim();if(i.has(t)){s.add(t);continue}c.push(e)}let l=[...s];if(s.size===0)return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let u=c.join(`
1592
- `);if(u!==a)try{j(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function GRe(e){let t=x5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!_(t.path))return`shared`;let n;try{n=C(t.path,`utf-8`)}catch{return`shared`}let r=w5(n),i=_5(e);for(let e of i)if(C5(r,e))return`local-only`;return r.has(h5)?`local-only`:`shared`}function KRe(e){let t=x5(e);if(t.kind!==`ok`||!_(t.path))return[];let n;try{n=C(t.path,`utf-8`)}catch{return[]}let r=w5(n),i=[..._5(e),...v5(e)].filter(e=>C5(r,e)),a=new Set(i),o=[];for(let e of Object.values(In))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===h5||e===g5){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function y5(e,t){let n=[];for(let r of t){let t=ae(e,r);if(_(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Zwe([r])],N6({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const qRe=/^[\w.\-/]+$/;function JRe(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function YRe(e){return qRe.test(e)?e:JRe(QK(e))}function b5(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}-- ${YRe(e)}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1592
+ `);if(u!==a)try{j(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function GRe(e){let t=x5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!_(t.path))return`shared`;let n;try{n=C(t.path,`utf-8`)}catch{return`shared`}let r=w5(n),i=_5(e);for(let e of i)if(C5(r,e))return`local-only`;return r.has(h5)?`local-only`:`shared`}function KRe(e){let t=x5(e);if(t.kind!==`ok`||!_(t.path))return[];let n;try{n=C(t.path,`utf-8`)}catch{return[]}let r=w5(n),i=[..._5(e),...v5(e)].filter(e=>C5(r,e)),a=new Set(i),o=[];for(let e of Object.values(In))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===h5||e===g5){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function y5(e,t){let n=[];for(let r of t){let t=ae(e,r);if(_(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Zwe([r])],P6({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const qRe=/^[\w.\-/]+$/;function JRe(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function YRe(e){return qRe.test(e)?e:JRe(QK(e))}function b5(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}-- ${YRe(e)}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1593
1593
  `)}function x5(e){let t=rDe(e);switch(t.kind){case`repository`:{let e=t.repository.readCommonDir();if(e.kind===`unreadable`)return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}};let n=F(e.path,`info`);return _(n)?{kind:`ok`,path:F(n,`exclude`)}:{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-info-dir`}}}case`absent`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-git`}};case`malformed-pointer`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`malformed-pointer`}};case`inaccessible`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}}}}function S5(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function C5(e,t){for(let n of S5(t))if(e.has(n))return!0;return!1}function w5(e){let t=new Set;for(let n of e.split(`
1594
1594
  `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function XRe(e,t){return ZRe(L(t,e))}function ZRe(e){return oe===`/`?e:e.split(oe).join(`/`)}function T5(e){switch(e?.code){case`EACCES`:case`EPERM`:return`permission-denied`;case`ELOOP`:return`unresolved-symlink`;case`EISDIR`:case`ENOTDIR`:return`not-a-file`;case`ENOENT`:return`disappeared`;default:return`unreadable`}}function E5(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions, then retry`;case`missing-symlink-target`:return`the symlink target is missing; restore the target or correct the symlink, then retry`;case`unresolved-symlink`:return`the path or symlink could not be resolved; check path permissions and repair any symlink cycle, then retry`;case`not-a-file`:return`the path is not a regular file; restore the intended configuration file, then retry`;case`disappeared`:return`the file disappeared; retry to check its current state`;case`unreadable`:return`the file could not be read; check that the path is accessible, then retry`;default:throw Error(`unhandled configuration file decline reason: ${e}`)}}function QRe(e){for(let t of e.split(`
1595
1595
  `)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function D5(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function O5(e){try{return ee(e).mode&511}catch{return}}function $Re(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
@@ -1614,7 +1614,7 @@ export default function okBridge(pi: {
1614
1614
  `);if(n===-1)return null;let r,i;try{r=i7(JSON.parse(t.slice(0,n))),i=i7(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=i7(e);t===null||typeof t.name!=`string`||!J5(t.name)||a.push({name:t.name,pid:r7(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:r7(t.rpages),lifetimeMaxPages:r7(t.lifetimeMax)})}let o=q5(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:r7(i7(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?J5(i.largestProcess):null,ownedProcesses:a}}const o7=/^JetsamEvent-.*\.ips$/;function s7(e,t,n,r){let i=e.flatMap(({file:e,mtimeMs:n})=>n!==null&&n>=t?[{file:e,mtimeMs:n}]:[]);return i.sort((e,t)=>r===`newest-first`?t.mtimeMs-e.mtimeMs:e.mtimeMs-t.mtimeMs),{files:i.slice(0,n).map(({file:e})=>e),statFailed:e.filter(({mtimeMs:e})=>e===null).length,droppedOverCap:Math.max(0,i.length-n)}}async function Oze(e,t){let n=e7(`darwin`,`macos-jetsam`,[F(e,`JetsamEvent-*.ips`)]),r;try{r=await Ce(e)}catch(e){return t7(n,e.code??`unknown`)}let i=s7(await Promise.all(r.filter(e=>o7.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await Ee(F(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-X5,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=a7(t,await Se(F(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return n7(n)}const kze=new Set([`vm-pageshortage`,`vm-compressor-thrashing`,`vm-pageout-starvation`,`low-swap`,`sustained-memory-pressure`]);function Aze(e,t=Z5){let n;try{n=T(t)}catch(e){return{outcome:`unavailable`,unavailableReason:e.code??`unknown`}}let r=e.fromMs-1e3,i=null,a=n.filter(e=>o7.test(e)).map(e=>{try{return{file:e,mtimeMs:ee(F(t,e)).mtimeMs}}catch(t){return i??=t.code??`unknown`,{file:e,mtimeMs:null}}}),o=s7(a,r,5,`oldest-first`),s=0,c=o.statFailed,l=0,u=null;for(let n of o.files){let i;try{i=C(F(t,n),`utf8`)}catch(e){c+=1,u??=e.code??`unknown`;continue}s+=1;let a=a7(n,i);if(a===null){l+=1;continue}let o=a.at===null?null:Date.parse(a.at);if(o!==null&&(o<r||o>e.toMs))continue;let d=a.ownedProcesses.find(t=>t.pid===e.pid&&t.killReason!==null);if(d!==void 0&&d.killReason!==null)return{outcome:`killed`,source:`macos-jetsam`,at:a.at,killReason:d.killReason,victimChosenByPriority:kze.has(d.killReason),largestProcessOwned:a.largestProcessOwned,residentBytes:d.residentPages===null||a.pageSize===null?null:d.residentPages*a.pageSize,reportsRead:s}}if(i!==null&&o.statFailed===a.length)return{outcome:`unavailable`,unavailableReason:i};if(s===0&&u!==null)return{outcome:`unavailable`,unavailableReason:u};let d=o.droppedOverCap;return c===0&&l===0&&d===0?{outcome:`not-killed`,reportsRead:s,unreadable:0,unparseable:0,skippedNewerOverCap:0}:{outcome:`inconclusive`,reportsRead:s,unreadable:c,unparseable:l,skippedNewerOverCap:d}}const c7=[`--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`],l7=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],u7=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,jze=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,Mze=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function Nze(e,t){let n=new Set,r;try{r=await Ce(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!Mze.test(a))continue;let r=F(e,a);try{if(t.getTime()-(await Ee(r)).mtimeMs>X5)continue;for(let e of(await Se(r,`utf8`)).split(`
1615
1615
  `)){if(!e.includes(`"event":"desktop.boot"`))continue;let t=/"pid":(\d+)/.exec(e)?.[1];t!==void 0&&n.add(Number(t))}}catch{i=!0}}return{pids:n,unreadable:i}}function Pze(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:Q5.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 Fze(e){let t=[],n=0,r=0;for(let i of e.split(`
1616
1616
  `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!Q5.test(s)){n+=1;continue}let c=Pze(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function Ize(e){let t=[],n=0,r=0;for(let i of e.split(`
1617
- `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=jze.exec(o);if(s===null){n+=1;continue}t.push({at:a,pid:Number(s[1]),detail:(s[2]??``).slice(0,200)})}return{lines:t,foreignIgnored:n,unparseable:r}}async function Lze(e,t,n){let r=Ize(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await Nze(t,n),a=[],o=0;for(let e of r.lines){if(!i.pids.has(e.pid)){o+=1;continue}a.push({kind:`journal`,at:e.at,origin:`chromium`,action:`display-connection-lost`,pid:e.pid,processName:null,unit:null,trigger:/Wayland/.test(e.detail)?`wayland`:`x11`,detail:e.detail})}let s=i.pids.size>0&&!i.unreadable;if(o>0&&!s){let e=i.unreadable?`desktop logs unreadable`:`no desktop.boot pid in desktop logs`;return{events:a,foreignIgnored:r.foreignIgnored,unparseable:r.unparseable,unattributed:`${o} Chromium display line(s) not attributed, ${e}`}}return{events:a,foreignIgnored:r.foreignIgnored+o,unparseable:r.unparseable,unattributed:null}}function d7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function Rze(e,t,n){let r=e7(`linux`,`linux-journal`,[`journalctl ${c7.join(` `)}`,`journalctl ${l7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...c7]),e(`journalctl`,[...l7])]),o=[];if(d7(i)){let e=Fze(i.stdout);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,/not seeing messages from other users/i.test(`${i.stdout}\n${i.stderr}`)&&(r.restrictedToCurrentUser=!0)}else o.push(`system journal: ${$5(i)}`);if(d7(a)){let e=await Lze(a.stdout,n,t);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,e.unattributed!==null&&o.push(`user journal: ${e.unattributed}`)}else o.push(`user journal: ${$5(a)}`);return o.length===2?t7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(r)}const zze={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},Bze={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function f7(e){return e===`System`?zze:Bze}function Vze(e){let t=`System[(${Object.keys(f7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${X5}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${Tze.map(e=>`Data='${e}'`).join(` or `)}]]`}function p7(e){return[`qe`,e,`/q:${Vze(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function Hze(e){return se.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function Uze(e){return e.replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}function Wze(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function m7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>Uze(e[1]??``).trim())}function Gze(e,t){let n=f7(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=m7(o,`Data`),u=m7(o,`Name`),d=[...l,...u].some(e=>Q5.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!==``&&!Wze(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function Kze(e,t){let n=Hze(t),r=[`System`,`Application`],i=e7(`win32`,`windows-event-log`,r.map(e=>`${n} ${p7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,p7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${$5(t)}`);continue}let n=Gze(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?t7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(i)}async function h7(e={}){let t=e.platform??process.platform,n=e.runCommand??Eze(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return Oze(e.macosReportsDir??Z5,r);case`linux`:return Rze(n,r,e.desktopLogsDir??F(St(),`logs`));case`win32`:return Kze(n,e.systemRoot??process.env.SystemRoot);default:return{...e7(t,null,[]),outcome:`unsupported`}}}const qze={schemaVersion:1,outcome:`not-collected`};function g7(e){return`${JSON.stringify(e??qze,null,2)}\n`}const Jze=tt.stable.appId;function _7(){return F(St(),`bug-reports`)}function Yze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=_7(),r=`${t}-bugreport`,i=F(n,`${r}.zip`);for(let e=2;_(i);e+=1)i=F(n,`${r}-${e}.zip`);return i}function v7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function y7(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let e=C(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 _(F(e,`.ok`))?ye(`sha256`).update(ae(e)).digest(`hex`).slice(0,12):null}function Xze(){let e={timestamp:new Date().toISOString(),platform:pe(),osType:_e(),osRelease:me(),hostname:`[redacted]`,uptime:ve(),freeMem:ue(),totalMem:ge(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,N6({encoding:`utf8`})).trim()}catch{}try{let t=F(__dirname,`..`,`..`,`package.json`);_(t)&&(e.okVersion=JSON.parse(C(t,`utf8`)).version)}catch{}return e}const Zze=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function b7(e){let t=ne(e);return Zze.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function Qze(e,t){return C7(e,t).files}const $ze=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function x7(e,t=Jze){let n=F(e,`${t}.ShipIt`);if(!_(n))return[];let r;try{r=T(n)}catch{return[]}return $ze.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).map(e=>{let t=F(n,e.entry);return{path:t,suffix:e.suffix,mtimeMs:eBe(t)}}).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.suffix-e.suffix).slice(0,4).map(e=>e.path))}function eBe(e){try{return ee(e).mtimeMs}catch{return 0}}function S7(e){if(!_(e))return[];try{let t=new Map;for(let n of T(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):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=>F(e,t))}catch{return[]}}function C7(e,t){if(!_(t))return{files:[],excludedByProjectSlug:0};let n=T(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>F(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(b7),i=[],a=r.filter(t=>{try{return C(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=>!b7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function tBe(e){let t=F(e,`.ok`,`local`);return _(t)?{files:[`server.lock`,Uf,Vf].map(e=>F(t,e)).filter(e=>_(e))}:{files:[]}}function w7(e,t,n){let r=_J(e),i=[],a=[];for(let e of t){let t=F(r,e),o=F(n,e),s=_(t);s&&i.push(t),_(o)&&(s?a:i).push(o)}return{files:i,legacyFiles:a}}function nBe(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#${ye(`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 T7(e){let t=e.revealDocNames?e.content:nBe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=eF(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 E7(e){for(let t of e.files)try{let n=C(t,`utf8`);T7({zipfile:e.zipfile,name:`${e.prefix}/${ne(t)}`,content:t.endsWith(`.ips`)?K5(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 rBe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??F(St(),`logs`),s=t.projectDir?y7(t.projectDir,i):null;y(N(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=Xze();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=C7(s,o),{files:d}=t.projectDir?tBe(t.projectDir):{files:[]},{files:f,legacyFiles:p}=t.projectDir?w7(t.projectDir,[Bf.logsCurrent,Bf.logsPrevious],F(t.projectDir,`.ok`,`local`,`logs`)):{files:[],legacyFiles:[]},{files:m,legacyFiles:h}=t.projectDir?w7(t.projectDir,[zf],F(t.projectDir,`.ok`,`local`)):{files:[],legacyFiles:[]},_=t.shipItLogFiles??[],v=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length+m.length+h.length,localSinkFileCount:f.length+p.length,shipItLogFileCount:_.length,diagnosticReportCount:v.length},`files collected`);let b=[],x=[],{ZipFile:S}=await Promise.resolve().then(()=>e(xZ(),1)),w=new S;E7({zipfile:w,files:[...l,..._],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:[...d,...m],prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:p,prefix:`legacy/local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:h,prefix:`legacy/lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:t.bugReportLedgerFiles??[],prefix:JK,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:v,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i});for(let e of t.extraFiles??[])try{let t=C(e.sourcePath),n=`extra/${e.zipName??ne(e.sourcePath)}`;w.addBuffer(t,n),x.push(n);let r=v7(e,n);r!==null&&b.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&T7({zipfile:w,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:x,redactions:b});let T=new Set(v.map(e=>`diagnostic-reports/${ne(e)}`)),E=x.filter(e=>T.has(e)),D=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(t.diagnosticReports,E.length);w.addBuffer(Buffer.from(`${D}\n`,`utf8`),`state/diagnostic-reports-status.txt`),x.push(`state/diagnostic-reports-status.txt`),T7({zipfile:w,name:Y5,content:g7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:x,redactions:b});let O=JSON.stringify(c,null,2);w.addBuffer(Buffer.from(O,`utf8`),`sysinfo.json`),x.push(`sysinfo.json`);let k={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:x,redactions:b,sysinfo:c};w.addBuffer(Buffer.from(JSON.stringify(k,null,2),`utf8`),`MANIFEST.json`);let A=b.reduce((e,t)=>e+t.lineCount,0),ee=new Set(_.map(e=>`logs/${ne(e)}`)),te=x.filter(e=>ee.has(e)),j=new Set((t.bugReportLedgerFiles??[]).map(e=>`${JK}/${ne(e)}`)),M=x.filter(e=>j.has(e)),P=s?x.filter(e=>e.startsWith(`logs/`)&&!b7(e)&&!ee.has(e)):[],re=E.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.`]:[],ie=re.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...re]:[`Redaction was disabled for this bundle; file contents are unmodified.`],I=[`# Bug Report Bundle`,``,`Generated: ${k.generatedAt}`,`Project: ${s??`(unscoped)`}`,...t.projectDir?[`Project diagnostic source: ${xt(`logs`,`projects`)} (current product only).`]:[],`Discipline version: ${k.disciplineVersion}`,``,`## Contents`,``,...x.map(e=>`- ${e}`),``,`## Privacy`,``,...P.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:`,...P.map(e=>`- ${e}`),``]:[],...te.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:`,...te.map(e=>`- ${e}`),``]:[],...E.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:`,...E.map(e=>`- ${e}`),``]:[],...(t.osTerminationEvidence?.events.length??0)>0?[`Termination records: read from the operating system's own logs, 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, plus display-connection errors this app's desktop`,`process wrote to the user's own journal, with Chromium's message cut to`,`200 characters. 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:`,`- ${Y5}`,``]:[],...M.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:`,...M.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${$P.join(`, `)}`,A>0?`${A} line(s) were scrubbed across ${b.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...re,``,`This bundle is safe to attach to a GitHub issue.`]:ie].join(`
1617
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=jze.exec(o);if(s===null){n+=1;continue}t.push({at:a,pid:Number(s[1]),detail:(s[2]??``).slice(0,200)})}return{lines:t,foreignIgnored:n,unparseable:r}}async function Lze(e,t,n){let r=Ize(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await Nze(t,n),a=[],o=0;for(let e of r.lines){if(!i.pids.has(e.pid)){o+=1;continue}a.push({kind:`journal`,at:e.at,origin:`chromium`,action:`display-connection-lost`,pid:e.pid,processName:null,unit:null,trigger:/Wayland/.test(e.detail)?`wayland`:`x11`,detail:e.detail})}let s=i.pids.size>0&&!i.unreadable;if(o>0&&!s){let e=i.unreadable?`desktop logs unreadable`:`no desktop.boot pid in desktop logs`;return{events:a,foreignIgnored:r.foreignIgnored,unparseable:r.unparseable,unattributed:`${o} Chromium display line(s) not attributed, ${e}`}}return{events:a,foreignIgnored:r.foreignIgnored+o,unparseable:r.unparseable,unattributed:null}}function d7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function Rze(e,t,n){let r=e7(`linux`,`linux-journal`,[`journalctl ${c7.join(` `)}`,`journalctl ${l7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...c7]),e(`journalctl`,[...l7])]),o=[];if(d7(i)){let e=Fze(i.stdout);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,/not seeing messages from other users/i.test(`${i.stdout}\n${i.stderr}`)&&(r.restrictedToCurrentUser=!0)}else o.push(`system journal: ${$5(i)}`);if(d7(a)){let e=await Lze(a.stdout,n,t);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,e.unattributed!==null&&o.push(`user journal: ${e.unattributed}`)}else o.push(`user journal: ${$5(a)}`);return o.length===2?t7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(r)}const zze={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},Bze={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function f7(e){return e===`System`?zze:Bze}function Vze(e){let t=`System[(${Object.keys(f7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${X5}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${Tze.map(e=>`Data='${e}'`).join(` or `)}]]`}function p7(e){return[`qe`,e,`/q:${Vze(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function Hze(e){return se.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function Uze(e){return e.replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}function Wze(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function m7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>Uze(e[1]??``).trim())}function Gze(e,t){let n=f7(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=m7(o,`Data`),u=m7(o,`Name`),d=[...l,...u].some(e=>Q5.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!==``&&!Wze(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function Kze(e,t){let n=Hze(t),r=[`System`,`Application`],i=e7(`win32`,`windows-event-log`,r.map(e=>`${n} ${p7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,p7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${$5(t)}`);continue}let n=Gze(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?t7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(i)}async function h7(e={}){let t=e.platform??process.platform,n=e.runCommand??Eze(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return Oze(e.macosReportsDir??Z5,r);case`linux`:return Rze(n,r,e.desktopLogsDir??F(St(),`logs`));case`win32`:return Kze(n,e.systemRoot??process.env.SystemRoot);default:return{...e7(t,null,[]),outcome:`unsupported`}}}const qze={schemaVersion:1,outcome:`not-collected`};function g7(e){return`${JSON.stringify(e??qze,null,2)}\n`}const Jze=tt.stable.appId;function _7(){return F(St(),`bug-reports`)}function Yze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=_7(),r=`${t}-bugreport`,i=F(n,`${r}.zip`);for(let e=2;_(i);e+=1)i=F(n,`${r}-${e}.zip`);return i}function v7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function y7(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let e=C(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 _(F(e,`.ok`))?ye(`sha256`).update(ae(e)).digest(`hex`).slice(0,12):null}function Xze(){let e={timestamp:new Date().toISOString(),platform:pe(),osType:_e(),osRelease:me(),hostname:`[redacted]`,uptime:ve(),freeMem:ue(),totalMem:ge(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,P6({encoding:`utf8`})).trim()}catch{}try{let t=F(__dirname,`..`,`..`,`package.json`);_(t)&&(e.okVersion=JSON.parse(C(t,`utf8`)).version)}catch{}return e}const Zze=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function b7(e){let t=ne(e);return Zze.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function Qze(e,t){return C7(e,t).files}const $ze=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function x7(e,t=Jze){let n=F(e,`${t}.ShipIt`);if(!_(n))return[];let r;try{r=T(n)}catch{return[]}return $ze.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).map(e=>{let t=F(n,e.entry);return{path:t,suffix:e.suffix,mtimeMs:eBe(t)}}).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.suffix-e.suffix).slice(0,4).map(e=>e.path))}function eBe(e){try{return ee(e).mtimeMs}catch{return 0}}function S7(e){if(!_(e))return[];try{let t=new Map;for(let n of T(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):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=>F(e,t))}catch{return[]}}function C7(e,t){if(!_(t))return{files:[],excludedByProjectSlug:0};let n=T(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>F(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(b7),i=[],a=r.filter(t=>{try{return C(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=>!b7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function tBe(e){let t=F(e,`.ok`,`local`);return _(t)?{files:[`server.lock`,Uf,Vf].map(e=>F(t,e)).filter(e=>_(e))}:{files:[]}}function w7(e,t,n){let r=_J(e),i=[],a=[];for(let e of t){let t=F(r,e),o=F(n,e),s=_(t);s&&i.push(t),_(o)&&(s?a:i).push(o)}return{files:i,legacyFiles:a}}function nBe(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#${ye(`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 T7(e){let t=e.revealDocNames?e.content:nBe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=eF(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 E7(e){for(let t of e.files)try{let n=C(t,`utf8`);T7({zipfile:e.zipfile,name:`${e.prefix}/${ne(t)}`,content:t.endsWith(`.ips`)?K5(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 rBe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??F(St(),`logs`),s=t.projectDir?y7(t.projectDir,i):null;y(N(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=Xze();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=C7(s,o),{files:d}=t.projectDir?tBe(t.projectDir):{files:[]},{files:f,legacyFiles:p}=t.projectDir?w7(t.projectDir,[Bf.logsCurrent,Bf.logsPrevious],F(t.projectDir,`.ok`,`local`,`logs`)):{files:[],legacyFiles:[]},{files:m,legacyFiles:h}=t.projectDir?w7(t.projectDir,[zf],F(t.projectDir,`.ok`,`local`)):{files:[],legacyFiles:[]},_=t.shipItLogFiles??[],v=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length+m.length+h.length,localSinkFileCount:f.length+p.length,shipItLogFileCount:_.length,diagnosticReportCount:v.length},`files collected`);let b=[],x=[],{ZipFile:S}=await Promise.resolve().then(()=>e(xZ(),1)),w=new S;E7({zipfile:w,files:[...l,..._],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:[...d,...m],prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:p,prefix:`legacy/local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:h,prefix:`legacy/lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:t.bugReportLedgerFiles??[],prefix:JK,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:v,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i});for(let e of t.extraFiles??[])try{let t=C(e.sourcePath),n=`extra/${e.zipName??ne(e.sourcePath)}`;w.addBuffer(t,n),x.push(n);let r=v7(e,n);r!==null&&b.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&T7({zipfile:w,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:x,redactions:b});let T=new Set(v.map(e=>`diagnostic-reports/${ne(e)}`)),E=x.filter(e=>T.has(e)),D=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(t.diagnosticReports,E.length);w.addBuffer(Buffer.from(`${D}\n`,`utf8`),`state/diagnostic-reports-status.txt`),x.push(`state/diagnostic-reports-status.txt`),T7({zipfile:w,name:Y5,content:g7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:x,redactions:b});let O=JSON.stringify(c,null,2);w.addBuffer(Buffer.from(O,`utf8`),`sysinfo.json`),x.push(`sysinfo.json`);let k={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:x,redactions:b,sysinfo:c};w.addBuffer(Buffer.from(JSON.stringify(k,null,2),`utf8`),`MANIFEST.json`);let A=b.reduce((e,t)=>e+t.lineCount,0),ee=new Set(_.map(e=>`logs/${ne(e)}`)),te=x.filter(e=>ee.has(e)),j=new Set((t.bugReportLedgerFiles??[]).map(e=>`${JK}/${ne(e)}`)),M=x.filter(e=>j.has(e)),P=s?x.filter(e=>e.startsWith(`logs/`)&&!b7(e)&&!ee.has(e)):[],re=E.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.`]:[],ie=re.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...re]:[`Redaction was disabled for this bundle; file contents are unmodified.`],I=[`# Bug Report Bundle`,``,`Generated: ${k.generatedAt}`,`Project: ${s??`(unscoped)`}`,...t.projectDir?[`Project diagnostic source: ${xt(`logs`,`projects`)} (current product only).`]:[],`Discipline version: ${k.disciplineVersion}`,``,`## Contents`,``,...x.map(e=>`- ${e}`),``,`## Privacy`,``,...P.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:`,...P.map(e=>`- ${e}`),``]:[],...te.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:`,...te.map(e=>`- ${e}`),``]:[],...E.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:`,...E.map(e=>`- ${e}`),``]:[],...(t.osTerminationEvidence?.events.length??0)>0?[`Termination records: read from the operating system's own logs, 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, plus display-connection errors this app's desktop`,`process wrote to the user's own journal, with Chromium's message cut to`,`200 characters. 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:`,`- ${Y5}`,``]:[],...M.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:`,...M.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${$P.join(`, `)}`,A>0?`${A} line(s) were scrubbed across ${b.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...re,``,`This bundle is safe to attach to a GitHub issue.`]:ie].join(`
1618
1618
  `);w.addBuffer(Buffer.from(I,`utf8`),`README.md`),w.end();let L=g(r);return w.outputStream.pipe(L),await new Promise((e,t)=>{L.on(`close`,e),L.on(`error`,t)}),i?.info({bundlePath:r,fileCount:x.length,redactionCount:A},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:x,redactions:b,redactedLineCount:A,generatedAt:k.generatedAt}}}function iBe(e){if(!e||typeof e!=`object`)return String(e);let t=typeof e.readProcessStart;return`${yq(e)} readProcessStart=${t}`}function D7(e,t={}){if(!Number.isSafeInteger(e)||e<=0||e>4294967295)return null;let n=t.arch??process.arch,r=(e,n,r)=>{xq(n,r),t.onNativeFailure?.({kind:e,reason:bq(n,r)})};try{let i=!1,a=Sq(t.nativeResolver,(e,t)=>{i=!0,r(`unavailable`,e,t)});if(!a||typeof a!=`object`||!(`readProcessStart`in a)||typeof a.readProcessStart!=`function`){let e;return e=a==null?i?`no usable binding was returned`:`the addon was not found`:iBe(a),r(`unavailable`,`the Windows native addon (native-config.win32-${n}-msvc.node) did not load or does not export readProcessStart`,e),null}let o=a.readProcessStart(e);return typeof o==`number`&&Number.isSafeInteger(o)&&o>=0?o:(r(`unavailable`,`readProcessStart returned an invalid value`,yq(o)),null)}catch(e){return r(`query-failed`,`readProcessStart failed`,e),null}}function aBe(e,t={}){return E8(e,{platform:t.platform,readNative:e=>D7(e,{onNativeFailure:t.onNativeFailure})})}function oBe(e){let{platform:t,pid:n,nativeFailures:r,causeRecorded:i}=e,a=r.some(e=>{switch(e.kind){case`unavailable`:return!0;case`query-failed`:return!1;default:return e.kind}}),o=r.length===0?``:a?`Reinstall OpenKnowledge to restore the Windows component that verifies process identity. `:`The Windows component loaded but the operating system refused the query, so reinstalling will not help; retry from an account that can inspect that process. `;return(t===`linux`?`Linux reads the process start from /proc/${n}/stat and /proc/stat; restore read access to /proc and retry. `:t===`darwin`?`macOS reads the process start with ps, and that read failed, as it does inside some sandboxes; retry from a shell where ps can run. `:t===`win32`?o:``)+(r.length>0&&i?`The failure detail is recorded in the CLI log under ${xt(`logs`)}. `:``)}function sBe(e){let t=new Set;return jLe(n=>{let r=[],i=D7(n,{onNativeFailure:e=>{r.push(e)}});for(let i of new Set(r.map(e=>e.kind)))t.has(i)||(t.add(i),(e??void 0)?.warn({event:`process-start-native-failure`,lockPid:n,kind:i,reasons:r.filter(e=>e.kind===i).map(e=>e.reason)},`the Windows process-start query failed, so lock holders cannot be verified; later failures of this kind are not recorded again`));return i})}function O7(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function k7(e){return ye(`sha256`).update(e).digest(`hex`)}function A7(e){return F(St(ae(e)),`pi-trust`)}function j7(e,t){return F(A7(e),k7(ae(t)))}function M7(e,t,n){return F(j7(e,t),`${k7(n)}.json`)}var N7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${O7(e)} ${O7(t)}; ${O7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function P7(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new N7(e,`could not ${t}: ${i}`,a,n)}function F7(e){let t;try{t=v(e)}catch(t){if(t.code===`ENOENT`)return!1;throw P7(e,`be inspected`,t)}if(!t.isDirectory())throw new N7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function I7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function L7(e,t){if(!_q(e)||!I7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==ae(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==ae(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==ae(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!_q(e.previous))throw new N7(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&I7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&I7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new N7(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function R7(e,t,n){let r;try{r=v(n)}catch(e){throw P7(n,`be inspected`,e)}if(!r.isFile())throw new N7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=C(n,`utf8`)}catch(e){throw P7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new N7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=L7(a,n);if(o.cwd!==ae(t)||n!==M7(e,t,o.canonicalTrustPath))throw new N7(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function z7(e,t){let{record:n,path:r}=t;for(let t of[A7(e),j7(e,n.cwd)])if(!F7(t))throw new N7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=R7(e,n.cwd,r);if(!je(i.record,n))throw new N7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function cBe(e,t,n,r,i){let a={version:1,cwd:ae(t),configuredTrustPath:ae(n),canonicalTrustPath:ae(r),state:`pending`,previous:i},o=M7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!je(L7(JSON.parse(s),o),a))throw new N7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);F7(A7(e)),F7(N(o));try{y(N(o),{recursive:!0,mode:448})}catch(e){throw P7(N(o),`be created`,e)}let c;try{c=v(o,{throwIfNoEntry:!1})}catch(e){throw P7(o,`be inspected`,e)}if(c)throw new N7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{Tt(o,s,{mode:384})}catch(e){throw P7(o,`be written`,e)}return{path:o,record:a}}function lBe(e,t){let n=z7(e,t);if(n.record.state!==`pending`)throw new N7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{Tt(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw P7(n.path,`be committed`,e)}return{path:n.path,record:r}}function B7(e,t){if(!F7(A7(e)))return[];let n=j7(e,t);if(!F7(n))return[];let r;try{r=T(n).sort()}catch(e){throw P7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>R7(e,t,F(n,r)))}function V7(e,t){let n=z7(e,t);try{te(n.path)}catch(e){throw P7(n.path,`be removed after reconciling its grant`,e)}for(let t of[N(n.path),A7(e)])try{A(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw P7(t,`be removed after reconciling its grant`,e)}}var uBe=i(((e,n)=>{var r=t(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),dBe=i(((e,n)=>{var r=t(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),fBe=i(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),H7=i(((e,n)=>{var r=t(`fs`),i=uBe(),a=dBe(),o=fBe(),s=t(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
1619
1619
  GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),t(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),pBe=i(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),mBe=i((e=>{var t=pBe();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),hBe=i(((e,t)=>{t.exports=mBe()})),gBe=i(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),_Be=i(((e,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=t(`assert`),o=gBe(),s=/^win/i.test(r.platform),c=t(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),vBe=i(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),yBe=i(((e,n)=>{let r=t(`path`),i=H7(),a=hBe(),o=_Be(),s=vBe(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),bBe=i(((e,t)=>{let n=H7();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),U7=e(i(((e,t)=>{let n=yBe(),{toPromise:r,toSync:i,toSyncOptions:a}=bBe();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const W7=5e3;function G7(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${W7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function K7(e,t){}function q7(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function xBe(e,t,n){await nEe(`${t}.ok.lock`,async()=>{let t=performance.now()+W7,r;for(;;)try{r=await U7.default.lock(N(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Le(G7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}q7(i,e)},{onWarn:K7})}function SBe(e,t,n){pJ(`${t}.ok.lock`,()=>{let t=performance.now()+W7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=U7.default.lockSync(N(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,G7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}q7(a,e)},{onWarn:K7})}const CBe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var J7=class extends Error{name=`PiResourceInspectionError`};function Y7(e){let t;try{t=v(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=ee(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new J7(E5(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function wBe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function TBe(e,t,n){let r=e;try{let i=D(e),a;r=t;try{a=D(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=ae(t)}let o=F(a,`.agents`,`skills`),s=[];for(let e of CBe)r=F(i,`.pi`,e),Y7(r)&&s.push(r);if(r=F(i,`.pi`,`extensions`),Y7(r))for(let t of T(r).sort()){let i=F(r,t);ae(n)!==F(ae(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[F(i,`.pi`,`skills`),F(i,`.agents`,`skills`)])if(e!==o&&(r=e,Y7(e)))for(let t of T(e).sort())wBe(t)||s.push(F(e,t));let c=N(i);for(;c!==i;){r=F(c,`.agents`,`skills`),r!==o&&Y7(r)&&s.push(r);let e=N(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${O7(r)}: ${e instanceof J7?e.message:E5(T5(e))}`}}}function X7(e){let t;try{t=v(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:T5(e)}}let n=m5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!ee(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:T5(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function Z7(e,t,n){let r=ae(e),i=aJ({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:sJ.pi.projectConfigPath(r),trustPath:F(i,`trust.json`)}}function Q7(e){try{let t=D(e);return ee(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${O7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${O7(e)} could not be resolved or accessed: ${O7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function $7(e){let t=Q7(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${O7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function e9(e,t,n){let r=H5(sJ.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return Bq(i)?{state:`own-current`,text:a}:n5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function t9(e,t){let n;try{n=C(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:T5(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return _q(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
1620
1620
  `)}:{state:`unreadable`,reason:`invalid-json`}}function EBe(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return E5(e)}}function n9(e,t){return{kind:`refused`,error:`trust store ${O7(e)}: ${EBe(t)}`}}function r9(e){let t=X7(e);try{switch(t.kind){case`declined`:return n9(e,t.reason);case`ready`:return{kind:`ready`,path:D(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=N(e),r=[ne(e)],i=v(n,{throwIfNoEntry:!1});for(;!i;){let t=N(n);if(t===n)return n9(e,`unavailable-root`);r.unshift(ne(n)),n=t,i=v(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:F(D(n),...r)}}catch(t){return n9(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:T5(t))}}catch(t){return n9(e,T5(t))}}function i9(e,t){let n=r9(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?n9(e,`path-changed`):n}function DBe(e,t,n){let r=Z7(e,t,n),i=Q7(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=e9(r.cwd,r.bridgePath,t).state,o=r9(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:t9(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:OBe(r.bridgePath).displayNames}}function OBe(e){let t=N(e),n=ne(e);try{return{displayNames:T(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>O7(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function kBe(e,t={mode:`published`},n,r,i){let a=Z7(e,n,r),o=Q7(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${O7(i)} no longer matches the current directory ${O7(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=e9(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=r5(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=z5(sJ.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:O7(e.error)}}let l=await ABe(a.trustPath,o.project,n??de());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function ABe(e,t,n){let r=t.canonical,i=r9(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{y(N(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:O7(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await xBe(e,i.path,()=>{let o=$7(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=i9(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=t9(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=n9(e,c.reason).error;return}let l=o9(n,()=>{let t=B7(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&V7(n,t),cBe(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
@@ -1630,13 +1630,13 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
1630
1630
  `),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
1631
1631
  `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
1632
1632
  `).replace(/\n/g,`\r
1633
- `));let u=`${i?``:``}${l}`;return u!==r&&Tt(e,u,{mode:O5(e)}),{kind:`removed`}}function BBe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function VBe(e){let{priorCommand:t,priorArgs:n}=u9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function d9(e,t,n={}){let r=$Le(e,t),i;try{i=C(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,text:i}}let o=a&&typeof a==`object`?a:{},s=O8(o),c=s&&!k8(o,n);if(!a||typeof a!=`object`||!TLe(a.pid))return{status:`corrupt`,lockPath:r,text:i,...c?{foreignHost:!0}:{}};let l=eRe(a),{pid:u}=l;if(c)return{status:`foreign-host`,lockPath:r,lock:l};let d=N8(l,{isAlive:n.isAlive,readProcessStart:n.readProcessStart,readBootInstant:n.readBootInstant,sameMachine:s});switch(d.verdict){case`gone`:return{status:`dead-pid`,lockPath:r,lock:l,text:i};case`replaced`:return{status:`reused-pid`,lockPath:r,lock:l,text:i};case`unverified`:return d.cause===`unverified-owner`?{status:`unverified-owner`,lockPath:r,pid:u}:{status:`alive`,lockPath:r,lock:l};case`writer`:return{status:`alive`,lockPath:r,lock:l};default:return d}}function HBe(e){return`does not record its owning machine, and its recorded process ${e} is still running on this machine`}function f9(e){return typeof e.machineId==`string`?`records a machine ID different from the one in ${h8()}`:`records only the host ${O7(e.hostname)}, not this machine's ${fe()}`}function UBe(e){return e===`win32`?`USERPROFILE`:`HOME`}function WBe(e){return e.processStart===void 0?` This lock records no process start; a server started by this release records one, which lets \`${ft()} stop\` confirm it from any home folder.`:``}function GBe(e,t){let n=`\`${ft()} stop\``;return`If the server was started on this machine from another account, run ${n} as that account. If it was started from this account with a different home folder, run ${n} with \`${UBe(t)}\` set to that folder. Otherwise stop it from the machine that owns the lock.${WBe(e)}`}async function KBe(e,t=void 0){let n=d9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=nRe(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 qBe(e,t={}){return $Be(e,t.isAlive??p8)?{targets:[{name:`server`,pid:e.lock.pid,port:e.lock.port}],lock:e.lock}:{targets:[]}}function JBe(e){try{return lt()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function YBe(e){let t=e.inspect??(()=>d9(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??KBe,o=e.logger??void 0,s=e.platform??process.platform,c=t(),l=qBe(c,{isAlive:e.isAlive}),{lock:u}=l,d=[],f=[],p=(t,n)=>{o?.warn({lockDir:e.lockDir,lockPath:n.lockPath,lockPid:n.pid,platform:s,cause:n.cause,...`nativeFailures`in n&&n.nativeFailures.length>0?{nativeFailures:n.nativeFailures}:{}},`stop declined: lock holder identity unverified`),f.push({target:t,error:ZBe(n,o!==void 0),unverified:n})},m=()=>{if(d.length>0){let e=d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);r(`Stopped: ${e}`)}if(o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0){let e=f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `);i(`Failed to stop: ${e}`)}return{stopped:d,failed:f,hadTargets:!0}};if(c.status===`unverified-owner`){let{pid:e,lockPath:t}=c;return p({name:`server`,pid:e},{cause:`unverified-owner`,pid:e,lockPath:t}),m()}if(u===void 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 h=c.status===`alive`||c.status===`foreign-host`?c.lock.channel:void 0;if(e.force!==!0&&typeof h==`string`&&h.length>0){let t=e.selfChannel??JBe(o);if(t!==void 0&&h!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(h)}. `+(h===`dev`?`Stop it from that dev build, or run \`${pt} stop\` with OK_CHANNEL=dev set, or re-run with --force to terminate anyway.`:`Stop it from that app or its CLI, or re-run with --force to terminate anyway.`)),o?.warn({lockDir:e.lockDir,holderChannel:h,selfChannel:t,pids:l.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:h}}}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:l.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}for(let t of l.targets){let a=[],o=(e.readProcessStart??aBe)(t.pid,{platform:s,onNativeFailure:e=>{a.push(e)}}),l=N8(u,{isAlive:e.isAlive??p8,readProcessStart:()=>o,refuseHolderStartedAfterLock:e.refuseHolderStartedAfterLock,platform:s,readBootInstant:e.readBootInstant});switch(l.verdict){case`writer`:try{n(t.pid,`SIGTERM`),d.push(t)}catch(e){f.push({target:t,error:e instanceof Error?e.message:String(e)})}break;case`gone`:r(`${t.name} (pid=${t.pid}) had already exited`);break;case`replaced`:i(`Process ${t.pid} is no longer the server that wrote ${c.lockPath}; it was not signalled. Run \`${ft()} clean\` to remove the stale lock.`);break;case`unverified`:p(t,XBe(l.cause,{pid:t.pid,lockPath:c.lockPath,lock:u,platform:s,nativeFailures:a}));break;default:return l}}return m()}function XBe(e,t){let{pid:n,lockPath:r}=t;switch(e){case`foreign-host`:return{cause:e,pid:n,lockPath:r,lock:t.lock,platform:t.platform};case`unverified-owner`:return{cause:e,pid:n,lockPath:r};default:return{cause:e,pid:n,lockPath:r,platform:t.platform,nativeFailures:t.nativeFailures}}}const p9=`it was not signalled, and --force does not override this check.`;function ZBe(e,t){let{pid:n,lockPath:r}=e;switch(e.cause){case`foreign-host`:{let{lock:t}=e;return typeof t.machineId==`string`?`The server lock at ${r} ${f9(t)}, so process ${n}, which is running on this machine, cannot be confirmed as the server that wrote it; ${p9} ${GBe(t,e.platform)}`:`The server lock at ${r} ${f9(t)}, and the start of process ${n}, which is running on this machine, does not confirm it as the server that wrote the lock; ${p9} If ${O7(t.hostname)} is another machine, stop the server there. If it is an earlier name of this machine, confirm that process ${n} is an OpenKnowledge server before ending it yourself, and once no OpenKnowledge server is running for this project, remove ${r}.`}case`unverified-owner`:return`The server lock at ${r} ${HBe(n)}, so it cannot be confirmed as the server that wrote the lock; ${p9} Check whether process ${n} is an OpenKnowledge server, and if it is, stop it yourself. Do not remove the lock file while that process is running.`;default:{let n=QBe(e,p9,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${r}.`,t);return e.cause===`writer-identity-unrecorded`?`${n} A server you start again with this release records its machine ID, so \`${ft()} stop\` can confirm it.`:n}}}function QBe(e,t,n,r){let{pid:i,lockPath:a,platform:o,nativeFailures:s}=e,c=`Before ending process ${i} yourself, confirm that it is an OpenKnowledge server.`;switch(e.cause){case`process-start-unreadable`:return`Could not read when process ${i} started, so it cannot be confirmed as the server that wrote ${a}; ${t} `+oBe({platform:o,pid:i,nativeFailures:s,causeRecorded:r})+`${c} ${n}`;case`process-start-incomparable`:return`The start of process ${i} cannot be compared with the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-start-mismatch`:return`Process ${i} started before the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-started-after-lock`:return`Process ${i} started after the server lock at ${a} was written, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`recorded-start-in-future`:return`The server lock at ${a} records a start later than the current time on this machine, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;case`writer-identity-unrecorded`:return`The server lock at ${a} records neither a machine ID nor a process start, as locks written by version 0.25.0 and earlier do, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;default:return e.cause}}function $Be(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function m9(e){if(!_(e))return{value:null,path:e,source:null,doc:null};let t;try{t=C(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,On.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return _q(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function eVe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=_f({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function tVe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=hJ(`user`,t),s=dJ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=m9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=Sf({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?wf(i.value):i.value;return t&&a.push(...Uwe({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=ae(t,`.ok`,`config.yml`),u=c(l,!0),d=c(hJ(`project-local`,t)),f=Joe(s.value,u,d),p=mRe.safeParse(f);if(!p.success){let e=m9(l),t={code:`SCHEMA_INVALID`,issues:eVe(p.error.issues,e)};throw Error(qoe(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function h9(e){return e.replace(/:\d+$/,``)}function g9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:h9(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}function _9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=eu(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=eu(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function nVe(e){let t=_9(e);if(t)return{kind:`doc`,...t};let n=v9(e);return n?{kind:`folder`,...n}:null}async function rVe(e,t){let n,r;try{n=await we(ae(e)),r=await we(ae(N(e)))}catch{return{kind:`not-git`}}if(!y9(n,r))return{kind:`symlink-escape`};let i=F(n,`.git`),a;try{a=ee(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await we(i)}catch{return{kind:`not-git`}}if(!y9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=nDe(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=g9(c);if(l===null)return{kind:`non-github`};let u=eu(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function y9(e,t){if(e===t)return!0;let n=L(t,e);return n.length>0&&!n.startsWith(`..`)&&!re(n)}const iVe=`# >>> open-knowledge cli >>>`,aVe=`# <<< open-knowledge cli <<<`,oVe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function sVe(e,t=process.platform,n=process.env){return Gwe(lt(),e,t,n.XDG_CONFIG_HOME)}function b9(e,t,n=[]){let r=_(F(e,E6[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function cVe(e,t){let n=Eq.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=Rn.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:YS}));return[...n,...r]}function x9(e,t,n,r){let i=DPe(e,cVe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function lVe(e,t){let n=(t??de()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function uVe(e,t){let n=sJ[e];return R5(n,``,t)&&!L5(n,``,t)}function S9(e,t,n,r,i){let a=sJ[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?lVe(o,r):void 0,c=H5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&uVe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];Bq(r)&&i.push(`reclaim-permissive`),Uq(r)&&i.push(`pre-approval-exact`),U5(e)(r)&&i.push(`injection-functional`);let o=Qq(a,n);return i.length>0&&(o!==null&&LTe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:MTe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function dVe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Us(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:b9(F(n,YS),`discovery`,x9(n,Ln,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=Ln[i];return e===null||n===void 0?null:R8(n).some(e=>e.editorId===i)?b9(F(n,e),`discovery`,x9(n,Ln,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=In[i];return e===null?null:b9(F(t,e),`project`,x9(t,In,i,`project`))}case`editor-user-config`:return S9(i,e.strictness,t,n);case`editor-project-config`:{let r=sJ[i].projectConfigPath?.(t);return r===void 0?null:S9(i,e.strictness,t,n,r)}}}}[...D6.map(e=>E6[e])];function fVe(e){if(!re(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=ae(e);if(t===oe||N(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function C9(e){let t=fVe(e),n=[];for(let e of D6){let r=E6[e];n.push({path:F(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Vn)n.push({path:F(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function pVe(e,t){let n=[];for(let r of C9(e))if(r.bundleId===t)try{k(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}const mVe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=z5(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=f5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function hVe(e,t,n={},r=mVe){let i=[];for(let a of t){let t=sJ[a];for(let a of r)i.push(a.write(t,e,n))}let a=RRe(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function gVe(e,t,n={}){return{integrations:hVe(e,t,n)}}function w9(e,t){let n=Ln[e];return n===null?null:F(t,...n.split(`/`),E6.discovery,`SKILL.md`)}function _Ve(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!R8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=A6(`discovery`,{checkDesktop:!0});return l5(N(n),t),{editorId:e,label:e,action:i5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function vVe(e){return _(F(e,...`.agents/skills`.split(`/`),E6.discovery))?!0:Fn.some(t=>{let n=w9(t,e);return n!==null&&_(N(n))})}function yVe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=N(n);try{return _(n)?(l5(r,t),k(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function bVe(e){return dJ({absPath:hJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function T9({home:e=de(),env:t=process.env}={}){let n=bVe(e),{override:r,preferenceList:i}=dEe(t),{locale:a,source:o}=JP({override:r,storedPreference:n,supportedLocales:bu,preferenceList:i,autoDetectableLocales:Nae});return{preference:n,locale:a,source:o,systemLanguages:i}}function E9(e){let t=new Set([e]);try{t.add(D.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 D9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function xVe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O9(e,t){if(typeof e==`string`)return D9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>O9(e,t));if(!xVe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=O9(i,t);return n}function k9(e,t){let n=C(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1633
+ `));let u=`${i?``:``}${l}`;return u!==r&&Tt(e,u,{mode:O5(e)}),{kind:`removed`}}function BBe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function VBe(e){let{priorCommand:t,priorArgs:n}=u9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function d9(e,t,n={}){let r=$Le(e,t),i;try{i=C(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,text:i}}let o=a&&typeof a==`object`?a:{},s=O8(o),c=s&&!k8(o,n);if(!a||typeof a!=`object`||!TLe(a.pid))return{status:`corrupt`,lockPath:r,text:i,...c?{foreignHost:!0}:{}};let l=eRe(a),{pid:u}=l;if(c)return{status:`foreign-host`,lockPath:r,lock:l};let d=N8(l,{isAlive:n.isAlive,readProcessStart:n.readProcessStart,readBootInstant:n.readBootInstant,sameMachine:s});switch(d.verdict){case`gone`:return{status:`dead-pid`,lockPath:r,lock:l,text:i};case`replaced`:return{status:`reused-pid`,lockPath:r,lock:l,text:i};case`unverified`:return d.cause===`unverified-owner`?{status:`unverified-owner`,lockPath:r,pid:u}:{status:`alive`,lockPath:r,lock:l};case`writer`:return{status:`alive`,lockPath:r,lock:l};default:return d}}function HBe(e){return`does not record its owning machine, and its recorded process ${e} is still running on this machine`}function f9(e){return typeof e.machineId==`string`?`records a machine ID different from the one in ${h8()}`:`records only the host ${O7(e.hostname)}, not this machine's ${fe()}`}function UBe(e){return e===`win32`?`USERPROFILE`:`HOME`}function WBe(e){return e.processStart===void 0?` This lock records no process start; a server started by this release records one, which lets \`${ft()} stop\` confirm it from any home folder.`:``}function GBe(e,t){let n=`\`${ft()} stop\``;return`If the server was started on this machine from another account, run ${n} as that account. If it was started from this account with a different home folder, run ${n} with \`${UBe(t)}\` set to that folder. Otherwise stop it from the machine that owns the lock.${WBe(e)}`}async function KBe(e,t=void 0){let n=d9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=nRe(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 qBe(e,t={}){return $Be(e,t.isAlive??p8)?{targets:[{name:`server`,pid:e.lock.pid,port:e.lock.port}],lock:e.lock}:{targets:[]}}function JBe(e){try{return lt()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function YBe(e){let t=e.inspect??(()=>d9(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??KBe,o=e.logger??void 0,s=e.platform??process.platform,c=t(),l=qBe(c,{isAlive:e.isAlive}),{lock:u}=l,d=[],f=[],p=(t,n)=>{o?.warn({lockDir:e.lockDir,lockPath:n.lockPath,lockPid:n.pid,platform:s,cause:n.cause,...`nativeFailures`in n&&n.nativeFailures.length>0?{nativeFailures:n.nativeFailures}:{}},`stop declined: lock holder identity unverified`),f.push({target:t,error:ZBe(n,o!==void 0),unverified:n})},m=()=>{if(d.length>0){let e=d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);r(`Stopped: ${e}`)}if(o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0){let e=f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `);i(`Failed to stop: ${e}`)}return{stopped:d,failed:f,hadTargets:!0}};if(c.status===`unverified-owner`){let{pid:e,lockPath:t}=c;return p({name:`server`,pid:e},{cause:`unverified-owner`,pid:e,lockPath:t}),m()}if(u===void 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 h=c.status===`alive`||c.status===`foreign-host`?c.lock.channel:void 0;if(e.force!==!0&&typeof h==`string`&&h.length>0){let t=e.selfChannel??JBe(o);if(t!==void 0&&h!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(h)}. `+(h===`dev`?`Stop it from that dev build, or run \`${pt} stop\` with OK_CHANNEL=dev set, or re-run with --force to terminate anyway.`:`Stop it from that app or its CLI, or re-run with --force to terminate anyway.`)),o?.warn({lockDir:e.lockDir,holderChannel:h,selfChannel:t,pids:l.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:h}}}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:l.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}for(let t of l.targets){let a=[],o=(e.readProcessStart??aBe)(t.pid,{platform:s,onNativeFailure:e=>{a.push(e)}}),l=N8(u,{isAlive:e.isAlive??p8,readProcessStart:()=>o,refuseHolderStartedAfterLock:e.refuseHolderStartedAfterLock,platform:s,readBootInstant:e.readBootInstant});switch(l.verdict){case`writer`:try{n(t.pid,`SIGTERM`),d.push(t)}catch(e){f.push({target:t,error:e instanceof Error?e.message:String(e)})}break;case`gone`:r(`${t.name} (pid=${t.pid}) had already exited`);break;case`replaced`:i(`Process ${t.pid} is no longer the server that wrote ${c.lockPath}; it was not signalled. Run \`${ft()} clean\` to remove the stale lock.`);break;case`unverified`:p(t,XBe(l.cause,{pid:t.pid,lockPath:c.lockPath,lock:u,platform:s,nativeFailures:a}));break;default:return l}}return m()}function XBe(e,t){let{pid:n,lockPath:r}=t;switch(e){case`foreign-host`:return{cause:e,pid:n,lockPath:r,lock:t.lock,platform:t.platform};case`unverified-owner`:return{cause:e,pid:n,lockPath:r};default:return{cause:e,pid:n,lockPath:r,platform:t.platform,nativeFailures:t.nativeFailures}}}const p9=`it was not signalled, and --force does not override this check.`;function ZBe(e,t){let{pid:n,lockPath:r}=e;switch(e.cause){case`foreign-host`:{let{lock:t}=e;return typeof t.machineId==`string`?`The server lock at ${r} ${f9(t)}, so process ${n}, which is running on this machine, cannot be confirmed as the server that wrote it; ${p9} ${GBe(t,e.platform)}`:`The server lock at ${r} ${f9(t)}, and the start of process ${n}, which is running on this machine, does not confirm it as the server that wrote the lock; ${p9} If ${O7(t.hostname)} is another machine, stop the server there. If it is an earlier name of this machine, confirm that process ${n} is an OpenKnowledge server before ending it yourself, and once no OpenKnowledge server is running for this project, remove ${r}.`}case`unverified-owner`:return`The server lock at ${r} ${HBe(n)}, so it cannot be confirmed as the server that wrote the lock; ${p9} Check whether process ${n} is an OpenKnowledge server, and if it is, stop it yourself. Do not remove the lock file while that process is running.`;default:{let n=QBe(e,p9,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${r}.`,t);return e.cause===`writer-identity-unrecorded`?`${n} A server you start again with this release records its machine ID, so \`${ft()} stop\` can confirm it.`:n}}}function QBe(e,t,n,r){let{pid:i,lockPath:a,platform:o,nativeFailures:s}=e,c=`Before ending process ${i} yourself, confirm that it is an OpenKnowledge server.`;switch(e.cause){case`process-start-unreadable`:return`Could not read when process ${i} started, so it cannot be confirmed as the server that wrote ${a}; ${t} `+oBe({platform:o,pid:i,nativeFailures:s,causeRecorded:r})+`${c} ${n}`;case`process-start-incomparable`:return`The start of process ${i} cannot be compared with the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-start-mismatch`:return`Process ${i} started before the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-started-after-lock`:return`Process ${i} started after the server lock at ${a} was written, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`recorded-start-in-future`:return`The server lock at ${a} records a start later than the current time on this machine, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;case`writer-identity-unrecorded`:return`The server lock at ${a} records neither a machine ID nor a process start, as locks written by version 0.25.0 and earlier do, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;default:return e.cause}}function $Be(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function m9(e){if(!_(e))return{value:null,path:e,source:null,doc:null};let t;try{t=C(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,On.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return _q(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function eVe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=_f({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function tVe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=hJ(`user`,t),s=dJ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=m9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=Sf({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?wf(i.value):i.value;return t&&a.push(...Uwe({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=ae(t,`.ok`,`config.yml`),u=c(l,!0),d=c(hJ(`project-local`,t)),f=Joe(s.value,u,d),p=mRe.safeParse(f);if(!p.success){let e=m9(l),t={code:`SCHEMA_INVALID`,issues:eVe(p.error.issues,e)};throw Error(qoe(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function h9(e){return e.replace(/:\d+$/,``)}function g9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:h9(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}function _9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=eu(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=eu(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function nVe(e){let t=_9(e);if(t)return{kind:`doc`,...t};let n=v9(e);return n?{kind:`folder`,...n}:null}async function rVe(e,t){let n,r;try{n=await we(ae(e)),r=await we(ae(N(e)))}catch{return{kind:`not-git`}}if(!y9(n,r))return{kind:`symlink-escape`};let i=F(n,`.git`),a;try{a=ee(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await we(i)}catch{return{kind:`not-git`}}if(!y9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=nDe(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=g9(c);if(l===null)return{kind:`non-github`};let u=eu(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function y9(e,t){if(e===t)return!0;let n=L(t,e);return n.length>0&&!n.startsWith(`..`)&&!re(n)}const iVe=`# >>> open-knowledge cli >>>`,aVe=`# <<< open-knowledge cli <<<`,oVe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function sVe(e,t=process.platform,n=process.env){return Gwe(lt(),e,t,n.XDG_CONFIG_HOME)}function b9(e,t,n=[]){let r=_(F(e,O6[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function cVe(e,t){let n=Eq.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=Rn.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:YS}));return[...n,...r]}function x9(e,t,n,r){let i=DPe(e,cVe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function lVe(e,t){let n=(t??de()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function uVe(e,t){let n=sJ[e];return R5(n,``,t)&&!L5(n,``,t)}function S9(e,t,n,r,i){let a=sJ[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?lVe(o,r):void 0,c=H5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&uVe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];Bq(r)&&i.push(`reclaim-permissive`),Uq(r)&&i.push(`pre-approval-exact`),U5(e)(r)&&i.push(`injection-functional`);let o=Qq(a,n);return i.length>0&&(o!==null&&LTe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:MTe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function dVe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Us(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:b9(F(n,YS),`discovery`,x9(n,Ln,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=Ln[i];return e===null||n===void 0?null:R8(n).some(e=>e.editorId===i)?b9(F(n,e),`discovery`,x9(n,Ln,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=In[i];return e===null?null:b9(F(t,e),`project`,x9(t,In,i,`project`))}case`editor-user-config`:return S9(i,e.strictness,t,n);case`editor-project-config`:{let r=sJ[i].projectConfigPath?.(t);return r===void 0?null:S9(i,e.strictness,t,n,r)}}}}[...k6.map(e=>O6[e])];function fVe(e){if(!re(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=ae(e);if(t===oe||N(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function C9(e){let t=fVe(e),n=[];for(let e of k6){let r=O6[e];n.push({path:F(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Vn)n.push({path:F(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function pVe(e,t){let n=[];for(let r of C9(e))if(r.bundleId===t)try{k(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}const mVe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=z5(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=f5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function hVe(e,t,n={},r=mVe){let i=[];for(let a of t){let t=sJ[a];for(let a of r)i.push(a.write(t,e,n))}let a=RRe(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function gVe(e,t,n={}){return{integrations:hVe(e,t,n)}}function w9(e,t){let n=Ln[e];return n===null?null:F(t,...n.split(`/`),O6.discovery,`SKILL.md`)}function _Ve(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!R8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=M6(`discovery`,{checkDesktop:!0});return l5(N(n),t),{editorId:e,label:e,action:i5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function vVe(e){return _(F(e,...`.agents/skills`.split(`/`),O6.discovery))?!0:Fn.some(t=>{let n=w9(t,e);return n!==null&&_(N(n))})}function yVe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=N(n);try{return _(n)?(l5(r,t),k(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function bVe(e){return dJ({absPath:hJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function T9({home:e=de(),env:t=process.env}={}){let n=bVe(e),{override:r,preferenceList:i}=dEe(t),{locale:a,source:o}=JP({override:r,storedPreference:n,supportedLocales:bu,preferenceList:i,autoDetectableLocales:Nae});return{preference:n,locale:a,source:o,systemLanguages:i}}function E9(e){let t=new Set([e]);try{t.add(D.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 D9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function xVe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O9(e,t){if(typeof e==`string`)return D9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>O9(e,t));if(!xVe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=O9(i,t);return n}function k9(e,t){let n=C(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1634
1634
  `),i=n.split(`
1635
1635
  `),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=O9(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
1636
1636
  `)}\n`:a.join(`
1637
1637
  `);j(e,o)}function A9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=O9(JSON.parse(n),t),i=n.endsWith(`
1638
1638
  `)?`
1639
1639
  `:``;j(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}function M9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>F(e,t.name))}catch{return[]}}const SVe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function N9(e){return/\.log\.\d+$/.test(e)}function CVe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||N9(e)}const wVe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function P9(e){let t={contentDirSpellings:E9(e.contentDir)};for(let n of wVe)for(let r of M9(F(e.stagingDir,n)))CVe(r)?k9(r,t):r.endsWith(`.json`)?A9(r,t):j9(r,t);for(let n of M9(F(e.stagingDir,`state`))){let e=ne(n);n.endsWith(`.jsonl`)?k9(n,t):SVe.has(e)?A9(n,t):j9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=Bf.spansCurrent,z9=Bf.spansPrevious,B9=Bf.logsCurrent,V9=Bf.logsPrevious,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function TVe(e){return F(e,...L9,H9)}function EVe(e){return F(e,...L9,U9)}const W9=1e3;async function DVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function OVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function kVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}function AVe(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(`
1640
- `)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){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 NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(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(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(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 $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.10-beta.0`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??NVe,m=r.isOtlpPushEnabled??PVe,g=b(F(he(),`ok-bundle-`));try{y(F(g,`telemetry`),{recursive:!0}),y(F(g,`logs`),{recursive:!0}),y(F(g,`state`),{recursive:!0}),Z9(XEe(n),F(n,...F9,R9),g,F(`telemetry`,R9)),Z9(ZEe(n),F(n,...F9,z9),g,F(`telemetry`,z9)),Z9(dY(n),F(n,...I9,B9),g,F(`logs`,B9)),Z9(fY(n),F(n,...I9,V9),g,F(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,F(g,`logs`,ne(t)));for(let t of e.userStateFiles??[])X9(t,F(g,JK,ne(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,F(g,`diagnostic-reports`,ne(t)))&&(v+=1);let b=F(n,`.ok`,`local`),x=F(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,F(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(j(F(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&j(F(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=AVe(n);e!==null&&j(F(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&j(F(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&j(F(g,`state`,`checkpoint-refs.txt`),D),X9(TVe(n),F(g,`state`,H9)),X9(EVe(n),F(g,`state`,U9)),Z9(pEe(n),F(b,zf),g,`state/last-spawn-error.log`),X9(F(b,Hf),F(g,`state`,Hf)),X9(F(b,Uf),F(g,`state`,Uf)),X9(F(b,Vf),F(g,`state`,Vf));let O=p(),A=d(),te=f(),M={ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te}};j(F(g,`state`,`runtime.json`),`${JSON.stringify(M,null,2)}\n`);let N=S===`running`?`running
1640
+ `)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],P6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],P6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){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 NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(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(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(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 $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.10-beta.2`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??NVe,m=r.isOtlpPushEnabled??PVe,g=b(F(he(),`ok-bundle-`));try{y(F(g,`telemetry`),{recursive:!0}),y(F(g,`logs`),{recursive:!0}),y(F(g,`state`),{recursive:!0}),Z9(XEe(n),F(n,...F9,R9),g,F(`telemetry`,R9)),Z9(ZEe(n),F(n,...F9,z9),g,F(`telemetry`,z9)),Z9(dY(n),F(n,...I9,B9),g,F(`logs`,B9)),Z9(fY(n),F(n,...I9,V9),g,F(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,F(g,`logs`,ne(t)));for(let t of e.userStateFiles??[])X9(t,F(g,JK,ne(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,F(g,`diagnostic-reports`,ne(t)))&&(v+=1);let b=F(n,`.ok`,`local`),x=F(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,F(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(j(F(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&j(F(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=AVe(n);e!==null&&j(F(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&j(F(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&j(F(g,`state`,`checkpoint-refs.txt`),D),X9(TVe(n),F(g,`state`,H9)),X9(EVe(n),F(g,`state`,U9)),Z9(pEe(n),F(b,zf),g,`state/last-spawn-error.log`),X9(F(b,Hf),F(g,`state`,Hf)),X9(F(b,Uf),F(g,`state`,Uf)),X9(F(b,Vf),F(g,`state`,Vf));let O=p(),A=d(),te=f(),M={ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te}};j(F(g,`state`,`runtime.json`),`${JSON.stringify(M,null,2)}\n`);let N=S===`running`?`running
1641
1641
  `:`not-running (${w})\n`;j(F(g,`state`,`server-status.txt`),N);let P=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(j(F(g,`state`,`diagnostic-reports-status.txt`),`${P}\n`),j(F(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=F(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let re=e.redact===!0;re&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:F(g,`legacy`),contentDir:t})),e.note&&j(F(g,`note.txt`),e.note);let ie=null;e.scrubSecrets===!0&&(ie=GVe(g));for(let t of e.extraFiles??[]){let e=t.zipName??ne(t.sourcePath);if(!X9(t.sourcePath,F(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=v7(t,`extra/${e}`);n!==null&&(ie??={redactions:[],redactedLineCount:0},ie.redactions.push(n),ie.redactedLineCount+=n.lineCount)}let I=IVe(n),L=Q9(g),ae=[],oe=0,se=0;for(let e of L){let t=$9(g,e),n=ee(e).size,r=HVe(t)?RVe(e):0;ae.push({path:t,bytes:n,lines:r}),oe+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(se+=BVe(e))}let ce={applied:re};ie!==null&&(ce.secretScrub=ie);let R={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te},contentDir:{pathSha256:LVe(t),absolutePath:re?`<CONTENT_DIR>`:t},telemetry:{localSink:{...I,directory:xt(`logs`,`projects`)},otlpPushEnabled:m()},redaction:ce,serverStatus:S,files:ae};j(F(g,`manifest.json`),`${JSON.stringify(R,null,2)}\n`);let le=E9(t),ue=L.some(e=>{try{let t=C(e,`utf-8`);return le.some(e=>t.includes(e))}catch{return!1}}),de={stagedDiagnosticReports:v,totalBytes:oe,fileCount:ae.length,docNameCount:se,contentDirVisible:ue,redacted:re},fe=!1;return{stagingDir:g,manifest:R,summary:de,cleanup:()=>{fe||(fe=!0,k(g,{recursive:!0,force:!0}))}}}catch(e){throw k(g,{recursive:!0,force:!0}),e}}async function qVe(e){let{collected:t,outputPath:n}=e,r=N(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new zAe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(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 JVe(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,On.parse)(C(n,`utf-8`)),r=_q(t)?t.content:void 0,i=_q(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ae(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 ae(e)}async function YVe(e,t,n,r,i,a){let o=y7(t,e.logger),s=await KVe({contentDir:JVe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Qze(o,e.userLogsDir??F(St(),`logs`)),...x7(e.cachesDir??F(de(),`Library`,`Caches`))],userStateFiles:S7(e.bugReportsDir??_7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(N(e.outputPath),{recursive:!0}),await qVe({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 XVe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??T9,i=()=>wze(e.diagnosticReportsDir??F(de(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return YVe(e,t,n,r,i(),await h7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await rBe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:x7(e.cachesDir??F(de(),`Library`,`Caches`)),bugReportLedgerFiles:S7(e.bugReportsDir??_7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await h7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Eq as ALL_EDITOR_IDS,Dq as EDITOR_LABELS,sJ as EDITOR_TARGETS,OTe as HOSTS_WITH_USER_SKILL_DIR,fze as LAUNCH_CONFIG_NAME,iVe as PATH_SHIM_BEGIN,oVe as PATH_SHIM_BLOCK_RE,aVe as PATH_SHIM_END,o5 as ProjectPathSafetyError,URe as addOkPathsToGitExclude,s5 as assertProjectPathSafe,Hq as buildManagedServerEntry,BBe as buildMcpConfigDeclineEvent,VBe as buildMcpConfigMigrateEvent,Qq as canonicalEntryFor,H5 as classifyExistingMcpEntry,XVe as collectReportBundle,dVe as createCliProbeResolver,Pn as createTokenStore,Yze as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,gze as detectInstalledEditors,Zq as droppedManagedKeys,YTe as editorConfigPathDisplay,JTe as editorEntryLocator,kBe as ensurePiBridge,Aze as findJetsamKillSync,b5 as formatTrackedRemediation,KRe as getExcludedOkPaths,v5 as getInstalledSkillProjectionPaths,DTe as getNativeTomlMcpEditor,_5 as getOkArtifactPaths,Bq as isEntryUpToDate,Uq as isOwnManagedEntry,tVe as loadConfig,Dee as makeLazyProbeTokenStore,_7 as okBugReportsDir,_9 as parseGitHubBlobUrl,nVe as parseGitHubShareUrl,v9 as parseGitHubTreeUrl,g9 as parseGitUrl,sVe as pathInstallMarkerPath,ORe as previewContent,_ze as probeOwnManagedEditorMcpEntry,DBe as probePiBridgeState,y5 as probeTrackedOkPaths,B5 as readExistingMcpEntry,GRe as readSharingMode,eF as redactContent,sBe as registerWindowsProcessStartReader,WRe as removeOkPathsFromGitExclude,IBe as removeOwnMcpEntry,zRe as removeProjectSkill,pVe as removeUserGlobalSkillBundle,yVe as removeUserSkill,NRe as resolveProjectRoot,YBe as runStop,u9 as truncatePriorEntry,C9 as userGlobalSkillBundleTargets,vVe as userSkillPresentAnywhere,rVe as validateLocalFolderForShare,z5 as writeEditorMcpConfig,gVe as writeProjectAiIntegrations,f5 as writeProjectSkill,hze as writeUserMcpConfigs,_Ve as writeUserSkill};
1642
1642
  //# sourceMappingURL=index.mjs.map