@inkeep/open-knowledge 0.88.3-beta.3 → 0.88.3-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/cli.mjs +75 -75
  2. package/dist/config-schema.json +1 -1
  3. package/dist/config.project.schema.json +1 -1
  4. package/dist/constants-BrQxqUNL.mjs +1 -0
  5. package/dist/{dist-RdM5Fw_L.mjs → dist-BniR5KN1.mjs} +507 -507
  6. package/dist/dist-D5Ry9hFU.mjs +1 -0
  7. package/dist/index.mjs +241 -241
  8. package/dist/init-CxYfudet.mjs +1 -0
  9. package/dist/{init-DxmL4VOM.mjs → init-UZr9GVxw.mjs} +17 -17
  10. package/dist/{launch-json-removal-joOXjG0j.mjs → launch-json-removal-DdasfWvu.mjs} +1 -1
  11. package/dist/{loader-7rHc_jKi.mjs → loader-Dbq_EWV8.mjs} +1 -1
  12. package/dist/loader-iVVo3m-3.mjs +1 -0
  13. package/dist/{md-manager-BGnqyqi1-C2MED2uJ.mjs → md-manager-BGnqyqi1-CSFPyGy0.mjs} +170 -170
  14. package/dist/{open-browser-BdzTIyUA.mjs → open-browser-CDTeL9eY.mjs} +1 -1
  15. package/dist/parse-worker.mjs +1 -1
  16. package/dist/{preview-BGzTZvt_.mjs → preview-BRJmRFNY.mjs} +1 -1
  17. package/dist/preview-ca3pkl9K.mjs +1 -0
  18. package/dist/public/assets/{AccountSection-liNW8VsY.js → AccountSection-B7HfUudL.js} +1 -1
  19. package/dist/public/assets/{ActivityModeContent-DxGsZGgV.js → ActivityModeContent-CmhZGNsW.js} +1 -1
  20. package/dist/public/assets/{AddPropertiesButton-B3R_loiY.js → AddPropertiesButton-BT2D84aD.js} +1 -1
  21. package/dist/public/assets/{AgentDiffPane-Dz8RCVvt.js → AgentDiffPane-CHF9pABO.js} +1 -1
  22. package/dist/public/assets/{AttachmentsSection-De2g52kJ.js → AttachmentsSection-ByGVMvG9.js} +1 -1
  23. package/dist/public/assets/{CodeMirrorPropInput-B7U-juwF.js → CodeMirrorPropInput-DR1N5trk.js} +1 -1
  24. package/dist/public/assets/{ContentRulesSection-CsfIqEzL.js → ContentRulesSection-C9Req4oF.js} +1 -1
  25. package/dist/public/assets/{DocumentContext-C4f5Y70q.js → DocumentContext-CSDucywQ.js} +28 -28
  26. package/dist/public/assets/{EditorModeToggle-C9QIZNw1.js → EditorModeToggle-gpcNAVY7.js} +1 -1
  27. package/dist/public/assets/{ExcalidrawDocEditor-D6UENgJN.js → ExcalidrawDocEditor-Cgmhgars.js} +1 -1
  28. package/dist/public/assets/FeedbackForm-ZahAS6z-.js +1 -0
  29. package/dist/public/assets/{ImportSkillDialog-DrRHS0gi.js → ImportSkillDialog-D_sEyaYd.js} +1 -1
  30. package/dist/public/assets/{LinkPreviewsSection-DlsYZvWP.js → LinkPreviewsSection-9BI_Ve7c.js} +1 -1
  31. package/dist/public/assets/{LintConfigEditor-DK2vLKmh.js → LintConfigEditor-Cd7vchN2.js} +1 -1
  32. package/dist/public/assets/{LintingSection-CHdefNBM.js → LintingSection-CYt6Mzbc.js} +1 -1
  33. package/dist/public/assets/ManagedArtifactProperties-BBtQ0jlN.js +1 -0
  34. package/dist/public/assets/{ManagedArtifactProperties-DX3SBi-r.js → ManagedArtifactProperties-DD9uK5we.js} +1 -1
  35. package/dist/public/assets/{MermaidDocEditor-LPiNsM_Y.js → MermaidDocEditor-C_HMHLXm.js} +1 -1
  36. package/dist/public/assets/{NetworkAccessSection-DBr35sw3.js → NetworkAccessSection-BrbkXzyJ.js} +1 -1
  37. package/dist/public/assets/{PropertyDisplayRow-Dcqf2vtN.js → PropertyDisplayRow-DrvArJ_K.js} +1 -1
  38. package/dist/public/assets/{PublishToGitHubDialog-3E5sNc_C.js → PublishToGitHubDialog-D0GzPYlL.js} +1 -1
  39. package/dist/public/assets/{SchemaConfigEditor-IrI43FpI.js → SchemaConfigEditor-Cxv9ZBLk.js} +1 -1
  40. package/dist/public/assets/{SearchSection-AaRMMipY.js → SearchSection-B2hY3rln.js} +1 -1
  41. package/dist/public/assets/{SessionsHost-PrQ4fSfv.js → SessionsHost-Dhya-YYl.js} +2 -2
  42. package/dist/public/assets/{SettingsDialogBody-onEowQv-.js → SettingsDialogBody-BqSzx5Tb.js} +2 -2
  43. package/dist/public/assets/{ShareReceiveMissDialog-CWhnF66w.js → ShareReceiveMissDialog-BIVMX9w3.js} +1 -1
  44. package/dist/public/assets/{SkillToolbarControls-Ce8HyDfK.js → SkillToolbarControls-F1L2HGgN.js} +1 -1
  45. package/dist/public/assets/{SourceEditor-CGa5C04v.js → SourceEditor-KucnhTGF.js} +1 -1
  46. package/dist/public/assets/{SpellingSettings-ojjyX__V.js → SpellingSettings-DdfEMafp.js} +1 -1
  47. package/dist/public/assets/{SyncSection-DvDM3TJk.js → SyncSection-B5pv2M0p.js} +1 -1
  48. package/dist/public/assets/{SyncStatusBadge-BGKNwwqG.js → SyncStatusBadge-emJ3GW6F.js} +1 -1
  49. package/dist/public/assets/{TerminalSection-uPIUKsXh.js → TerminalSection-BTwUAO1z.js} +1 -1
  50. package/dist/public/assets/{TerminalWindowApp-BrmUwrT7.js → TerminalWindowApp-DqRB0Vv9.js} +1 -1
  51. package/dist/public/assets/{TextDocEditor-DpwR30S1.js → TextDocEditor-DI35AumM.js} +1 -1
  52. package/dist/public/assets/{ThemePluginSection-DnaaY8Z2.js → ThemePluginSection-C-SayLL7.js} +1 -1
  53. package/dist/public/assets/{ThreadView-D5qHL77s.js → ThreadView-Dykd2VWP.js} +1 -1
  54. package/dist/public/assets/{TimelineDiffPane-C4SPjhs4.js → TimelineDiffPane-BMkb_oht.js} +1 -1
  55. package/dist/public/assets/{client-version-DY4pmZts.js → client-version-BLwdND1C.js} +1 -1
  56. package/dist/public/assets/{comment-chips-jMy102T_.js → comment-chips-CvYUezma.js} +1 -1
  57. package/dist/public/assets/{config-provider-Br4OqjRm.js → config-provider-DW_79HvK.js} +1 -1
  58. package/dist/public/assets/config-schema-Cdmd2Mb9.js +1 -0
  59. package/dist/public/assets/{doc-undo-manager-DqthvzQR.js → doc-undo-manager-CLhgkmvC.js} +1 -1
  60. package/dist/public/assets/field-controls-B5XGrBle.js +1 -0
  61. package/dist/public/assets/{field-controls-xmZJD7CS.js → field-controls-CxY76_35.js} +1 -1
  62. package/dist/public/assets/{index-DZ4NdVgz.js → index-X807k4xA.js} +7 -7
  63. package/dist/public/assets/{lint-config-client-Cvaam883.js → lint-config-client-Bd8ngCU8.js} +1 -1
  64. package/dist/public/assets/{lint-plugins-DDhE0rAj.js → lint-plugins-Czjcu-H_.js} +1 -1
  65. package/dist/public/assets/{markdown-lint-BwsN6kr-.js → markdown-lint-ABdPsjuJ.js} +1 -1
  66. package/dist/public/assets/{markdownlint-rule-browser-COUuCPT4.js → markdownlint-rule-browser-C56kvk1x.js} +1 -1
  67. package/dist/public/assets/messages-B0A-BhSz.js +1 -0
  68. package/dist/public/assets/messages-Bozj8gn5.js +1 -0
  69. package/dist/public/assets/messages-BsFG2CYm.js +1 -0
  70. package/dist/public/assets/messages-CH4Y5J-b.js +1 -0
  71. package/dist/public/assets/messages-CKXedJpN.js +1 -0
  72. package/dist/public/assets/messages-CSj5vIPE.js +1 -0
  73. package/dist/public/assets/messages-CSujoKud.js +1 -0
  74. package/dist/public/assets/messages-CWaPbX0C.js +1 -0
  75. package/dist/public/assets/messages-CoLA64og.js +1 -0
  76. package/dist/public/assets/messages-Dna-nCpV.js +1 -0
  77. package/dist/public/assets/messages-Q2aFEeTO.js +1 -0
  78. package/dist/public/assets/messages-fzV9fvJY.js +1 -0
  79. package/dist/public/assets/messages-sTf2glOl.js +1 -0
  80. package/dist/public/assets/{pending-receive-nav-store-DEZs5wc3.js → pending-receive-nav-store-C-OIVRCW.js} +1 -1
  81. package/dist/public/assets/{preferred-session-events-KRrpUrGT.js → preferred-session-events-BNgqIkFZ.js} +1 -1
  82. package/dist/public/assets/{progress-BnVhYHVl.js → progress-CWeTZaVu.js} +1 -1
  83. package/dist/public/assets/saved-themes-client-Cq80E6xi.js +1 -0
  84. package/dist/public/assets/{schema-section-wsqWXSSM.js → schema-section-DNLDm-pQ.js} +1 -1
  85. package/dist/public/assets/{selection-context-DVpYX1Ay.js → selection-context-BdQZZ1HB.js} +1 -1
  86. package/dist/public/assets/{src-D9vmg6O3.js → src-DO7J3WVu.js} +1 -1
  87. package/dist/public/assets/{telemetry-impl-Bip4u1Ek.js → telemetry-impl-BTJogCD2.js} +1 -1
  88. package/dist/public/assets/{telemetry-startup-C5oki7WN.js → telemetry-startup-CjA9BXC1.js} +1 -1
  89. package/dist/public/assets/{typing-burst-detector-DS6wGcl3.js → typing-burst-detector-fQQTAQsm.js} +1 -1
  90. package/dist/public/assets/{uninstall-gnyatfna.js → uninstall-wTHWhxcV.js} +1 -1
  91. package/dist/public/assets/{use-activity-panel-CRusEB7v.js → use-activity-panel-D2QIpezB.js} +1 -1
  92. package/dist/public/assets/{use-apply-config-language-GGKe-kOK.js → use-apply-config-language-B_oVrEAw.js} +2 -2
  93. package/dist/public/assets/{use-open-skill-d6yLx6dL.js → use-open-skill-CkTZwt2b.js} +1 -1
  94. package/dist/public/assets/{use-terminal-enabled-CjYCBfkT.js → use-terminal-enabled-CZCtVTgy.js} +1 -1
  95. package/dist/public/assets/{use-timeline-entry-diff-DMMM8WST.js → use-timeline-entry-diff-BwKzDqXd.js} +1 -1
  96. package/dist/public/index.html +24 -24
  97. package/dist/public/uninstall.html +3 -3
  98. package/dist/{registry-probes-CIpYsPg_.mjs → registry-probes-DA_47MnL.mjs} +8 -8
  99. package/dist/{removal-file-path-DaE_OEQ1.mjs → removal-file-path-Yisg-4PO.mjs} +1 -1
  100. package/dist/{repair-launch-json-CzQJldao.mjs → repair-launch-json-ByHbUrvl.mjs} +1 -1
  101. package/dist/{repair-mcp-configs-CtVjr0VS.mjs → repair-mcp-configs-Cz7RUmn9.mjs} +1 -1
  102. package/dist/schemas/v0/config.project.schema.json +1 -1
  103. package/dist/src--qjAZ5fK.mjs +16 -0
  104. package/dist/src-ue3sSI-I.mjs +1 -0
  105. package/dist/{start-CZVNt90K.mjs → start-0pD-b-lJ.mjs} +4 -4
  106. package/dist/start-r-TtnKpy.mjs +1 -0
  107. package/package.json +4 -4
  108. package/dist/constants-DUZK5snO.mjs +0 -1
  109. package/dist/dist-C-GaD236.mjs +0 -1
  110. package/dist/init-dxu5hQlo.mjs +0 -1
  111. package/dist/loader-CjL-5Pk1.mjs +0 -1
  112. package/dist/preview-Cdv-UrrD.mjs +0 -1
  113. package/dist/public/assets/FeedbackForm-BVj8lH2K.js +0 -1
  114. package/dist/public/assets/ManagedArtifactProperties-A88_zVZK.js +0 -1
  115. package/dist/public/assets/config-schema-B392I0mu.js +0 -1
  116. package/dist/public/assets/field-controls-BLuu0LLy.js +0 -1
  117. package/dist/public/assets/messages--wX-6jvz.js +0 -1
  118. package/dist/public/assets/messages-BWH6xaIt.js +0 -1
  119. package/dist/public/assets/messages-Bl6RVy5f.js +0 -1
  120. package/dist/public/assets/messages-C12CEVlb.js +0 -1
  121. package/dist/public/assets/messages-C72PW9gH.js +0 -1
  122. package/dist/public/assets/messages-DnkP1Emg.js +0 -1
  123. package/dist/public/assets/messages-DpgtXjLB.js +0 -1
  124. package/dist/public/assets/messages-F_TitmhP.js +0 -1
  125. package/dist/public/assets/messages-LMNA06Bk.js +0 -1
  126. package/dist/public/assets/messages-l6-R7kj0.js +0 -1
  127. package/dist/public/assets/messages-oVKfHfSb.js +0 -1
  128. package/dist/public/assets/messages-r7y_qPx0.js +0 -1
  129. package/dist/public/assets/messages-uuZvac8w.js +0 -1
  130. package/dist/public/assets/saved-themes-client-BeMdeoNG.js +0 -1
  131. package/dist/src-Bf43s8QJ.mjs +0 -16
  132. package/dist/src-C-R2vPyW.mjs +0 -1
  133. package/dist/start-CINPPjym.mjs +0 -1
@@ -1,12 +1,12 @@
1
- import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Bf as r,Cf as i,Ef as a,Kf as o,Nd as s,Of as c,Tf as l,Uf as u,Vf as d,Xf as f,Ya as p,Yf as m,Zf as h,ep as g,fd as _,ol as v,tl as y}from"./md-manager-BGnqyqi1-C2MED2uJ.mjs";import{Cs as ee,Hn as b,Ss as te,Wo as x,_r as ne,_s as S,as as re,hs as C,ja as w,m as ie,nr as ae}from"./dist-RdM5Fw_L.mjs";import{A as oe,B as se,E as ce,F as le,M as ue,N as T,S as de,T as fe,Y as pe,Z as E,at as me,b as he,et as ge,f as _e,ft as ve,it as ye,j as be,k as D,lt as xe,nt as Se,ot as Ce,p as we,rt as Te,s as Ee,ut as De,y as Oe}from"./init-DxmL4VOM.mjs";import{t as ke}from"./is-object-BGze3w87.mjs";import{t as Ae}from"./removal-file-path-DaE_OEQ1.mjs";import{spawn as je}from"node:child_process";import{basename as O,dirname as k,join as A,resolve as j,win32 as Me}from"node:path";import{accessSync as Ne,constants as M,existsSync as N,lstatSync as P,mkdirSync as Pe,readFileSync as F,readdirSync as I,realpathSync as L,rmSync as Fe,rmdirSync as Ie,statSync as R,unlinkSync as Le}from"node:fs";import{homedir as z}from"node:os";import{createHash as Re}from"node:crypto";import{isDeepStrictEqual as ze}from"node:util";import{setTimeout as Be}from"node:timers/promises";var Ve=_();let He;function Ue(){return He}function We(e,t){if(t!==void 0&&t.length>0)return t;try{return ne(e)?.rootPath}catch{return}}function Ge(e){let t=We(e.cwd,e.configuredProjectName),n=b({name:`cli`,project:t});return He=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}function B(){return v(y)}function V(){return o().keyringService}function H(e){try{e()}catch{}}var Ke=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(V(),e).getPassword()}catch(t){return H(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return H(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return H(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(V(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(V(),e).deletePassword()}catch{}}},U=class{backend=`file`;authFile;constructor(e){this.authFile=e??A(S(),`auth.yml`)}read(){if(!N(this.authFile))return{};try{let e=F(this.authFile,`utf-8`);return(0,Ve.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=k(this.authFile);N(t)||Pe(t,{recursive:!0,mode:448}),C(this.authFile,(0,Ve.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},qe=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${B()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function Je(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(V(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
- `),H(()=>t?.onBackendSelected?.({backend:`keyring`})),new qe(new Ke(t?.onKeychainRead),new U(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (${B()}) — OS keychain unavailable: ${r}\n`),H(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new U(e)}}function Ye(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (${B()})\n`),r(new U(e))},n)});try{return await Promise.race([Je(e),r])}catch{return new U(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Xe(e){let t=Ye(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function Ze(e){let t=Ye(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function Qe(e,t){let n=[],r=new U(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));let i;try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(V(),`__probe__`);let r,a=await new Ke(e=>{e.kind===`read-error`&&(r=e.error??`read-error`)}).get(e);if(r!==void 0)i=r;else if(a!=null)try{new t(V(),e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function $e(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function et(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function tt(e){return x({detached:!0,stdio:`ignore`,shell:!1,env:$e(e)})}function nt(e,t,n={}){let r=(n.spawn??je)(e,[...t],tt(n.env??process.env));return r.unref(),r}function rt(e,t,n={}){let r=n.spawn??je,i=n.timeoutMs??2e3;return new Promise(a=>{let o=!1,s=e=>{o||(o=!0,a(e))},c=setTimeout(()=>s({ok:!1,reason:`timeout`}),i);try{let i=r(e,[...t],tt(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(et(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(et(e))}})}const it=r.stable.appId,W=u,at=[`stable`,`beta`];function ot(e,t,n=e=>console.error(e)){try{return g(e,t)}catch(r){let i=g({...e,[d]:void 0},t);return n(`Treating this CLI as ${m(i)} for this command: ${r instanceof Error?r.message:String(r)}`),i}}function G(e){return at.includes(e)||!W.includes(e)?at:[e,...at]}function st(e){return e.bundlePath===void 0?null:{bundlePath:e.bundlePath,protocolScheme:r[e.product].protocolScheme}}function ct(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return R(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function lt(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let n=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(n?.[1]){let e=n[1];return{path:e,product:W.find(t=>e.endsWith(`/${r[t].productName}.app`))??t}}}let n=e.homeDir??z();for(let i of G(t)){let{productName:t}=r[i];for(let r of[A(n,`Applications`),`/Applications`]){let n=A(r,`${t}.app`);if(ut(e,A(n,`Contents`,`MacOS`,t)))return{path:n,product:i}}}return null}function ut(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}function dt(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=W.find(t=>e.execPath.toLowerCase().endsWith(`\\${f(r[t]).toLowerCase()}`));if(t)return{path:e.execPath,product:t}}let n=e.env.LOCALAPPDATA;if(n)for(let i of G(t))for(let t of h(r[i])){let a=Me.join(n,`Programs`,t,f(r[i]));if(ut(e,a))return{path:a,product:i}}return null}function ft(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=W.find(t=>e.execPath.endsWith(`/${r[t].linuxExecutableName}`));if(t)return{path:e.execPath,product:t}}for(let n of G(t)){let{productName:t,linuxExecutableName:i}=r[n],a=`/opt/${t}/${i}`;if(ut(e,a))return{path:a,product:n}}return null}function pt(e){let t=ot(e.env,e.execPath,e.warn);if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`,cliProduct:t};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`,cliProduct:t};let n;try{n=e.platform===`darwin`?lt(e,t):e.platform===`win32`?dt(e,t):ft(e,t)}catch{return{available:!1,reason:`stat-error`,cliProduct:t}}if(!n)return{available:!1,reason:`no-bundle`,cliProduct:t};let r={bundlePath:n.path,product:n.product,cliProduct:t};return e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,...r}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,...r}:{available:!0,reason:`available`,...r}}function mt(e,t){let n=e.log??(e=>console.error(e)),i=e.platform??process.platform;if(t.bundlePath===void 0){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}let{productName:a}=r[t.product],[o]=r[t.cliProduct].cliCommandNames;n(`Launching ${a} desktop (use \`${o} start\` for the browser server, or \`OK_FORCE_BROWSER=1\` to always skip)`);let s=t.bundlePath;if(i===`darwin`){nt(`open`,[`-a`,s],{spawn:e.spawn});return}nt(s,[],{spawn:e.spawn})}function ht(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it from https://openknowledge.ai/download, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function K(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 gt(e){return Re(`sha256`).update(e).digest(`hex`)}function q(e){return A(S(j(e)),`pi-trust`)}function _t(e,t){return A(q(e),gt(j(t)))}function vt(e,t,n){return A(_t(e,t),`${gt(n)}.json`)}var J=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${K(e)} ${K(t)}; ${K(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function Y(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 J(e,`could not ${t}: ${i}`,a,n)}function X(e){let t;try{t=P(e)}catch(t){if(t.code===`ENOENT`)return!1;throw Y(e,`be inspected`,t)}if(!t.isDirectory())throw new J(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function yt(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function bt(e,t){if(!ke(e)||!yt(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==j(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==j(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==j(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!ke(e.previous))throw new J(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&&yt(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&yt(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new J(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 xt(e,t,n){let r;try{r=P(n)}catch(e){throw Y(n,`be inspected`,e)}if(!r.isFile())throw new J(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=F(n,`utf8`)}catch(e){throw Y(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new J(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=bt(a,n);if(o.cwd!==j(t)||n!==vt(e,t,o.canonicalTrustPath))throw new J(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 St(e,t){let{record:n,path:r}=t;for(let t of[q(e),_t(e,n.cwd)])if(!X(t))throw new J(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=xt(e,n.cwd,r);if(!ze(i.record,n))throw new J(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function Ct(e,t,n,r,i){let a={version:1,cwd:j(t),configuredTrustPath:j(n),canonicalTrustPath:j(r),state:`pending`,previous:i},o=vt(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!ze(bt(JSON.parse(s),o),a))throw new J(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);X(q(e)),X(k(o));try{Pe(k(o),{recursive:!0,mode:448})}catch(e){throw Y(k(o),`be created`,e)}let c;try{c=P(o,{throwIfNoEntry:!1})}catch(e){throw Y(o,`be inspected`,e)}if(c)throw new J(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{C(o,s,{mode:384})}catch(e){throw Y(o,`be written`,e)}return{path:o,record:a}}function wt(e,t){let n=St(e,t);if(n.record.state!==`pending`)throw new J(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{C(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw Y(n.path,`be committed`,e)}return{path:n.path,record:r}}function Tt(e,t){if(!X(q(e)))return[];let n=_t(e,t);if(!X(n))return[];let r;try{r=I(n).sort()}catch(e){throw Y(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>xt(e,t,A(n,r)))}function Et(e,t){let n=St(e,t);try{Le(n.path)}catch(e){throw Y(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),q(e)])try{Ie(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw Y(t,`be removed after reconciling its grant`,e)}}var Dt=n(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),Ot=n(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),kt=n(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),At=n(((t,n)=>{var r=e(`fs`),i=Dt(),a=Ot(),o=kt(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
3
- GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=S,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);b=g.ReadStream,x=g.WriteStream}var _=e.ReadStream;_&&(b.prototype=Object.create(_.prototype),b.prototype.open=te);var v=e.WriteStream;v&&(x.prototype=Object.create(v.prototype),x.prototype.open=ne),Object.defineProperty(e,"ReadStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0});var y=b;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var ee=x;Object.defineProperty(e,"FileWriteStream",{get:function(){return ee},set:function(e){ee=e},enumerable:!0,configurable:!0});function b(e,t){return this instanceof b?(_.apply(this,arguments),this):b.apply(Object.create(b.prototype),arguments)}function te(){var e=this;w(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 x(e,t){return this instanceof x?(v.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function ne(){var e=this;w(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function S(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var C=e.open;e.open=w;function w(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 C(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))}}})),jt=n(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Mt=n((e=>{var t=jt();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}}})),Nt=n(((e,t)=>{t.exports=Mt()})),Pt=n(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),Ft=n(((t,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=e(`assert`),o=Pt(),s=/^win/i.test(r.platform),c=e(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),It=n(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Lt=n(((t,n)=>{let r=e(`path`),i=At(),a=Nt(),o=Ft(),s=It(),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})),Rt=n(((e,t)=>{let n=At();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}})),zt=t(n(((e,t)=>{let n=Lt(),{toPromise:r,toSync:i,toSyncOptions:a}=Rt();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 Bt=5e3;function Vt(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 ${Bt}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Ht(e,t){Ue()?.warn(t,e)}function Ut(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 Wt(e,t,n){await te(`${t}.ok.lock`,async()=>{let t=performance.now()+Bt,r;for(;;)try{r=await zt.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Be(Vt(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}Ut(i,e)},{onWarn:Ht})}function Gt(e,t,n){ee(`${t}.ok.lock`,()=>{let t=performance.now()+Bt,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=zt.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,Vt(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}Ut(a,e)},{onWarn:Ht})}const Kt=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var qt=class extends Error{name=`PiResourceInspectionError`};function Z(e){let t;try{t=P(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=R(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new qt(ue(`missing-symlink-target`),{cause:e}):e}return Ne(e,M.R_OK|(n.isDirectory()?M.X_OK:0)),!0}function Jt(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function Yt(e,t,n){let r=e;try{let i=L(e),a;r=t;try{a=L(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=j(t)}let o=A(a,`.agents`,`skills`),s=[];for(let e of Kt)r=A(i,`.pi`,e),Z(r)&&s.push(r);if(r=A(i,`.pi`,`extensions`),Z(r))for(let t of I(r).sort()){let i=A(r,t);j(n)!==A(j(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[A(i,`.pi`,`skills`),A(i,`.agents`,`skills`)])if(e!==o&&(r=e,Z(e)))for(let t of I(e).sort())Jt(t)||s.push(A(e,t));let c=k(i);for(;c!==i;){r=A(c,`.agents`,`skills`),r!==o&&Z(r)&&s.push(r);let e=k(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 ${K(r)}: ${e instanceof qt?e.message:ue(T(e))}`}}}function Xt(e,t,n){let r=j(e),i=xe({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:E.pi.projectConfigPath(r),trustPath:A(i,`trust.json`)}}function Zt(e){try{let t=L(e);return R(t).isDirectory()?(Ne(t,M.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${K(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${K(e)} could not be resolved or accessed: ${K(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function Qt(e){let t=Zt(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${K(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function $t(e,t,n){let r=Ee(E.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return ye(i)?{state:`own-current`,text:a}:ce(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function en(e,t){let n;try{n=F(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:T(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 ke(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
4
- `)}:{state:`unreadable`,reason:`invalid-json`}}function tn(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 ue(e)}}function Q(e,t){return{kind:`refused`,error:`trust store ${K(e)}: ${tn(t)}`}}function nn(e){let t=Ae(e);try{switch(t.kind){case`declined`:return Q(e,t.reason);case`ready`:return{kind:`ready`,path:L(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=k(e),r=[O(e)],i=P(n,{throwIfNoEntry:!1});for(;!i;){let t=k(n);if(t===n)return Q(e,`unavailable-root`);r.unshift(O(n)),n=t,i=P(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:A(L(n),...r)}}catch(t){return Q(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:T(t))}}catch(t){return Q(e,T(t))}}function rn(e,t){let n=nn(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?Q(e,`path-changed`):n}function an(e,t,n){let r=Xt(e,t,n),i=Zt(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=$t(r.cwd,r.bridgePath,t).state,o=nn(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:en(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:on(r.bridgePath).displayNames}}function on(e){let t=k(e),n=O(e);try{return{displayNames:I(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>K(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function sn(e,t={mode:`published`},n,r,i){let a=Xt(e,n,r),o=Zt(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 ${K(i)} no longer matches the current directory ${K(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=$t(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=fe(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=he(E.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:K(e.error)}}let l=await cn(a.trustPath,o.project,n??z());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function cn(e,t,n){let r=t.canonical,i=nn(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{Pe(k(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:K(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await Wt(e,i.path,()=>{let o=Qt(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=rn(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=en(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=Q(e,c.reason).error;return}let l=$(n,()=>{let t=Tt(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&Et(n,t),Ct(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?`
1
+ import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Df as r,Ef as i,Hf as a,Pd as o,Qf as s,Vf as c,Wf as l,Xf as u,Ya as d,Zf as f,kf as p,ol as m,pd as h,qf as g,tl as _,tp as v,wf as y}from"./md-manager-BGnqyqi1-CSFPyGy0.mjs";import{Bs as ee,Hn as b,Ko as te,Na as x,Ps as S,Vs as ne,_r as re,js as C,m as w,nr as ie,ss as ae}from"./dist-BniR5KN1.mjs";import{A as oe,B as se,E as ce,F as le,M as ue,N as T,S as de,T as fe,Y as pe,Z as E,at as me,b as he,et as ge,f as _e,ft as ve,it as ye,j as be,k as D,lt as xe,nt as Se,ot as Ce,p as we,rt as Te,s as Ee,ut as De,y as Oe}from"./init-UZr9GVxw.mjs";import{t as ke}from"./is-object-BGze3w87.mjs";import{t as Ae}from"./removal-file-path-Yisg-4PO.mjs";import{spawn as je}from"node:child_process";import{basename as O,dirname as k,join as A,resolve as j,win32 as Me}from"node:path";import{accessSync as Ne,constants as M,existsSync as N,lstatSync as P,mkdirSync as Pe,readFileSync as F,readdirSync as I,realpathSync as L,rmSync as Fe,rmdirSync as Ie,statSync as R,unlinkSync as Le}from"node:fs";import{homedir as z}from"node:os";import{createHash as Re}from"node:crypto";import{isDeepStrictEqual as ze}from"node:util";import{setTimeout as Be}from"node:timers/promises";var Ve=h();let He;function Ue(){return He}function We(e,t){if(t!==void 0&&t.length>0)return t;try{return re(e)?.rootPath}catch{return}}function Ge(e){let t=We(e.cwd,e.configuredProjectName),n=b({name:`cli`,project:t});return He=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}function B(){return m(_)}function V(){return g().keyringService}function H(e){try{e()}catch{}}var Ke=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(V(),e).getPassword()}catch(t){return H(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return H(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return H(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(V(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(V(),e).deletePassword()}catch{}}},U=class{backend=`file`;authFile;constructor(e){this.authFile=e??A(S(),`auth.yml`)}read(){if(!N(this.authFile))return{};try{let e=F(this.authFile,`utf-8`);return(0,Ve.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=k(this.authFile);N(t)||Pe(t,{recursive:!0,mode:448}),C(this.authFile,(0,Ve.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},qe=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${B()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function Je(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(V(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ `),H(()=>t?.onBackendSelected?.({backend:`keyring`})),new qe(new Ke(t?.onKeychainRead),new U(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (${B()}) — OS keychain unavailable: ${r}\n`),H(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new U(e)}}function Ye(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (${B()})\n`),r(new U(e))},n)});try{return await Promise.race([Je(e),r])}catch{return new U(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Xe(e){let t=Ye(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function Ze(e){let t=Ye(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function Qe(e,t){let n=[],r=new U(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));let i;try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(V(),`__probe__`);let r,a=await new Ke(e=>{e.kind===`read-error`&&(r=e.error??`read-error`)}).get(e);if(r!==void 0)i=r;else if(a!=null)try{new t(V(),e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function $e(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function et(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function tt(e){return te({detached:!0,stdio:`ignore`,shell:!1,env:$e(e)})}function nt(e,t,n={}){let r=(n.spawn??je)(e,[...t],tt(n.env??process.env));return r.unref(),r}function rt(e,t,n={}){let r=n.spawn??je,i=n.timeoutMs??2e3;return new Promise(a=>{let o=!1,s=e=>{o||(o=!0,a(e))},c=setTimeout(()=>s({ok:!1,reason:`timeout`}),i);try{let i=r(e,[...t],tt(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(et(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(et(e))}})}const it=c.stable.appId,W=l,at=[`stable`,`beta`];function ot(e,t,n=e=>console.error(e)){try{return v(e,t)}catch(r){let i=v({...e,[a]:void 0},t);return n(`Treating this CLI as ${u(i)} for this command: ${r instanceof Error?r.message:String(r)}`),i}}function G(e){return at.includes(e)||!W.includes(e)?at:[e,...at]}function st(e){return e.bundlePath===void 0?null:{bundlePath:e.bundlePath,protocolScheme:c[e.product].protocolScheme}}function ct(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return R(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function lt(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let n=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(n?.[1]){let e=n[1];return{path:e,product:W.find(t=>e.endsWith(`/${c[t].productName}.app`))??t}}}let n=e.homeDir??z();for(let r of G(t)){let{productName:t}=c[r];for(let i of[A(n,`Applications`),`/Applications`]){let n=A(i,`${t}.app`);if(ut(e,A(n,`Contents`,`MacOS`,t)))return{path:n,product:r}}}return null}function ut(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}function dt(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=W.find(t=>e.execPath.toLowerCase().endsWith(`\\${f(c[t]).toLowerCase()}`));if(t)return{path:e.execPath,product:t}}let n=e.env.LOCALAPPDATA;if(n)for(let r of G(t))for(let t of s(c[r])){let i=Me.join(n,`Programs`,t,f(c[r]));if(ut(e,i))return{path:i,product:r}}return null}function ft(e,t){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=W.find(t=>e.execPath.endsWith(`/${c[t].linuxExecutableName}`));if(t)return{path:e.execPath,product:t}}for(let n of G(t)){let{productName:t,linuxExecutableName:r}=c[n],i=`/opt/${t}/${r}`;if(ut(e,i))return{path:i,product:n}}return null}function pt(e){let t=ot(e.env,e.execPath,e.warn);if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`,cliProduct:t};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`,cliProduct:t};let n;try{n=e.platform===`darwin`?lt(e,t):e.platform===`win32`?dt(e,t):ft(e,t)}catch{return{available:!1,reason:`stat-error`,cliProduct:t}}if(!n)return{available:!1,reason:`no-bundle`,cliProduct:t};let r={bundlePath:n.path,product:n.product,cliProduct:t};return e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,...r}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,...r}:{available:!0,reason:`available`,...r}}function mt(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;if(t.bundlePath===void 0){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}let{productName:i}=c[t.product],[a]=c[t.cliProduct].cliCommandNames;n(`Launching ${i} desktop (use \`${a} start\` for the browser server, or \`OK_FORCE_BROWSER=1\` to always skip)`);let o=t.bundlePath;if(r===`darwin`){nt(`open`,[`-a`,o],{spawn:e.spawn});return}nt(o,[],{spawn:e.spawn})}function ht(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it from https://openknowledge.ai/download, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function K(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 gt(e){return Re(`sha256`).update(e).digest(`hex`)}function q(e){return A(S(j(e)),`pi-trust`)}function _t(e,t){return A(q(e),gt(j(t)))}function vt(e,t,n){return A(_t(e,t),`${gt(n)}.json`)}var J=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${K(e)} ${K(t)}; ${K(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function Y(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 J(e,`could not ${t}: ${i}`,a,n)}function X(e){let t;try{t=P(e)}catch(t){if(t.code===`ENOENT`)return!1;throw Y(e,`be inspected`,t)}if(!t.isDirectory())throw new J(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function yt(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function bt(e,t){if(!ke(e)||!yt(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==j(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==j(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==j(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!ke(e.previous))throw new J(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&&yt(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&yt(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new J(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 xt(e,t,n){let r;try{r=P(n)}catch(e){throw Y(n,`be inspected`,e)}if(!r.isFile())throw new J(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=F(n,`utf8`)}catch(e){throw Y(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new J(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=bt(a,n);if(o.cwd!==j(t)||n!==vt(e,t,o.canonicalTrustPath))throw new J(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 St(e,t){let{record:n,path:r}=t;for(let t of[q(e),_t(e,n.cwd)])if(!X(t))throw new J(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=xt(e,n.cwd,r);if(!ze(i.record,n))throw new J(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function Ct(e,t,n,r,i){let a={version:1,cwd:j(t),configuredTrustPath:j(n),canonicalTrustPath:j(r),state:`pending`,previous:i},o=vt(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!ze(bt(JSON.parse(s),o),a))throw new J(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);X(q(e)),X(k(o));try{Pe(k(o),{recursive:!0,mode:448})}catch(e){throw Y(k(o),`be created`,e)}let c;try{c=P(o,{throwIfNoEntry:!1})}catch(e){throw Y(o,`be inspected`,e)}if(c)throw new J(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{C(o,s,{mode:384})}catch(e){throw Y(o,`be written`,e)}return{path:o,record:a}}function wt(e,t){let n=St(e,t);if(n.record.state!==`pending`)throw new J(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{C(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw Y(n.path,`be committed`,e)}return{path:n.path,record:r}}function Z(e,t){if(!X(q(e)))return[];let n=_t(e,t);if(!X(n))return[];let r;try{r=I(n).sort()}catch(e){throw Y(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>xt(e,t,A(n,r)))}function Tt(e,t){let n=St(e,t);try{Le(n.path)}catch(e){throw Y(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),q(e)])try{Ie(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw Y(t,`be removed after reconciling its grant`,e)}}var Et=n(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),Dt=n(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),Ot=n(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),kt=n(((t,n)=>{var r=e(`fs`),i=Et(),a=Dt(),o=Ot(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
3
+ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=ne,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);b=g.ReadStream,x=g.WriteStream}var _=e.ReadStream;_&&(b.prototype=Object.create(_.prototype),b.prototype.open=te);var v=e.WriteStream;v&&(x.prototype=Object.create(v.prototype),x.prototype.open=S),Object.defineProperty(e,"ReadStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0});var y=b;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var ee=x;Object.defineProperty(e,"FileWriteStream",{get:function(){return ee},set:function(e){ee=e},enumerable:!0,configurable:!0});function b(e,t){return this instanceof b?(_.apply(this,arguments),this):b.apply(Object.create(b.prototype),arguments)}function te(){var e=this;w(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 x(e,t){return this instanceof x?(v.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;w(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var C=e.open;e.open=w;function w(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 C(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))}}})),At=n(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),jt=n((e=>{var t=At();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}}})),Mt=n(((e,t)=>{t.exports=jt()})),Nt=n(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),Pt=n(((t,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=e(`assert`),o=Nt(),s=/^win/i.test(r.platform),c=e(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),Ft=n(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),It=n(((t,n)=>{let r=e(`path`),i=kt(),a=Mt(),o=Pt(),s=Ft(),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})),Lt=n(((e,t)=>{let n=kt();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}})),Rt=t(n(((e,t)=>{let n=It(),{toPromise:r,toSync:i,toSyncOptions:a}=Lt();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 zt=5e3;function Bt(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 ${zt}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Vt(e,t){Ue()?.warn(t,e)}function Ht(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 Ut(e,t,n){await ee(`${t}.ok.lock`,async()=>{let t=performance.now()+zt,r;for(;;)try{r=await Rt.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Be(Bt(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}Ht(i,e)},{onWarn:Vt})}function Wt(e,t,n){ne(`${t}.ok.lock`,()=>{let t=performance.now()+zt,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=Rt.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,Bt(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}Ht(a,e)},{onWarn:Vt})}const Gt=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var Kt=class extends Error{name=`PiResourceInspectionError`};function qt(e){let t;try{t=P(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=R(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new Kt(ue(`missing-symlink-target`),{cause:e}):e}return Ne(e,M.R_OK|(n.isDirectory()?M.X_OK:0)),!0}function Jt(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function Yt(e,t,n){let r=e;try{let i=L(e),a;r=t;try{a=L(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=j(t)}let o=A(a,`.agents`,`skills`),s=[];for(let e of Gt)r=A(i,`.pi`,e),qt(r)&&s.push(r);if(r=A(i,`.pi`,`extensions`),qt(r))for(let t of I(r).sort()){let i=A(r,t);j(n)!==A(j(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[A(i,`.pi`,`skills`),A(i,`.agents`,`skills`)])if(e!==o&&(r=e,qt(e)))for(let t of I(e).sort())Jt(t)||s.push(A(e,t));let c=k(i);for(;c!==i;){r=A(c,`.agents`,`skills`),r!==o&&qt(r)&&s.push(r);let e=k(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 ${K(r)}: ${e instanceof Kt?e.message:ue(T(e))}`}}}function Xt(e,t,n){let r=j(e),i=xe({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:E.pi.projectConfigPath(r),trustPath:A(i,`trust.json`)}}function Zt(e){try{let t=L(e);return R(t).isDirectory()?(Ne(t,M.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${K(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${K(e)} could not be resolved or accessed: ${K(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function Qt(e){let t=Zt(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${K(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function $t(e,t,n){let r=Ee(E.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return ye(i)?{state:`own-current`,text:a}:ce(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function en(e,t){let n;try{n=F(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:T(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 ke(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
4
+ `)}:{state:`unreadable`,reason:`invalid-json`}}function tn(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 ue(e)}}function Q(e,t){return{kind:`refused`,error:`trust store ${K(e)}: ${tn(t)}`}}function nn(e){let t=Ae(e);try{switch(t.kind){case`declined`:return Q(e,t.reason);case`ready`:return{kind:`ready`,path:L(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=k(e),r=[O(e)],i=P(n,{throwIfNoEntry:!1});for(;!i;){let t=k(n);if(t===n)return Q(e,`unavailable-root`);r.unshift(O(n)),n=t,i=P(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:A(L(n),...r)}}catch(t){return Q(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:T(t))}}catch(t){return Q(e,T(t))}}function rn(e,t){let n=nn(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?Q(e,`path-changed`):n}function an(e,t,n){let r=Xt(e,t,n),i=Zt(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=$t(r.cwd,r.bridgePath,t).state,o=nn(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:en(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:on(r.bridgePath).displayNames}}function on(e){let t=k(e),n=O(e);try{return{displayNames:I(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>K(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function sn(e,t={mode:`published`},n,r,i){let a=Xt(e,n,r),o=Zt(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 ${K(i)} no longer matches the current directory ${K(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=$t(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=fe(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=he(E.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:K(e.error)}}let l=await cn(a.trustPath,o.project,n??z());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function cn(e,t,n){let r=t.canonical,i=nn(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{Pe(k(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:K(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await Ut(e,i.path,()=>{let o=Qt(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=rn(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=en(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=Q(e,c.reason).error;return}let l=$(n,()=>{let t=Z(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&Tt(n,t),Ct(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
5
5
  `:``),f=D(s.path);C(s.path,d,f===void 0?void 0:{mode:f}),$(n,()=>wt(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:K(e instanceof Error?e.message:String(e))}}return a}function ln(e){let t=[],n=e;try{for(;;){if(P(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=L(n);return R(e).isDirectory()?(Ne(e,M.X_OK),A(e,...t)):void 0}let e=k(n);if(e===n)return;t.unshift(O(n)),n=e}}catch{return}}function un(e){let t={"not-present":0,removed:1,"kept-unowned":2,"kept-shared":3,"kept-unverified":4,"refused-unreadable":5,failed:6},n=e.reduce((e,n)=>t[n.action]>t[e.action]?n:e,{action:`not-present`}),r=e.flatMap(e=>e.error??[]),i=e.flatMap(e=>e.detail??[]);return r.length>0?{action:n.error===void 0?`failed`:n.action,error:[...r,...i].join(`
6
6
  `)}:n.detail===void 0?n:{...n,detail:i.join(`
7
- `)}}function dn(e,t,n,r={}){let i=Xt(e,t,n),a=t??z(),o=Zt(i.cwd),s=o.kind===`refused`&&r.recordedOnly?ln(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=$(a,()=>{let e=Tt(a,i.cwd);return c===void 0||c===i.cwd?e:[...Tt(a,c),...e]})}catch(e){return{action:`failed`,error:K(e instanceof Error?e.message:String(e))}}if(l.length===0&&r.recordedOnly)return o.kind===`ready`||s!==void 0?{action:`not-present`}:{action:`kept-unverified`,error:`${o.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`};if(o.kind===`refused`){if(l.length===0)return{action:`kept-unverified`,error:o.error};let e=l.map(({path:e,record:t})=>`key ${K(JSON.stringify(t.cwd))}; configured store ${K(JSON.stringify(t.configuredTrustPath))}; recorded destination ${K(JSON.stringify(t.canonicalTrustPath))}; ownership record ${K(JSON.stringify(e))} (${t.state})`);return{action:`kept-unverified`,error:[`${o.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,...e,`To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.`].join(`
8
- `)}}let u=Yt(o.project.canonical,a,E.pi.projectConfigPath(o.project.canonical));if(u.kind===`unreadable`)return{action:`kept-unverified`,error:u.error};let d=u.kind===`shared`?u.paths:[],f=[],p=new Map,m=(e,t)=>{let n=p.get(e);if(!n){let t=nn(e);if(t.kind===`refused`){f.push({action:`refused-unreadable`,error:t.error});return}n={trustPath:e,resolved:t,keys:new Map},p.set(e,n)}if(t){if(n.resolved.path!==t.record.canonicalTrustPath){f.push({action:`refused-unreadable`,error:`Pi trust store ${K(e)} no longer points to its recorded destination ${K(t.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`});return}n.keys.set(t.record.cwd,{cwd:t.record.cwd,mode:`recorded`,receipt:t})}};for(let e of l)m(e.record.configuredTrustPath,e);m(i.trustPath);for(let e of p.values()){for(let t of[o.project.canonical,i.cwd])e.keys.has(t)||e.keys.set(t,{cwd:t,mode:`inspect`,receipt:l.find(n=>n.record.cwd===t&&n.record.canonicalTrustPath===e.resolved.path)});f.push(fn(e,a,d,o.project))}return un(f)}function $(e,t){try{return t()}catch(t){throw t instanceof J?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${K(A(S(e),`pi-trust`))}: ${K(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function fn(e,t,n,r){let{trustPath:i,resolved:a}=e,o=[...e.keys.values()];if(!o.some(e=>e.mode===`recorded`)&&a.kind===`missing`)return{action:`not-present`};if(a.kind===`missing`)try{P(k(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${K(k(a.path))} is unavailable: ${K(e instanceof Error?e.message:String(e))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`}}let s=[],c={result:{action:`not-present`}};try{Gt(i,a.path,()=>{let e=Qt(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=rn(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=en(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:Q(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:$(t,()=>Tt(t,e.cwd).find(e=>e.record.canonicalTrustPath===l.path))}));if(d.some(e=>e.receipt&&e.receipt.record.configuredTrustPath!==e.expectedConfiguredPath)){c.result={action:`failed`,error:`The Pi trust ownership record changed during cleanup; retry to read its current location.`};return}for(let e of d){try{pn(e,t,i,l.path,u,n,r,c)}catch(t){let n=K(t instanceof Error?t.message:String(t)),r=t instanceof J?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${K(JSON.stringify(e.cwd))} in ${K(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:K(e instanceof Error?e.message:String(e))})}return un([...s,c.result])}function pn(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&$(t,()=>Et(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${K(JSON.stringify(c))} entry from ${K(n)}; parent-folder and global trust settings still apply.`;if(a.length>0&&c===o.canonical){let n=`kept Pi's folder trust because other resources still need it: ${a.slice(0,3).map(e=>K(JSON.stringify(e))).join(`, `)}${a.length>3?` (+${a.length-3} more)`:``}. ${u} Removing this grant may stop Pi from loading those resources, including any not listed here.`;s.result={action:`kept-shared`,detail:n},l&&e.mode===`recorded`&&$(t,()=>Et(t,l)),s.result={action:`kept-shared`,detail:`${n} ${l?e.mode===`recorded`?`OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.`:`OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.`:`OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.`}`};return}if(e.mode===`inspect`||!l||l.record.state===`pending`){let e=l?l.record.state===`pending`?`its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.`:`OpenKnowledge must reconcile its recorded location at ${K(l.record.configuredTrustPath)} before removing it.`:`no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.`;s.result={action:`kept-unowned`,detail:`${c===o.canonical?`kept Pi's folder trust because ${e}`:`kept a Pi trust entry under a non-canonical project path because ${e} Pi uses the real project directory instead of this key.`} ${u}`};return}let d={...i.entries};l.record.previous.present?d[c]=l.record.previous.value:delete d[c];let f=JSON.stringify(d,null,2)+(i.trailingNewline?`
9
- `:``),p=D(r);C(r,f,p===void 0?void 0:{mode:p}),i.entries=d,$(t,()=>Et(t,l)),s.result={action:`removed`}}function mn(e){return ye(e)||me(e)||ce(e)}const hn=10485760;function gn(e,t,n,r=!1){let i=dn(e,t,n,{recordedOnly:r});switch(i.action){case`removed`:case`not-present`:return{trust:i.action};case`kept-shared`:case`kept-unowned`:return{trust:i.action,trustDetail:i.detail};case`failed`:case`refused-unreadable`:case`kept-unverified`:{let e=r?`Trust cleanup remains incomplete`:`The bridge file was left untouched`;throw Error(`Pi trust cleanup failed (${i.action}):\n${i.error}\n${e} so cleanup can be retried.`)}default:throw Error(`unhandled Pi trust cleanup result: ${i}`)}}function _n(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=gn(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function vn(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=Ae(a);if(o.kind===`not-present`)return _n(e,t,n,i);if(o.kind===`declined`)return o;let s=Ee(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return _n(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!mn(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=gn(t,n,i);try{Fe(a,{force:!0})}catch(t){throw e.trustDetail?Error(`${t instanceof Error?t.message:String(t)}\n${e.trustDetail}`,{cause:t}):t}return{kind:`removed`,...e}}return e.format===`toml`?xn(o.path,c):e.format===`yaml`?bn(o.path,e.topLevelKey,c):yn(o.path,e.topLevelKey,e.serverMapSubKey,c)}function yn(e,t,n,r){let i;try{i=F(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T(e)}}if(Buffer.byteLength(i,`utf-8`)>hn)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=be(i,Oe(t,n,r));return o?(C(e,a,{mode:D(e)}),{kind:`removed`}):{kind:`not-present`}}function bn(e,t,n){let r;try{r=F(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T(e)}}if(Buffer.byteLength(r,`utf-8`)>hn)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,Ve.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=oe(a);a.trim()===``||a.endsWith(`
7
+ `)}}function dn(e,t,n,r={}){let i=Xt(e,t,n),a=t??z(),o=Zt(i.cwd),s=o.kind===`refused`&&r.recordedOnly?ln(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=$(a,()=>{let e=Z(a,i.cwd);return c===void 0||c===i.cwd?e:[...Z(a,c),...e]})}catch(e){return{action:`failed`,error:K(e instanceof Error?e.message:String(e))}}if(l.length===0&&r.recordedOnly)return o.kind===`ready`||s!==void 0?{action:`not-present`}:{action:`kept-unverified`,error:`${o.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`};if(o.kind===`refused`){if(l.length===0)return{action:`kept-unverified`,error:o.error};let e=l.map(({path:e,record:t})=>`key ${K(JSON.stringify(t.cwd))}; configured store ${K(JSON.stringify(t.configuredTrustPath))}; recorded destination ${K(JSON.stringify(t.canonicalTrustPath))}; ownership record ${K(JSON.stringify(e))} (${t.state})`);return{action:`kept-unverified`,error:[`${o.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,...e,`To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.`].join(`
8
+ `)}}let u=Yt(o.project.canonical,a,E.pi.projectConfigPath(o.project.canonical));if(u.kind===`unreadable`)return{action:`kept-unverified`,error:u.error};let d=u.kind===`shared`?u.paths:[],f=[],p=new Map,m=(e,t)=>{let n=p.get(e);if(!n){let t=nn(e);if(t.kind===`refused`){f.push({action:`refused-unreadable`,error:t.error});return}n={trustPath:e,resolved:t,keys:new Map},p.set(e,n)}if(t){if(n.resolved.path!==t.record.canonicalTrustPath){f.push({action:`refused-unreadable`,error:`Pi trust store ${K(e)} no longer points to its recorded destination ${K(t.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`});return}n.keys.set(t.record.cwd,{cwd:t.record.cwd,mode:`recorded`,receipt:t})}};for(let e of l)m(e.record.configuredTrustPath,e);m(i.trustPath);for(let e of p.values()){for(let t of[o.project.canonical,i.cwd])e.keys.has(t)||e.keys.set(t,{cwd:t,mode:`inspect`,receipt:l.find(n=>n.record.cwd===t&&n.record.canonicalTrustPath===e.resolved.path)});f.push(fn(e,a,d,o.project))}return un(f)}function $(e,t){try{return t()}catch(t){throw t instanceof J?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${K(A(S(e),`pi-trust`))}: ${K(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function fn(e,t,n,r){let{trustPath:i,resolved:a}=e,o=[...e.keys.values()];if(!o.some(e=>e.mode===`recorded`)&&a.kind===`missing`)return{action:`not-present`};if(a.kind===`missing`)try{P(k(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${K(k(a.path))} is unavailable: ${K(e instanceof Error?e.message:String(e))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`}}let s=[],c={result:{action:`not-present`}};try{Wt(i,a.path,()=>{let e=Qt(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=rn(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=en(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:Q(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:$(t,()=>Z(t,e.cwd).find(e=>e.record.canonicalTrustPath===l.path))}));if(d.some(e=>e.receipt&&e.receipt.record.configuredTrustPath!==e.expectedConfiguredPath)){c.result={action:`failed`,error:`The Pi trust ownership record changed during cleanup; retry to read its current location.`};return}for(let e of d){try{pn(e,t,i,l.path,u,n,r,c)}catch(t){let n=K(t instanceof Error?t.message:String(t)),r=t instanceof J?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${K(JSON.stringify(e.cwd))} in ${K(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:K(e instanceof Error?e.message:String(e))})}return un([...s,c.result])}function pn(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&$(t,()=>Tt(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${K(JSON.stringify(c))} entry from ${K(n)}; parent-folder and global trust settings still apply.`;if(a.length>0&&c===o.canonical){let n=`kept Pi's folder trust because other resources still need it: ${a.slice(0,3).map(e=>K(JSON.stringify(e))).join(`, `)}${a.length>3?` (+${a.length-3} more)`:``}. ${u} Removing this grant may stop Pi from loading those resources, including any not listed here.`;s.result={action:`kept-shared`,detail:n},l&&e.mode===`recorded`&&$(t,()=>Tt(t,l)),s.result={action:`kept-shared`,detail:`${n} ${l?e.mode===`recorded`?`OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.`:`OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.`:`OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.`}`};return}if(e.mode===`inspect`||!l||l.record.state===`pending`){let e=l?l.record.state===`pending`?`its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.`:`OpenKnowledge must reconcile its recorded location at ${K(l.record.configuredTrustPath)} before removing it.`:`no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.`;s.result={action:`kept-unowned`,detail:`${c===o.canonical?`kept Pi's folder trust because ${e}`:`kept a Pi trust entry under a non-canonical project path because ${e} Pi uses the real project directory instead of this key.`} ${u}`};return}let d={...i.entries};l.record.previous.present?d[c]=l.record.previous.value:delete d[c];let f=JSON.stringify(d,null,2)+(i.trailingNewline?`
9
+ `:``),p=D(r);C(r,f,p===void 0?void 0:{mode:p}),i.entries=d,$(t,()=>Tt(t,l)),s.result={action:`removed`}}function mn(e){return ye(e)||me(e)||ce(e)}const hn=10485760;function gn(e,t,n,r=!1){let i=dn(e,t,n,{recordedOnly:r});switch(i.action){case`removed`:case`not-present`:return{trust:i.action};case`kept-shared`:case`kept-unowned`:return{trust:i.action,trustDetail:i.detail};case`failed`:case`refused-unreadable`:case`kept-unverified`:{let e=r?`Trust cleanup remains incomplete`:`The bridge file was left untouched`;throw Error(`Pi trust cleanup failed (${i.action}):\n${i.error}\n${e} so cleanup can be retried.`)}default:throw Error(`unhandled Pi trust cleanup result: ${i}`)}}function _n(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=gn(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function vn(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=Ae(a);if(o.kind===`not-present`)return _n(e,t,n,i);if(o.kind===`declined`)return o;let s=Ee(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return _n(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!mn(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=gn(t,n,i);try{Fe(a,{force:!0})}catch(t){throw e.trustDetail?Error(`${t instanceof Error?t.message:String(t)}\n${e.trustDetail}`,{cause:t}):t}return{kind:`removed`,...e}}return e.format===`toml`?xn(o.path,c):e.format===`yaml`?bn(o.path,e.topLevelKey,c):yn(o.path,e.topLevelKey,e.serverMapSubKey,c)}function yn(e,t,n,r){let i;try{i=F(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T(e)}}if(Buffer.byteLength(i,`utf-8`)>hn)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=be(i,Oe(t,n,r));return o?(C(e,a,{mode:D(e)}),{kind:`removed`}):{kind:`not-present`}}function bn(e,t,n){let r;try{r=F(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T(e)}}if(Buffer.byteLength(r,`utf-8`)>hn)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,Ve.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=oe(a);a.trim()===``||a.endsWith(`
10
10
  `)?c.endsWith(`
11
11
  `)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
12
12
  `).replace(/\n/g,`\r
@@ -14,4 +14,4 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
14
14
  `),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
15
15
  `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
16
16
  `).replace(/\n/g,`\r
17
- `));let u=`${i?``:``}${l}`;return u!==r&&C(e,u,{mode:D(e)}),{kind:`removed`}}function Sn(e,t){let n=a[e];return n===null?null:A(t,...n.split(`/`),ie.discovery,`SKILL.md`)}function Cn(e,t){let n=Sn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!ae(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=w(`discovery`,{checkDesktop:!0});return le(k(n),t),{editorId:e,label:e,action:se(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function wn(e){return N(A(e,...`.agents/skills`.split(`/`),ie.discovery))?!0:i.some(t=>{let n=Sn(t,e);return n!==null&&N(k(n))})}function Tn(e,t){let n=Sn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return N(n)?(le(r,t),Fe(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 En(e){return e===`opencode`?Ce:Te}function Dn(e,t,n){let r=E[e],i=En(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=we(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function On(e,t,n=[]){let r=N(A(e,ie[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function kn(e,t){let n=pe.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=c.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:p}));return[...n,...r]}function An(e,t,n,r){let i=re(e,kn(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 jn(e,t){let n=(t??z()).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 Mn(e,t){let n=E[e];return de(n,``,t)&&!_e(n,``,t)}function Nn(e,t,n,r,i){let a=E[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?jn(o,r):void 0,c=Ee(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&Mn(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];ye(r)&&i.push(`reclaim-permissive`),me(r)&&i.push(`pre-approval-exact`),En(e)(r)&&i.push(`injection-functional`);let o=ge(a,n);return i.length>0&&(o!==null&&Se(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}:De(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function Pn(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=s(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:On(A(n,p),`discovery`,An(n,a,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=a[i];return e===null||n===void 0?null:ae(n).some(e=>e.editorId===i)?On(A(n,e),`discovery`,An(n,a,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=l[i];return e===null?null:On(A(t,e),`project`,An(t,l,i,`project`))}case`editor-user-config`:return Nn(i,e.strictness,t,n);case`editor-project-config`:{let r=E[i].projectConfigPath?.(t);return r===void 0?null:Nn(i,e.strictness,t,n,r)}}}}export{Xe as C,Ge as E,Je as S,Ue as T,ot as _,Cn as a,B as b,an as c,ct as d,st as f,ht as g,mt as h,wn as i,K as l,pt as m,Dn as n,vn as o,G as p,Tn as r,sn as s,Pn as t,it as u,nt as v,Ze as w,Qe as x,rt as y};
17
+ `));let u=`${i?``:``}${l}`;return u!==r&&C(e,u,{mode:D(e)}),{kind:`removed`}}function Sn(e,t){let n=r[e];return n===null?null:A(t,...n.split(`/`),w.discovery,`SKILL.md`)}function Cn(e,t){let n=Sn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!ie(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=x(`discovery`,{checkDesktop:!0});return le(k(n),t),{editorId:e,label:e,action:se(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function wn(e){return N(A(e,...`.agents/skills`.split(`/`),w.discovery))?!0:y.some(t=>{let n=Sn(t,e);return n!==null&&N(k(n))})}function Tn(e,t){let n=Sn(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return N(n)?(le(r,t),Fe(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 En(e){return e===`opencode`?Ce:Te}function Dn(e,t,n){let r=E[e],i=En(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=we(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function On(e,t,n=[]){let r=N(A(e,w[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function kn(e,t){let n=pe.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=p.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:d}));return[...n,...r]}function An(e,t,n,r){let i=ae(e,kn(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 jn(e,t){let n=(t??z()).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 Mn(e,t){let n=E[e];return de(n,``,t)&&!_e(n,``,t)}function Nn(e,t,n,r,i){let a=E[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?jn(o,r):void 0,c=Ee(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&Mn(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];ye(r)&&i.push(`reclaim-permissive`),me(r)&&i.push(`pre-approval-exact`),En(e)(r)&&i.push(`injection-functional`);let o=ge(a,n);return i.length>0&&(o!==null&&Se(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}:De(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function Pn(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let a=o(e.pathId);if(a===null)return null;if(a.kind===`central-skill-store`)return n===void 0?null:On(A(n,d),`discovery`,An(n,r,e.agent,`global`));let s=a.editor;switch(a.kind){case`editor-user-skill-root`:{let e=r[s];return e===null||n===void 0?null:ie(n).some(e=>e.editorId===s)?On(A(n,e),`discovery`,An(n,r,s,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=i[s];return e===null?null:On(A(t,e),`project`,An(t,i,s,`project`))}case`editor-user-config`:return Nn(s,e.strictness,t,n);case`editor-project-config`:{let r=E[s].projectConfigPath?.(t);return r===void 0?null:Nn(s,e.strictness,t,n,r)}}}}export{Xe as C,Ge as E,Je as S,Ue as T,ot as _,Cn as a,B as b,an as c,ct as d,st as f,ht as g,mt as h,wn as i,K as l,pt as m,Dn as n,vn as o,G as p,Tn as r,sn as s,Pn as t,it as u,nt as v,Ze as w,Qe as x,rt as y};
@@ -1 +1 @@
1
- import{C as e,N as t}from"./init-DxmL4VOM.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:t(e)}}let o=e(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:a&&e.code===`ENOENT`?`missing-symlink-target`:t(e)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
1
+ import{C as e,N as t}from"./init-UZr9GVxw.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:t(e)}}let o=e(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:a&&e.code===`ENOENT`?`missing-symlink-target`:t(e)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
@@ -1 +1 @@
1
- import{t as e}from"./launch-json-removal-joOXjG0j.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
1
+ import{t as e}from"./launch-json-removal-DdasfWvu.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
@@ -1 +1 @@
1
- import{E as e}from"./md-manager-BGnqyqi1-C2MED2uJ.mjs";import{Y as t,Z as n,b as r,et as i,it as a,p as o,tt as s}from"./init-DxmL4VOM.mjs";import{homedir as c}from"node:os";function l(e){let{priorCommand:t,priorArgs:n}=u(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u(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 d(e){let r=e.logger??h,i=e.home??c(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=f(()=>t.configPath(``,i));if(s!==null&&a.push(p({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=f(()=>n(e.projectDir));i!==null&&a.push(p({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function f(e){try{return e()}catch{return null}}function p(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},c=o(t.target,t.cwd,t.home,t.configPathOverride);if(c===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(c))return{...n,outcome:`canonical`}}else{let a=e(c);if(a.kind===`recognized`&&a.disposition===`keep`){let e=s(c,i(t.target,t.cwd));if(e.length===0)return{...n,outcome:`canonical`};let a=m(t,n,r(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(a.outcome===`repaired`||a.outcome===`canonical`)&&t.logger({event:a.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:a.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),a.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:a}if(a.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:a.reason}),{...n,outcome:`foreign`,reason:a.reason}}return t.logger({...l({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:c}),severity:`info`}),m(t,n,r(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride))}function m(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function h(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{u as n,d as repairMcpConfigs,l as t};
1
+ import{E as e}from"./md-manager-BGnqyqi1-CSFPyGy0.mjs";import{Y as t,Z as n,b as r,et as i,it as a,p as o,tt as s}from"./init-UZr9GVxw.mjs";import{homedir as c}from"node:os";function l(e){let{priorCommand:t,priorArgs:n}=u(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u(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 d(e){let r=e.logger??h,i=e.home??c(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=f(()=>t.configPath(``,i));if(s!==null&&a.push(p({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=f(()=>n(e.projectDir));i!==null&&a.push(p({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function f(e){try{return e()}catch{return null}}function p(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},c=o(t.target,t.cwd,t.home,t.configPathOverride);if(c===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(c))return{...n,outcome:`canonical`}}else{let a=e(c);if(a.kind===`recognized`&&a.disposition===`keep`){let e=s(c,i(t.target,t.cwd));if(e.length===0)return{...n,outcome:`canonical`};let a=m(t,n,r(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(a.outcome===`repaired`||a.outcome===`canonical`)&&t.logger({event:a.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:a.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),a.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:a}if(a.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:a.reason}),{...n,outcome:`foreign`,reason:a.reason}}return t.logger({...l({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:c}),severity:`info`}),m(t,n,r(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride))}function m(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function h(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{u as n,d as repairMcpConfigs,l as t};
@@ -189,7 +189,7 @@
189
189
  "agentSettable": false,
190
190
  "reload": "live",
191
191
  "defaultScope": "project",
192
- "description": "Write local diagnostic spans + logs under .ok/local/ for `ok diagnose bundle`. Local-only — never leaves the machine until you run bundle. Set false for sensitive workspaces. Shared across collaborators."
192
+ "description": "Write per-project diagnostic spans + logs under the user-level OpenKnowledge logs directory for `ok diagnose bundle`. Files stay local unless shared, including in a support bundle. Set false for sensitive workspaces. Shared across collaborators."
193
193
  },
194
194
  "spans": {
195
195
  "default": {
@@ -0,0 +1,16 @@
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$l as t,Bf as n,Da as r,Ff as i,G as a,Kf as o,Oa as s,U as c,Vf as l,W as u,Wf as d,Xf as ee,Zf as f,eu as p,fl as m,l as h,ml as te,ol as g,pd as _,pl as v,qf as y,sl as b,tp as x,u as ne,ul as S}from"./md-manager-BGnqyqi1-CSFPyGy0.mjs";import{Ai as C,Di as w,Ds as T,Ei as re,Eo as E,Es as D,Is as O,Ji as k,Ko as A,Ls as ie,Ns as ae,Nt as j,Oi as M,Os as oe,Ps as N,Qt as P,Rs as F,Sa as se,Va as I,Ws as ce,Xi as le,_r as ue,bi as de,ii as fe,ks as pe,m as me,oa as he,pi as L,pr as ge,rr as _e,ya as ve,zs as ye}from"./dist-BniR5KN1.mjs";import{t as be}from"./yazl-BBz29IQN.mjs";import{ct as xe,gt as Se,ht as Ce,mt as we,pt as Te,st as Ee,wt as De}from"./init-UZr9GVxw.mjs";import{T as Oe,l as ke,u as Ae}from"./registry-probes-DA_47MnL.mjs";import{c as je}from"./colors-r_owlCuY.mjs";import{t as Me}from"./is-object-BGze3w87.mjs";import{n as Ne}from"./constants-BrQxqUNL.mjs";import"./loader-Dbq_EWV8.mjs";import"./preview-BRJmRFNY.mjs";import{execFile as Pe,execSync as Fe,spawnSync as Ie}from"node:child_process";import{basename as R,dirname as z,isAbsolute as Le,join as B,relative as Re,resolve as V,sep as H,win32 as ze}from"node:path";import{closeSync as Be,cpSync as Ve,createWriteStream as He,existsSync as U,lstatSync as Ue,mkdirSync as W,mkdtempSync as We,openSync as Ge,readFileSync as G,readSync as Ke,readdirSync as K,readlinkSync as qe,realpathSync as Je,rmSync as Ye,rmdirSync as Xe,statSync as Ze,writeFileSync as q}from"node:fs";import{arch as Qe,freemem as $e,homedir as J,hostname as et,platform as tt,release as nt,tmpdir as rt,totalmem as it,type as at,uptime as ot}from"node:os";import{createHash as st}from"node:crypto";import{readFile as ct,readdir as lt,stat as ut}from"node:fs/promises";function dt(e,t){let n=t.map(e=>[ce(e),e]);for(let t of e){let e=ce(t);if(e===null)continue;let r=n.find(([t])=>t===e);if(r!==void 0)return r[1]}}function ft(e){let{override:t,storedPreference:n,preferenceList:r,supportedLocales:i}=e,a=e.autoDetectableLocales??i;if(t!==void 0){let e=dt([t],i);if(e!==void 0)return{locale:e,source:`override`}}if(n!==void 0&&n!==`system`&&i.includes(n))return{locale:n,source:`explicit`};let o=dt(r,a);return o===void 0?{locale:`en`,source:`fallback`}:{locale:o,source:`system`}}function pt(e,t=Date.now()){let n=Date.parse(e);if(!Number.isFinite(n))return`unknown`;let r=Math.floor(Math.max(0,t-n)/1e3);if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}const mt=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`audit`,`deinit`,`auth`]);function ht(e,t,n=ue){if(e!==void 0&&!mt.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let gt=null;function _t(e){gt=e}function vt(){return gt??process.cwd()}const yt=`Open Knowledge`;function bt(e={}){let t=e.platformName??process.platform,n=e.productName??y().productName;return Ee(t).join(xe({...e,platformName:t}),n)}function xt(e={}){let t=e.platformName??process.platform,n=e.home??J(),r=e.env??process.env,i=Ee(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`${y().packageName.replaceAll(`/`,``)}-updater`)}function St(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Ct(e){let t=B(e,`state.json`);if(!U(t))return[];let n;try{n=JSON.parse(G(t,`utf-8`))}catch{return[]}return St(n)??[]}function wt(e){let t=B(e,`state.json`);if(!U(t))return!1;try{return St(JSON.parse(G(t,`utf-8`)))!==null}catch{return!1}}const Tt=8192;function Et(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function Dt(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Ot=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function kt(e){return e.replace(Ot,`$1"[REDACTED-DEVICE-ID]"`)}function At(e){return kt(Dt(e))}const jt=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Mt(e){if(typeof e!=`string`)return null;let t=jt.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function Nt(e){let t=Ge(e,`r`);try{let e=Buffer.alloc(Tt),n=0,r=!1;for(;n<Tt;){let i=Ke(t,e,n,Tt-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{Be(t)}}function Pt(e){try{let t=Nt(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Mt(a)}}catch{return{kind:`unreadable`}}}function Ft(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function It(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=K(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=B(e,t.name),r;try{r=Ze(n).mtimeMs}catch{continue}if(r<i)continue;let c=Pt(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Ft(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}const Lt=`state/os-termination-evidence.json`,Rt=6048e5,zt=/openknowledge/i,Bt=d.map(e=>f(l[e]));function Vt(e={}){return(t,n)=>new Promise(r=>{try{Pe(t,n,{encoding:`utf8`,timeout:e.timeoutMs??15e3,maxBuffer:e.maxBuffer??16777216,windowsHide:!0},(e,t,n)=>{r({...Ht(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function Ht(e){return e===null?{status:0}:typeof e.code==`string`?{status:null,errorCode:e.code}:typeof e.code==`number`?{status:e.code}:e.killed===!0?{status:null,errorCode:`ETIMEDOUT`}:e.signal?{status:null,signal:e.signal}:{status:null}}function Ut(e){if(e.errorCode!==void 0)return e.errorCode;if(e.signal!==void 0)return`signal ${e.signal}`;let t=(e.stderr.trim().split(`
2
+ `)[0]??``).replace(/\S*\/journal\/\S*/g,`<journal path>`).replace(/\b[0-9a-f]{32}\b/gi,`<id>`);return`exit ${e.status}${t===``?``:`: ${t}`}`}function Wt(e,t,n){return{schemaVersion:1,platform:e,source:t,outcome:`none-in-window`,readFrom:n,windowDays:7,foreignIgnored:0,unparseable:0,droppedOverCap:0,events:[]}}function Gt(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function Kt(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function qt(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Jt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Yt(e,t){let n=t.indexOf(`
3
+ `);if(n===-1)return null;let r,i;try{r=Jt(JSON.parse(t.slice(0,n))),i=Jt(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=Jt(e);t===null||typeof t.name!=`string`||!Ft(t.name)||a.push({name:t.name,pid:qt(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:qt(t.rpages),lifetimeMaxPages:qt(t.lifetimeMax)})}let o=Mt(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:qt(Jt(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?Ft(i.largestProcess):null,ownedProcesses:a}}const Xt=/^JetsamEvent-.*\.ips$/;function Zt(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 Qt(e,t){let n=Wt(`darwin`,`macos-jetsam`,[B(e,`JetsamEvent-*.ips`)]),r;try{r=await lt(e)}catch(e){return Gt(n,e.code??`unknown`)}let i=Zt(await Promise.all(r.filter(e=>Xt.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await ut(B(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-Rt,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=Yt(t,await ct(B(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return Kt(n)}const $t=[`--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`],en=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],tn=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,nn=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,rn=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function an(e,t){let n=new Set,r;try{r=await lt(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!rn.test(a))continue;let r=B(e,a);try{if(t.getTime()-(await ut(r)).mtimeMs>Rt)continue;for(let e of(await ct(r,`utf8`)).split(`
4
+ `)){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 on(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:zt.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 sn(e){let t=[],n=0,r=0;for(let i of e.split(`
5
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=tn.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!zt.test(s)){n+=1;continue}let c=on(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function cn(e){let t=[],n=0,r=0;for(let i of e.split(`
6
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=tn.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=nn.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 ln(e,t,n){let r=cn(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await an(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 un(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function dn(e,t,n){let r=Wt(`linux`,`linux-journal`,[`journalctl ${$t.join(` `)}`,`journalctl ${en.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...$t]),e(`journalctl`,[...en])]),o=[];if(un(i)){let e=sn(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: ${Ut(i)}`);if(un(a)){let e=await ln(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: ${Ut(a)}`);return o.length===2?Gt(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:Kt(r)}const fn={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},pn={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function mn(e){return e===`System`?fn:pn}function hn(e){let t=`System[(${Object.keys(mn(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${Rt}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${Bt.map(e=>`Data='${e}'`).join(` or `)}]]`}function gn(e){return[`qe`,e,`/q:${hn(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function _n(e){return ze.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function vn(e){return e.replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}function yn(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function bn(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>vn(e[1]??``).trim())}function xn(e,t){let n=mn(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=bn(o,`Data`),u=bn(o,`Name`),d=[...l,...u].some(e=>zt.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!==``&&!yn(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function Sn(e,t){let n=_n(t),r=[`System`,`Application`],i=Wt(`win32`,`windows-event-log`,r.map(e=>`${n} ${gn(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,gn(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${Ut(t)}`);continue}let n=xn(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?Gt(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:Kt(i)}async function Cn(e={}){let t=e.platform??process.platform,n=e.runCommand??Vt(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return Qt(e.macosReportsDir??`/Library/Logs/DiagnosticReports`,r);case`linux`:return dn(n,r,e.desktopLogsDir??B(N(),`logs`));case`win32`:return Sn(n,e.systemRoot??process.env.SystemRoot);default:return{...Wt(t,null,[]),outcome:`unsupported`}}}const wn={schemaVersion:1,outcome:`not-collected`};function Tn(e){return`${JSON.stringify(e??wn,null,2)}\n`}const En={"macos-jetsam":`macOS low-memory reports`,"linux-journal":`system and user journals`,"windows-event-log":`Windows event logs`};function Dn(e){let t=[`${e.windowDays}d`,`${e.events.length} kept`,`${e.foreignIgnored} other-process record(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&t.push(`${e.droppedOverCap} older dropped over cap`);let n=e.source?` from ${En[e.source]}`:``,r=e.unavailableReason?`, ${e.unavailableReason}`:``;return`${e.outcome}${n}${r} (${t.join(`; `)})`}function On(){return B(N(),`bug-reports`)}function kn(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=On(),r=`${t}-bugreport`,i=B(n,`${r}.zip`);for(let e=2;U(i);e+=1)i=B(n,`${r}-${e}.zip`);return i}function An(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function jn(e,t){let n=B(e,`.ok`,`config.yml`);if(U(n))try{let e=G(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return U(B(e,`.ok`))?st(`sha256`).update(V(e)).digest(`hex`).slice(0,12):null}function Mn(){let e={timestamp:new Date().toISOString(),platform:tt(),osType:at(),osRelease:nt(),hostname:`[redacted]`,uptime:ot(),freeMem:$e(),totalMem:it(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Fe(`sw_vers -productVersion 2>/dev/null`,A({encoding:`utf8`})).trim()}catch{}try{let t=B(__dirname,`..`,`..`,`package.json`);U(t)&&(e.okVersion=JSON.parse(G(t,`utf8`)).version)}catch{}return e}const Nn=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function Pn(e){let t=R(e);return Nn.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function Fn(e,t){return zn(e,t).files}const In=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function Ln(e,t=Ae){let n=B(e,`${t}.ShipIt`);if(!U(n))return[];let r;try{r=K(n)}catch{return[]}return In.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>B(n,e.entry)))}function Rn(e){if(!U(e))return[];try{let t=new Map;for(let n of K(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-h.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>B(e,t))}catch{return[]}}function zn(e,t){if(!U(t))return{files:[],excludedByProjectSlug:0};let n=K(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>B(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(Pn),i=[],a=r.filter(t=>{try{return G(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!Pn(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function Bn(e){let t=B(e,`.ok`,`local`);return U(t)?{files:[`server.lock`,m,b].map(e=>B(t,e)).filter(e=>U(e))}:{files:[]}}function Vn(e,t,n){let r=ae(e),i=[],a=[];for(let e of t){let t=B(r,e),o=B(n,e),s=U(t);s&&i.push(t),U(o)&&(s?a:i).push(o)}return{files:i,legacyFiles:a}}function Hn(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#${st(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function Un(e){let t=e.revealDocNames?e.content:Hn(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=s(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 Y(e){for(let t of e.files)try{let n=G(t,`utf8`);Un({zipfile:e.zipfile,name:`${e.prefix}/${R(t)}`,content:t.endsWith(`.ips`)?At(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 Wn(t){let{redact:n,outputPath:i,logger:a}=t,o=t.revealDocNames??!1,s=t.userLogsDir??B(N(),`logs`),c=t.projectDir?jn(t.projectDir,a):null;W(z(i),{recursive:!0}),a?.info({projectSlug:c},`gathering diagnostic data`);let l=Mn();l.desktop=t.desktop??null,l.language=t.language??null;let{files:u,excludedByProjectSlug:d}=zn(c,s),{files:ee}=t.projectDir?Bn(t.projectDir):{files:[]},{files:f,legacyFiles:p}=t.projectDir?Vn(t.projectDir,[S.logsCurrent,S.logsPrevious],B(t.projectDir,`.ok`,`local`,`logs`)):{files:[],legacyFiles:[]},{files:m,legacyFiles:h}=t.projectDir?Vn(t.projectDir,[te],B(t.projectDir,`.ok`,`local`)):{files:[],legacyFiles:[]},_=t.shipItLogFiles??[],v=t.diagnosticReports?.files??[];a?.info({logFileCount:u.length,logFilesExcludedByProjectSlug:d,lockFileCount:ee.length+m.length+h.length,localSinkFileCount:f.length+p.length,shipItLogFileCount:_.length,diagnosticReportCount:v.length},`files collected`);let y=[],b=[],{ZipFile:x}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),C=new x;Y({zipfile:C,files:[...u,..._],prefix:`logs`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:[...ee,...m],prefix:`lockdir`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:f,prefix:`local-logs`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:p,prefix:`legacy/local-logs`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:h,prefix:`legacy/lockdir`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:t.bugReportLedgerFiles??[],prefix:ne,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a}),Y({zipfile:C,files:v,prefix:`diagnostic-reports`,redact:n,revealDocNames:o,bundleFiles:b,redactions:y,logger:a});for(let e of t.extraFiles??[])try{let t=G(e.sourcePath),n=`extra/${e.zipName??R(e.sourcePath)}`;C.addBuffer(t,n),b.push(n);let r=An(e,n);r!==null&&y.push(r)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&Un({zipfile:C,name:`note.txt`,content:t.note,redact:n,revealDocNames:o,bundleFiles:b,redactions:y});let w=new Set(v.map(e=>`diagnostic-reports/${R(e)}`)),T=b.filter(e=>w.has(e)),re=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Et(t.diagnosticReports,T.length);C.addBuffer(Buffer.from(`${re}\n`,`utf8`),`state/diagnostic-reports-status.txt`),b.push(`state/diagnostic-reports-status.txt`),Un({zipfile:C,name:Lt,content:Tn(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:b,redactions:y});let E=JSON.stringify(l,null,2);C.addBuffer(Buffer.from(E,`utf8`),`sysinfo.json`),b.push(`sysinfo.json`);let D={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:c,files:b,redactions:y,sysinfo:l};C.addBuffer(Buffer.from(JSON.stringify(D,null,2),`utf8`),`MANIFEST.json`);let O=y.reduce((e,t)=>e+t.lineCount,0),k=new Set(_.map(e=>`logs/${R(e)}`)),A=b.filter(e=>k.has(e)),ie=new Set((t.bugReportLedgerFiles??[]).map(e=>`${ne}/${R(e)}`)),ae=b.filter(e=>ie.has(e)),j=c?b.filter(e=>e.startsWith(`logs/`)&&!Pn(e)&&!k.has(e)):[],M=T.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.`]:[],oe=M.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...M]:[`Redaction was disabled for this bundle; file contents are unmodified.`],P=[`# Bug Report Bundle`,``,`Generated: ${D.generatedAt}`,`Project: ${c??`(unscoped)`}`,...t.projectDir?[`Project diagnostic source: ${g(`logs`,`projects`)} (current product only).`]:[],`Discipline version: ${D.disciplineVersion}`,``,`## Contents`,``,...b.map(e=>`- ${e}`),``,`## Privacy`,``,...j.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:`,...j.map(e=>`- ${e}`),``]:[],...A.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:`,...A.map(e=>`- ${e}`),``]:[],...T.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:`,...T.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:`,`- ${Lt}`,``]:[],...ae.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:`,...ae.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${r.join(`, `)}`,O>0?`${O} line(s) were scrubbed across ${y.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...M,``,`This bundle is safe to attach to a GitHub issue.`]:oe].join(`
7
+ `);C.addBuffer(Buffer.from(P,`utf8`),`README.md`),C.end();let F=He(i);return C.outputStream.pipe(F),await new Promise((e,t)=>{F.on(`close`,e),F.on(`error`,t)}),a?.info({bundlePath:i,fileCount:b.length,redactionCount:O},`bundle written`),{zipPath:i,summary:{projectSlug:c,files:b,redactions:y,redactedLineCount:O,generatedAt:D.generatedAt}}}var Gn=_(),Kn=e(be(),1),X=e(je(),1);function qn(e){let t=ye(`user`,e,e);return ie({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function Jn({home:e=J(),env:n=process.env}={}){let r=qn(e),{override:i,preferenceList:a}=F(n),{locale:o,source:s}=ft({override:i,storedPreference:r,supportedLocales:p,preferenceList:a,autoDetectableLocales:t});return{preference:r,locale:o,source:s,systemLanguages:a}}function Yn(e){let t=new Set([e]);try{t.add(Je.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 Xn(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function Zn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qn(e,t){if(typeof e==`string`)return Xn(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>Qn(e,t));if(!Zn(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=Qn(i,t);return n}function $n(e,t){let n=G(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
8
+ `),i=n.split(`
9
+ `),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=Qn(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
10
+ `)}\n`:a.join(`
11
+ `);q(e,o)}function er(e,t){let n=G(e,`utf-8`);if(n.trim().length!==0)try{let r=Qn(JSON.parse(n),t),i=n.endsWith(`
12
+ `)?`
13
+ `:``;q(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=Xn(n,t.contentDirSpellings);r!==n&&q(e,r)}}function tr(e,t){let n=G(e,`utf-8`),r=Xn(n,t.contentDirSpellings);r!==n&&q(e,r)}function nr(e){try{return K(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>B(e,t.name))}catch{return[]}}const rr=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function ir(e){return/\.log\.\d+$/.test(e)}function ar(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||ir(e)}const or=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function sr(e){let t={contentDirSpellings:Yn(e.contentDir)};for(let n of or)for(let r of nr(B(e.stagingDir,n)))ar(r)?$n(r,t):r.endsWith(`.json`)?er(r,t):tr(r,t);for(let n of nr(B(e.stagingDir,`state`))){let e=R(n);n.endsWith(`.jsonl`)?$n(n,t):rr.has(e)?er(n,t):tr(n,t)}}const cr=[`.ok`,`local`,`telemetry`],lr=[`.ok`,`local`,`logs`],ur=[`.ok`,`local`,`loss-capture`],dr=S.spansCurrent,fr=S.spansPrevious,pr=S.logsCurrent,mr=S.logsPrevious,hr=`loss-current.jsonl`,gr=`loss-prev.jsonl`;function _r(e){return B(e,...ur,hr)}function vr(e){return B(e,...ur,gr)}const yr=1e3;async function br(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(yr)});return t.ok?await t.text():null}catch{return null}}async function xr(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(yr)});return t.ok?await t.text():null}catch{return null}}async function Sr(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(yr)});return t.ok?await t.text():null}catch{return null}}function Cr(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(`
14
+ `)}\n`:null}catch{return null}}function wr(e){let t=B(e,`.git`,`ok`);if(!U(t))return null;let n=Ie(`git`,[`-C`,t,`log`,`--oneline`,`-50`],A({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Tr(e){let t=B(e,`.git`,`ok`);if(!U(t))return null;let n=Ie(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],A({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Er(){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 Dr(){return{nodeVersion:process.version,platform:tt(),arch:Qe()}}function Or(){return process.env.OTEL_SDK_DISABLED===`false`}function kr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ar(e){if(!U(e))return{};let t;try{t=(0,Gn.parse)(G(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!kr(t))return{};let n=t.telemetry;if(!kr(n))return{};let r=n.localSink;return kr(r)?r:{}}function jr(e){return typeof e==`boolean`?e:void 0}function Mr(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Nr(e){if(kr(e))return Mr(e.maxBytes)}function Pr(e){let t=Ar(ye(`project`,e)),n=Ar(ye(`project-local`,e));return{enabled:jr(n.enabled)??jr(t.enabled)??!0,spansMaxBytes:Nr(n.spans)??Nr(t.spans)??52428800,logsMaxBytes:Nr(n.logs)??Nr(t.logs)??26214400}}function Fr(e){return st(`sha256`).update(e).digest(`hex`)}function Ir(e){let t=G(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Lr=[`"doc.name"`,`"docName"`];function Rr(e){let t=G(e,`utf-8`),n=0;for(let e of Lr){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z(e,t){if(!U(e))return!1;try{return W(z(t),{recursive:!0}),e.endsWith(`.ips`)?q(t,At(G(e,`utf-8`))):Ve(e,t),!0}catch{return!1}}function Q(e,t,n,r){let i=U(e);Z(e,B(n,r)),Z(t,i?B(n,`legacy`,r):B(n,r))}function zr(e){let t=[],n=e=>{let r=K(e,{withFileTypes:!0});for(let i of r){let r=B(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Br=new Set([`.jsonl`]);function Vr(e){let t=e.lastIndexOf(`.`);return t!==-1&&Br.has(e.slice(t))}const Hr=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Ur(e){if(ir(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Hr.has(e.slice(t))}function Wr(e){let t=[];for(let n of zr(e)){let r=Gr(e,n);if(!Ur(r))continue;let{redacted:i,patterns:a,lineCount:o}=s(G(n,`utf-8`));a.length!==0&&(q(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function Gr(e,t){return Re(e,t).split(H).join(`/`)}async function Kr(e){let t=V(e.contentDir),n=V(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??br,a=r.fetchAgentEffects??xr,o=r.fetchWatcherRecent??Sr,s=r.readShadowHead??wr,c=r.readCheckpointRefs??Tr,l=r.now??(()=>new Date),u=r.okVersion??(()=>Ne),d=r.readDesktopEnv??Er,ee=r.readLanguage??Jn,f=r.readRuntime??Dr,p=r.isOtlpPushEnabled??Or,h=We(B(rt(),`ok-bundle-`));try{W(B(h,`telemetry`),{recursive:!0}),W(B(h,`logs`),{recursive:!0}),W(B(h,`state`),{recursive:!0}),Q(oe(n),B(n,...cr,dr),h,B(`telemetry`,dr)),Q(pe(n),B(n,...cr,fr),h,B(`telemetry`,fr)),Q(D(n),B(n,...lr,pr),h,B(`logs`,pr)),Q(T(n),B(n,...lr,mr),h,B(`logs`,mr));for(let t of e.userLogFiles??[])Z(t,B(h,`logs`,R(t)));for(let t of e.userStateFiles??[])Z(t,B(h,ne,R(t)));let _=0;for(let t of e.diagnosticReports?.files??[])Z(t,B(h,`diagnostic-reports`,R(t)))&&(_+=1);let y=B(n,`.ok`,`local`),x=B(y,`server.lock`),S=`not-running`,C=`no server.lock`,w=null;if(U(x)){Z(x,B(h,`state`,`server.lock`));try{let e=G(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?w=t.port:C=`lock present but no port`}catch{C=`lock present but unparseable`}}if(w!==null){let e=await i(w);e===null?C=`agent-presence endpoint at :${w} unreachable`:(q(B(h,`state`,`agent-presence.json`),e),S=`running`,C=``);let t=await a(w);t!==null&&q(B(h,`state`,`agent-effects.json`),t);let n=await o(w);if(n!==null){let e=Cr(n);e!==null&&q(B(h,`state`,`watcher-recent.jsonl`),e)}}let re=s(t);re!==null&&q(B(h,`state`,`shadow-head.txt`),re);let E=c(t);E!==null&&q(B(h,`state`,`checkpoint-refs.txt`),E),Z(_r(n),B(h,`state`,hr)),Z(vr(n),B(h,`state`,gr)),Q(O(n),B(y,te),h,`state/last-spawn-error.log`),Z(B(y,v),B(h,`state`,v)),Z(B(y,m),B(h,`state`,m)),Z(B(y,b),B(h,`state`,b));let k=f(),A=d(),ie=ee(),ae={ok:{version:u(),nodeVersion:k.nodeVersion,platform:k.platform,arch:k.arch},host:{desktop:A,language:ie}};q(B(h,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let j=S===`running`?`running
15
+ `:`not-running (${C})\n`;q(B(h,`state`,`server-status.txt`),j);let M=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:Et(e.diagnosticReports,_);if(q(B(h,`state`,`diagnostic-reports-status.txt`),`${M}\n`),q(B(h,Lt),Tn(e.osTerminationEvidence)),e.processDir&&U(e.processDir)){let t=B(h,`process`);W(t,{recursive:!0}),Ve(e.processDir,t,{recursive:!0})}let N=e.redact===!0;N&&(sr({stagingDir:h,contentDir:t}),sr({stagingDir:B(h,`legacy`),contentDir:t})),e.note&&q(B(h,`note.txt`),e.note);let P=null;e.scrubSecrets===!0&&(P=Wr(h));for(let t of e.extraFiles??[]){let e=t.zipName??R(t.sourcePath);if(!Z(t.sourcePath,B(h,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=An(t,`extra/${e}`);n!==null&&(P??={redactions:[],redactedLineCount:0},P.redactions.push(n),P.redactedLineCount+=n.lineCount)}let F=Pr(n),se=zr(h),I=[],ce=0,le=0;for(let e of se){let t=Gr(h,e),n=Ze(e).size,r=Vr(t)?Ir(e):0;I.push({path:t,bytes:n,lines:r}),ce+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(le+=Rr(e))}let ue={applied:N};P!==null&&(ue.secretScrub=P);let de={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:k.nodeVersion,platform:k.platform,arch:k.arch},host:{desktop:A,language:ie},contentDir:{pathSha256:Fr(t),absolutePath:N?`<CONTENT_DIR>`:t},telemetry:{localSink:{...F,directory:g(`logs`,`projects`)},otlpPushEnabled:p()},redaction:ue,serverStatus:S,files:I};q(B(h,`manifest.json`),`${JSON.stringify(de,null,2)}\n`);let fe=Yn(t),me=se.some(e=>{try{let t=G(e,`utf-8`);return fe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:_,totalBytes:ce,fileCount:I.length,docNameCount:le,contentDirVisible:me,redacted:N},L=!1;return{stagingDir:h,manifest:de,summary:he,cleanup:()=>{L||(L=!0,Ye(h,{recursive:!0,force:!0}))}}}catch(e){throw Ye(h,{recursive:!0,force:!0}),e}}async function qr(e){let{collected:t,outputPath:n}=e,r=z(n);if(!U(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new Kn.ZipFile,a=zr(t.stagingDir);for(let e of a){let n=Gr(t.stagingDir,e);i.addFile(e,n)}i.end();let o=He(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 Jr(e,t){let n=B(e,`.ok`,`config.yml`);if(U(n))try{let t=(0,Gn.parse)(G(n,`utf-8`)),r=Me(t)?t.content:void 0,i=Me(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return V(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return V(e)}async function Yr(e,t,n,r,i,a){let o=jn(t,e.logger),s=await Kr({contentDir:Jr(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Fn(o,e.userLogsDir??B(N(),`logs`)),...Ln(e.cachesDir??B(J(),`Library`,`Caches`))],userStateFiles:Rn(e.bugReportsDir??On()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{W(z(e.outputPath),{recursive:!0}),await qr({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function Xr(e){let{projectDir:t}=e,n=e.readDesktopEnv??Er,r=e.readLanguage??Jn,i=()=>It(e.diagnosticReportsDir??B(J(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Yr(e,t,n,r,i(),await Cn(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await Wn({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:Ln(e.cachesDir??B(J(),`Library`,`Caches`)),bugReportLedgerFiles:Rn(e.bugReportsDir??On()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await Cn(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=M(e,t),i;try{i=G(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r,text:i}}let o=a&&typeof a==`object`?a:{},s=ve(o),c=s&&!fe(o,n);if(!a||typeof a!=`object`||!de(a.pid))return{status:`corrupt`,lockPath:r,text:i,...c?{foreignHost:!0}:{}};let l=E(a),{pid:u}=l;if(c)return{status:`foreign-host`,lockPath:r,lock:l};let d=P(l,{isAlive:n.isAlive,readProcessStart:n.readProcessStart,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 Zr(e){return`does not record its owning machine, and its recorded process ${e} is still running on this machine`}function Qr(e){return typeof e.machineId==`string`?`records a machine ID different from the one in ${C()}`:`records only the host ${ke(e.hostname)}, not this machine's ${et()}`}function $r(e){return e===`win32`?`USERPROFILE`:`HOME`}function ei(e){return e.processStart===void 0?` This lock records no process start; a server started by this release records one, which lets \`${o()} stop\` confirm it from any home folder.`:``}function ti(e,t){let n=`\`${o()} 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 \`${$r(t)}\` set to that folder. Otherwise stop it from the machine that owns the lock.${ei(e)}`}function ni(e,t){let n=o();return`If the server was started on this machine from another account, run \`${n} stop\` as that account while it is running, or \`${n} clean\` once it has exited. If it was started from this account with a different home folder, run the same command with \`${$r(t)}\` set to that folder. Otherwise run the same command on the machine that owns the lock.${ei(e)}`}function ri(e){return`Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it. Only then remove the stale lock file at ${e} and retry cleanup.`}function ii(e,t=process.platform){let{lock:n,lockPath:r}=e;return`${typeof n.machineId==`string`?ni(n,t):`If ${ke(n.hostname)} is another machine, stop OpenKnowledge there; if it is an earlier name of this machine, stop OpenKnowledge here if it is still running.`} ${ri(r)}`}function ai(e,t=process.platform){let{lockPath:n}=e;return e.status===`unverified-owner`?`Cannot verify shutdown: the server lock at ${n} ${Zr(e.pid)}. Check whether process ${e.pid} is an OpenKnowledge server. If it is, stop it and retry. Do not remove the lock file while that process is running.`:e.status===`corrupt`?`Cannot verify shutdown: the server lock at ${n} records a machine ID or host name that is not this machine's, so its server may run on another machine, or on this one from another account, with a different home folder, or under an earlier host name. Stop OpenKnowledge wherever it was started. ${ri(n)}`:`Cannot verify shutdown: the server lock at ${n} ${Qr(e.lock)}. ${ii(e,t)}`}function oi(e){return e.replace(/:\d+$/,``)}function si(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:oi(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:oi(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:oi(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const ci=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function li(e){return a(x(),e)}function ui(){return u(x())}function di(){let e=x();if(e===`stable`)return ci;let t=c(e);return RegExp(`^# >>> ${t} >>>\\n[\\s\\S]*?^# <<< ${t} <<<\\n?`,`m`)}const fi={existsSync:e=>U(e),readFileSync:(e,t)=>G(e,t),lstatSync:e=>Ue(e),readlinkSync:e=>qe(e)};function pi(e,t=fi){let n=li(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function mi(e){let t=e.replace(di(),``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function hi(e,t,n=fi){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const gi=[{hostDir:`.adal`,pruneRoot:`.adal`},{hostDir:`.aider-desk`,pruneRoot:`.aider-desk`},{hostDir:`.astrbot/data`,pruneRoot:`.astrbot`},{hostDir:`.augment`,pruneRoot:`.augment`},{hostDir:`.autohand`,pruneRoot:`.autohand`},{hostDir:`.bob`,pruneRoot:`.bob`},{hostDir:`.codeartsdoer`,pruneRoot:`.codeartsdoer`},{hostDir:`.codebuddy`,pruneRoot:`.codebuddy`},{hostDir:`.codeium/windsurf`,pruneRoot:`.codeium`},{hostDir:`.codemaker`,pruneRoot:`.codemaker`},{hostDir:`.codestudio`,pruneRoot:`.codestudio`},{hostDir:`.commandcode`,pruneRoot:`.commandcode`},{hostDir:`.config/crush`,pruneRoot:`.config/crush`},{hostDir:`.config/devin`,pruneRoot:`.config/devin`},{hostDir:`.config/goose`,pruneRoot:`.config/goose`},{hostDir:`.config/kimchi/harness`,pruneRoot:`.config/kimchi`},{hostDir:`.continue`,pruneRoot:`.continue`},{hostDir:`.factory`,pruneRoot:`.factory`},{hostDir:`.forge`,pruneRoot:`.forge`},{hostDir:`.grok`,pruneRoot:`.grok`},{hostDir:`.iflow`,pruneRoot:`.iflow`},{hostDir:`.inferencesh`,pruneRoot:`.inferencesh`},{hostDir:`.jazz`,pruneRoot:`.jazz`},{hostDir:`.junie`,pruneRoot:`.junie`},{hostDir:`.kilocode`,pruneRoot:`.kilocode`},{hostDir:`.kiro`,pruneRoot:`.kiro`},{hostDir:`.kode`,pruneRoot:`.kode`},{hostDir:`.lingma`,pruneRoot:`.lingma`},{hostDir:`.mcpjam`,pruneRoot:`.mcpjam`},{hostDir:`.moxby`,pruneRoot:`.moxby`},{hostDir:`.mux`,pruneRoot:`.mux`},{hostDir:`.neovate`,pruneRoot:`.neovate`},{hostDir:`.ona`,pruneRoot:`.ona`},{hostDir:`.openhands`,pruneRoot:`.openhands`},{hostDir:`.pochi`,pruneRoot:`.pochi`},{hostDir:`.qoder`,pruneRoot:`.qoder`},{hostDir:`.qoder-cn`,pruneRoot:`.qoder-cn`},{hostDir:`.qwen`,pruneRoot:`.qwen`},{hostDir:`.reasonix`,pruneRoot:`.reasonix`},{hostDir:`.roo`,pruneRoot:`.roo`},{hostDir:`.rovodev`,pruneRoot:`.rovodev`},{hostDir:`.snowflake/cortex`,pruneRoot:`.snowflake`},{hostDir:`.tabnine/agent`,pruneRoot:`.tabnine`},{hostDir:`.terramind`,pruneRoot:`.terramind`},{hostDir:`.tinycloud`,pruneRoot:`.tinycloud`},{hostDir:`.trae`,pruneRoot:`.trae`},{hostDir:`.trae-cn`,pruneRoot:`.trae-cn`},{hostDir:`.vibe`,pruneRoot:`.vibe`},{hostDir:`.zcode`,pruneRoot:`.zcode`},{hostDir:`.zencoder`,pruneRoot:`.zencoder`}],_i=[...j.map(e=>me[e]),`open-knowledge`];function vi(e){if(!Le(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=V(e);if(t===H||z(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function yi(e,t){let n=Re(e,t);if(n.startsWith(`..`)||Le(n))return!1;let r=e;for(let e of n.split(H)){r=B(r,e);try{if(!Ue(r).isDirectory())return!1}catch{return!1}}return!0}function bi(e,t){try{return K(e).every(n=>t.has(B(e,n)))}catch{return!1}}function xi(e){let t=vi(e),n=[],r=[],i=new Set;for(let e of gi){let a=B(t,e.hostDir,`skills`);if(!yi(t,a))continue;let o=_i.map(e=>B(a,e)).filter(e=>U(e));n.push(...o);for(let e of o)i.add(e);let s=B(t,e.pruneRoot),c=a;for(;bi(c,i)&&(r.push(c),i.add(c),c!==s);){let e=z(c);if(e===c||e===t||!e.startsWith(t+H))break;c=e}}return{skillDirs:n,emptyDirs:r}}function Si(e){try{if(!Ue(e).isDirectory())return!1;let t=K(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function Ci(e){let t=new Set,n=new Set;for(let r of gi){let i=B(e,r.hostDir,`skills`);for(let e of _i)t.add(B(i,e));let a=B(e,r.pruneRoot),o=i;for(;n.add(o),o!==a;){let t=z(o);if(t===o||t===e||!t.startsWith(e+H))break;o=t}}return{skillDirs:t,emptyDirs:n}}function wi(e,t){let n=vi(e),r=Ci(n),i=[...t.skillDirs.filter(e=>!r.skillDirs.has(e)),...t.emptyDirs.filter(e=>!r.emptyDirs.has(e))];if(i.length>0)throw Error(`refusing skill cleanup — ${i.length} path(s) outside the known legacy set: ${i.join(`, `)}`);let a=[];for(let e of t.skillDirs)if(yi(n,e)&&Si(e))try{Ye(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(yi(n,e))try{Xe(e),a.push(e)}catch{}return a}function Ti(e){let t=vi(e),n=[];for(let e of j){let r=me[e];n.push({path:B(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let a of i)n.push({path:B(t,a.skillsRoot,r),bundleId:e,scope:`host`,hostDir:a.hostDir})}return n}function Ei(e,t){let n=[];for(let r of Ti(e))if(r.bundleId===t)try{Ye(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function Di(e){if(!e||typeof e!=`object`)return String(e);let t=typeof e.readProcessStart;return`${Ce(e)} readProcessStart=${t}`}function Oi(e,t={}){if(!Number.isSafeInteger(e)||e<=0||e>4294967295)return null;let n=t.arch??process.arch,r=(e,n,r)=>{Te(n,r),t.onNativeFailure?.({kind:e,reason:we(n,r)})};try{let i=!1,a=Se(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`:Di(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`,Ce(o)),null)}catch(e){return r(`query-failed`,`readProcessStart failed`,e),null}}function ki(e,t={}){return he(e,{platform:t.platform,readNative:e=>Oi(e,{onNativeFailure:t.onNativeFailure})})}function Ai(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 ${g(`logs`)}. `:``)}function ji(e){let t=new Set;return se(n=>{let r=[],i=Oi(n,{onNativeFailure:e=>{r.push(e)}});for(let i of new Set(r.map(e=>e.kind)))t.has(i)||(t.add(i),(e??Oe())?.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 Mi(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Ni(e,t=Date.now()){if(e===null)return`—`;let n=pt(e,t);return n===`unknown`?`—`:n}function Pi(e){let t=z(e);return R(e)===`local`&&R(t)===`.ok`?z(t):R(e)===`.ok`?t:null}function Fi(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:Pi(e),server:{port:null,status:t.status,pid:t.pid,startedAt:null,usage:null},ui:null,hostname:null,lockPath:t.lockPath,binary:null,command:null,isDesktop:!1};let i=t.lock,a=t.status===`alive`&&re(i)?{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r}:null;return{directory:i.worktreeRoot,server:{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r},ui:a,hostname:i.hostname,lockPath:t.lockPath,binary:n==null?null:ge(n),command:n,isDesktop:Mi(n)}}function Ii(e){let t=e.server.status;switch(t){case`unverified-owner`:return`unverified`;case`alive`:return e.isDesktop?`desktop`:`running`;case`foreign-host`:return e.isDesktop?`desktop`:`foreign`;case`dead-pid`:case`reused-pid`:return`stale`;default:return t}}const Li=new Set([`running`,`desktop`,`foreign`,`unverified`]);function Ri(e){switch(e){case`running`:return X.default.green(e);case`desktop`:return X.default.blue(e);case`foreign`:return X.default.cyan(e);case`unverified`:case`stale`:return X.default.yellow(e)}}function zi(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Bi(e){return`${zi(e.server.usage)} | ${zi(e.ui?.usage??null)}`}function Vi(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function Hi(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,Vi(e),Bi(e),Ii(e),String(e.server.pid),Ni(e.server.startedAt),e.binary??`—`]),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),s=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Ri(Ii(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),c=X.default.dim(`To stop a server: ${o()} stop <port|pid|directory|all>`);return[a,...s,``,c].join(`
16
+ `)}async function Ui(e={}){let t=e.discover??_e,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??k,a=e.resolveUsage??le,o=await t(),s=[];for(let e of o){let t=n(e),r=Fi(e,t,t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`||t.status===`reused-pid`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`||t.status===`reused-pid`?null:a(t.lock.pid));r!=null&&s.push(r)}if(e.json){let e=s.map(e=>({...e,displayStatus:Ii(e)}));r(JSON.stringify(e,null,2));return}r(Hi(e.all?s:s.filter(e=>Li.has(Ii(e)))))}function Wi(){return new De(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale entries`).option(`--all`,`Include stale entries (foreign and unverified entries already show)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await Ui({all:t.all===!0||e===`all`,json:t.json===!0})})}async function Gi(e,t=Oe()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=w(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 Ki(e,t={}){return $i(e,t.isAlive??L)?{targets:[{name:`server`,pid:e.lock.pid,port:e.lock.port}],lock:e.lock}:{targets:[]}}function qi(e){try{return x()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function Ji(e){let t=e.inspect??(()=>$(e.lockDir,`server`)),r=e.kill??((e,t)=>process.kill(e,t)),i=e.log??(e=>console.log(e)),a=e.error??(e=>console.error(e)),s=e.probeClients??Gi,c=e.logger??Oe(),l=e.platform??process.platform,u=t(),d=Ki(u,{isAlive:e.isAlive}),{lock:f}=d,p=[],m=[],h=(t,n)=>{c?.warn({lockDir:e.lockDir,lockPath:n.lockPath,lockPid:n.pid,platform:l,cause:n.cause,...`nativeFailures`in n&&n.nativeFailures.length>0?{nativeFailures:n.nativeFailures}:{}},`stop declined: lock holder identity unverified`),m.push({target:t,error:Zi(n,c!==void 0),unverified:n})},te=()=>{if(p.length>0){let e=p.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);i(`Stopped: ${e}`)}if(c?.info({lockDir:e.lockDir,signalled:p.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:m.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),m.length>0){let e=m.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `);a(`Failed to stop: ${e}`)}return{stopped:p,failed:m,hadTargets:!0}};if(u.status===`unverified-owner`){let{pid:e,lockPath:t}=u;return h({name:`server`,pid:e},{cause:`unverified-owner`,pid:e,lockPath:t}),te()}if(f===void 0)return i(`No running open-knowledge processes.`),c?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};let g=u.status===`alive`||u.status===`foreign-host`?u.lock.channel:void 0;if(e.force!==!0&&typeof g==`string`&&g.length>0){let t=e.selfChannel??qi(c);if(t!==void 0&&g!==t)return a(`Not stopping: the server at ${e.lockDir} belongs to ${ee(g)}. `+(g===`dev`?`Stop it from that dev build, or run \`${n} 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.`)),c?.warn({lockDir:e.lockDir,holderChannel:g,selfChannel:t,pids:d.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:g}}}if(e.force!==!0){let t=await s(e.lockDir,c);if(t!==null&&t>0)return a(`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.`),c?.warn({lockDir:e.lockDir,clients:t,pids:d.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}for(let t of d.targets){let n=[],s=(e.readProcessStart??ki)(t.pid,{platform:l,onNativeFailure:e=>{n.push(e)}}),c=P(f,{isAlive:e.isAlive??L,readProcessStart:()=>s,refuseHolderStartedAfterLock:e.refuseHolderStartedAfterLock});switch(c.verdict){case`writer`:try{r(t.pid,`SIGTERM`),p.push(t)}catch(e){m.push({target:t,error:e instanceof Error?e.message:String(e)})}break;case`gone`:i(`${t.name} (pid=${t.pid}) had already exited`);break;case`replaced`:a(`Process ${t.pid} is no longer the server that wrote ${u.lockPath}; it was not signalled. Run \`${o()} clean\` to remove the stale lock.`);break;case`unverified`:h(t,Yi(c.cause,{pid:t.pid,lockPath:u.lockPath,lock:f,platform:l,nativeFailures:n}));break;default:return c}}return te()}function Yi(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 Xi=`it was not signalled, and --force does not override this check.`;function Zi(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} ${Qr(t)}, so process ${n}, which is running on this machine, cannot be confirmed as the server that wrote it; ${Xi} ${ti(t,e.platform)}`:`The server lock at ${r} ${Qr(t)}, and the start of process ${n}, which is running on this machine, does not confirm it as the server that wrote the lock; ${Xi} If ${ke(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} ${Zr(n)}, so it cannot be confirmed as the server that wrote the lock; ${Xi} 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=Qi(e,Xi,`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 \`${o()} stop\` can confirm it.`:n}}}function Qi(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} `+Ai({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 $i(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function ea(e,t=L){let n=await _e(),r=null;for(let i of n){let n=$(i,`server`);if($i(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}function ta(e){(e.failed.length>0||e.declined!==void 0)&&(process.exitCode=1)}async function na(e,t){let n=await Ji({lockDir:e,force:t});return ta(n),n}function ra(e,t,n={}){return t===0?`Nothing was running for ${e}, and no other open-knowledge servers are running.`:`Nothing was running for ${e}. ${t} other open-knowledge server${t===1?` is`:`s are`} running${n.listingFollows===!0?``:` — run \`${o()} ps\` to list them`}.`}async function ia(e){let t=await _e(),n=0;for(let r of t)r!==e&&$i($(r,`server`),L)&&n++;return n}function aa(e){return new De(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the enclosing project — run it from anywhere inside the project. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).option(`--force`,`Stop even when the server belongs to another OpenKnowledge app (Stable, Beta or a dev build run from source) or editor windows or agents are still connected to it`).action(async(t,n)=>{let r=n.force===!0,i=t.length===0?void 0:t.join(` `);if(i===void 0){e();let t=I(process.cwd()),n=[],i=await Ji({lockDir:t,force:r,log:e=>n.push(e)});if(i.hadTargets){for(let e of n)console.log(e);ta(i)}else{let e=await ia(t);console.log(ra(process.cwd(),e,{listingFollows:e>0})),e>0&&await Ui({})}return}if(i===`all`){let e=await _e();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e)$i($(n,`server`),L)&&(await na(n,r),t++);t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(i)){let e=Number.parseInt(i,10),t=await ea(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await na(t,r);return}let a=V(vt(),i),o=I(a),s=[],c=await Ji({lockDir:o,force:r,log:e=>s.push(e)});if(ta(c),c.hadTargets)for(let e of s)console.log(e);else console.log(ra(a,await ia(o)))})}export{It as A,Xr as C,On as D,kn as E,Ct as F,wt as I,vt as L,yt as M,xt as N,Cn as O,bt as P,_t as R,$ as S,qr as T,mi as _,Wi as a,Qr as b,wi as c,Ti as d,ci as f,pi as g,ui as h,aa as i,Et as j,Dn as k,xi as l,li as m,Gi as n,ki as o,hi as p,Ji as r,ji as s,Qi as t,Ei as u,si as v,Kr as w,ai as x,ii as y,ht as z};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-CSFPyGy0.mjs";import"./src--qjAZ5fK.mjs";import"./init-UZr9GVxw.mjs";import"./registry-probes-DA_47MnL.mjs";import"./start-0pD-b-lJ.mjs";import{n as e}from"./loader-Dbq_EWV8.mjs";import"./preview-BRJmRFNY.mjs";import"./repair-mcp-configs-Cz7RUmn9.mjs";export{e as loadConfig};