@inkeep/open-knowledge 0.88.9-beta.4 → 0.88.9-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 (85) hide show
  1. package/dist/{cli-CApr5vJh.mjs → cli-BWG-Aq4r.mjs} +8 -8
  2. package/dist/cli.mjs +1 -1
  3. package/dist/constants-DqD-WwtH.mjs +1 -0
  4. package/dist/{dist-C5NH8F7J.mjs → dist-By4Q8HCV.mjs} +488 -488
  5. package/dist/{dist-eiP2xn_A.mjs → dist-Ttulen40.mjs} +1 -1
  6. package/dist/index.mjs +157 -157
  7. package/dist/init-CMXr3PqV.mjs +1 -0
  8. package/dist/{init-_MYjUgbc.mjs → init-DgagwO3Q.mjs} +2 -2
  9. package/dist/{launch-json-removal-Dmz2x-7W.mjs → launch-json-removal-RTdY_4MQ.mjs} +1 -1
  10. package/dist/loader-B_W8tqBx.mjs +1 -0
  11. package/dist/{loader-D0z63VhQ.mjs → loader-bqg6WDaz.mjs} +1 -1
  12. package/dist/{open-browser-Bdh6sD0e.mjs → open-browser-kL892VYi.mjs} +1 -1
  13. package/dist/{preview-DlbLi7gD.mjs → preview-CpwcPVCo.mjs} +1 -1
  14. package/dist/preview-uakaw7R6.mjs +1 -0
  15. package/dist/public/assets/{AccountSection-WnZI9Y4X.js → AccountSection-OC5q0omm.js} +1 -1
  16. package/dist/public/assets/{ActivityModeContent-BW34hghR.js → ActivityModeContent-BrTDTihv.js} +1 -1
  17. package/dist/public/assets/{AddPropertiesButton-Yxk08VnZ.js → AddPropertiesButton-DzmO7lPO.js} +1 -1
  18. package/dist/public/assets/{AgentDiffPane-BtR2fIQk.js → AgentDiffPane-D3NHWroZ.js} +1 -1
  19. package/dist/public/assets/{AttachmentsSection-DheSSdwi.js → AttachmentsSection-BRw5iHsN.js} +1 -1
  20. package/dist/public/assets/{CodeMirrorPropInput-CTxnGgD1.js → CodeMirrorPropInput-_xlIZfnP.js} +1 -1
  21. package/dist/public/assets/{ContentRulesSection-m1yJ_5W5.js → ContentRulesSection-C3zJL3XT.js} +1 -1
  22. package/dist/public/assets/{DocumentContext-tPl3222n.js → DocumentContext-DudOKaBE.js} +1 -1
  23. package/dist/public/assets/{EditorModeToggle-CgAxXc9n.js → EditorModeToggle-C6XVQvNH.js} +1 -1
  24. package/dist/public/assets/{ExcalidrawDocEditor-BDPLX-a4.js → ExcalidrawDocEditor-CNbYH26b.js} +1 -1
  25. package/dist/public/assets/FeedbackForm-JqmULtp1.js +1 -0
  26. package/dist/public/assets/{ImportSkillDialog-DeVO4S8O.js → ImportSkillDialog-BvMF42t1.js} +1 -1
  27. package/dist/public/assets/{LinkPreviewsSection-bEPxLhlm.js → LinkPreviewsSection-CfBE3a3F.js} +1 -1
  28. package/dist/public/assets/{LintConfigEditor-D65vodB4.js → LintConfigEditor-C5OeqI_-.js} +1 -1
  29. package/dist/public/assets/{LintingSection-BOCmIlCP.js → LintingSection-CA0Fab7L.js} +1 -1
  30. package/dist/public/assets/{ManagedArtifactProperties-BHfiDMNo.js → ManagedArtifactProperties-9GJ7LIgQ.js} +1 -1
  31. package/dist/public/assets/ManagedArtifactProperties-CiPHTfJ5.js +1 -0
  32. package/dist/public/assets/{MermaidDocEditor-DLd-f9Xs.js → MermaidDocEditor-BkAp4SwO.js} +1 -1
  33. package/dist/public/assets/{NetworkAccessSection-BAjeEdGd.js → NetworkAccessSection-5853q-6H.js} +1 -1
  34. package/dist/public/assets/{PropertyDisplayRow-B2Ye_A12.js → PropertyDisplayRow-BfPIxbJe.js} +1 -1
  35. package/dist/public/assets/{PublishToGitHubDialog-Bx6_BCDO.js → PublishToGitHubDialog-D-DLQtYQ.js} +1 -1
  36. package/dist/public/assets/{SchemaConfigEditor-DV1Y294T.js → SchemaConfigEditor-CCWn7X-u.js} +1 -1
  37. package/dist/public/assets/{SearchSection-oHyCW1cw.js → SearchSection-2KCDB2VA.js} +1 -1
  38. package/dist/public/assets/{SessionsHost-Cr8QROmn.js → SessionsHost-CRPnzYN1.js} +2 -2
  39. package/dist/public/assets/{SettingsDialogBody-SDayK0GJ.js → SettingsDialogBody-1yLR-GsZ.js} +2 -2
  40. package/dist/public/assets/{ShareReceiveMissDialog-Dz2l51c8.js → ShareReceiveMissDialog-BXKUoF1i.js} +1 -1
  41. package/dist/public/assets/{SkillToolbarControls-11TOzdmT.js → SkillToolbarControls-B6E5iiKJ.js} +1 -1
  42. package/dist/public/assets/{SourceEditor-D8LleSVP.js → SourceEditor-BLtDTcHX.js} +1 -1
  43. package/dist/public/assets/{SyncSection-D9HwTuQH.js → SyncSection-BsLX6-vW.js} +1 -1
  44. package/dist/public/assets/{SyncStatusBadge-DlXMIfnP.js → SyncStatusBadge-C36jYktv.js} +1 -1
  45. package/dist/public/assets/{TerminalSection-B-1W5J1j.js → TerminalSection-DZKCNM7y.js} +1 -1
  46. package/dist/public/assets/{TerminalWindowApp-CHt3oCGP.js → TerminalWindowApp-CmU1Cb8o.js} +1 -1
  47. package/dist/public/assets/{TextDocEditor-DTtAO6MS.js → TextDocEditor-BabRgTt7.js} +1 -1
  48. package/dist/public/assets/{ThreadView-DjPpy_DW.js → ThreadView-C_zy2m7k.js} +1 -1
  49. package/dist/public/assets/{TimelineDiffPane-Cu-wZdGq.js → TimelineDiffPane-DYpDj0gb.js} +1 -1
  50. package/dist/public/assets/{client-version-CsPDy_mS.js → client-version-C1mluhO6.js} +1 -1
  51. package/dist/public/assets/{comment-chips-0VDCgiLf.js → comment-chips-Bg_fHZit.js} +1 -1
  52. package/dist/public/assets/{config-provider-PZhtKwZ4.js → config-provider-rlX-hNO5.js} +1 -1
  53. package/dist/public/assets/{doc-undo-manager-Cjle_cou.js → doc-undo-manager-BeKYlR4y.js} +1 -1
  54. package/dist/public/assets/{index-BtXMY-lm.js → index-CcicSOZg.js} +7 -7
  55. package/dist/public/assets/{lint-plugins-BgXd5eb3.js → lint-plugins-C777a3Eb.js} +1 -1
  56. package/dist/public/assets/{pending-receive-nav-store-yu2l0rmr.js → pending-receive-nav-store-CV2evy8J.js} +1 -1
  57. package/dist/public/assets/{preferred-session-events-AxKg0Sw4.js → preferred-session-events-_cY_seNN.js} +1 -1
  58. package/dist/public/assets/{progress-COboqCdt.js → progress-Bq_b5Dwi.js} +1 -1
  59. package/dist/public/assets/{selection-context-CqPsJN1K.js → selection-context-DsN_o-oO.js} +1 -1
  60. package/dist/public/assets/{src-bjWQtRl1.js → src-MfTCWnJS.js} +1 -1
  61. package/dist/public/assets/{telemetry-impl-CnTOH7Vq.js → telemetry-impl-DoFXV7zT.js} +1 -1
  62. package/dist/public/assets/{telemetry-startup-DEDQn7NX.js → telemetry-startup-Dh6dlltT.js} +1 -1
  63. package/dist/public/assets/{typing-burst-detector-CKGqqUho.js → typing-burst-detector-CQpkMJPV.js} +1 -1
  64. package/dist/public/assets/{use-activity-panel-CjQtwblB.js → use-activity-panel-DK_CY04P.js} +1 -1
  65. package/dist/public/assets/{use-open-skill-wBK1EQdE.js → use-open-skill-B0yLjGNV.js} +1 -1
  66. package/dist/public/assets/{use-terminal-enabled-ZJDRhsBW.js → use-terminal-enabled-x6P_EH4P.js} +1 -1
  67. package/dist/public/assets/{use-timeline-entry-diff-CliAvkzA.js → use-timeline-entry-diff-BAgwVMRs.js} +1 -1
  68. package/dist/public/index.html +19 -19
  69. package/dist/{registry-probes-D0Wp5e7Z.mjs → registry-probes-B2fn4XJx.mjs} +2 -2
  70. package/dist/{removal-file-path-yLPrekRN.mjs → removal-file-path-HAS5JVGt.mjs} +1 -1
  71. package/dist/{repair-launch-json-EuA85m8g.mjs → repair-launch-json-Crbpi7Jj.mjs} +1 -1
  72. package/dist/{repair-mcp-configs-C7yBPBvC.mjs → repair-mcp-configs-CV-7zYuV.mjs} +1 -1
  73. package/dist/{src-xBlfQBhu.mjs → src-B_q1_C1R.mjs} +1 -1
  74. package/dist/src-BjiiSghS.mjs +1 -0
  75. package/dist/{start-PPqSRW1B.mjs → start-BjstUFs5.mjs} +3 -3
  76. package/dist/start-MRWYWYqt.mjs +1 -0
  77. package/package.json +4 -4
  78. package/dist/constants-Ca_9Ar85.mjs +0 -1
  79. package/dist/init-D8_giXgq.mjs +0 -1
  80. package/dist/loader-CIxtIlMB.mjs +0 -1
  81. package/dist/preview-h0nWv2-p.mjs +0 -1
  82. package/dist/public/assets/FeedbackForm-DqkKWe5H.js +0 -1
  83. package/dist/public/assets/ManagedArtifactProperties-13jOCHuP.js +0 -1
  84. package/dist/src-BA_wxupY.mjs +0 -1
  85. package/dist/start-C1as3B3R.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{a as t,i as n,r,t as i}from"./git-credential-operation-9lLcCrJB.mjs";import{C as a,D as o,L as s,N as c,O as l,P as u,_ as d,a as f,b as p,c as m,d as h,h as g,k as _,o as v,v as y,x as b,y as x}from"./constants-ok-dir-DZ25OS9-.mjs";import{$c as S,Bd as C,Bo as ee,Dd as w,Do as te,Ed as ne,Es as re,F as ie,Fd as ae,Id as T,Jd as oe,Jo as se,Ko as ce,Ml as le,N as ue,Nc as de,Nd as fe,No as pe,Od as E,Pd as me,Ra as he,Sc as ge,Sd as _e,So as ve,Vr as ye,Wd as be,X as xe,Ya as Se,_c as Ce,af as we,au as Te,da as Ee,dc as De,fc as Oe,gl as ke,hu as Ae,io as je,jo as Me,lf as Ne,m as Pe,mf as Fe,nf as Ie,no as Le,oa as Re,p as ze,q as Be,qc as D,qo as Ve,r as He,sl as Ue,uc as We,uf as Ge,vf as Ke,yl as qe}from"./md-manager-BGnqyqi1-B5Gyjk_N.mjs";import{Ut as Je}from"./memoizer-D67BaNBw.mjs";import{$o as Ye,B as Xe,Bi as Ze,Br as Qe,Ci as $e,Dn as et,Ds as tt,Dt as nt,Ea as rt,En as it,Et as at,F as ot,Fa as st,Fr as ct,Fs as lt,Ha as ut,Hi as dt,Ia as O,J as ft,Ji as pt,Jo as mt,Jt as ht,Kn as gt,Kt as _t,La as vt,Ln as yt,Mn as bt,Mr as xt,Na as St,Nn as Ct,No as wt,Nt as Tt,O as Et,Oa as Dt,Os as Ot,Ot as kt,Pa as At,Ps as jt,Pt as Mt,Q as Nt,Qo as Pt,R as Ft,Ri as It,Sa as Lt,T as Rt,Tn as zt,Ts as Bt,Ut as Vt,Vi as Ht,Vo as k,Vs as Ut,W as Wt,Wi as Gt,Wo as Kt,Wt as qt,Xi as Jt,Xo as Yt,Yi as Xt,Yr as Zt,Zo as Qt,_r as $t,aa as en,an as tn,ar as nn,bi as rn,br as an,bs as on,ci as sn,cs as cn,d as ln,ds as un,dt as dn,ei as fn,eo as pn,es as mn,fs as hn,ga as gn,gt as _n,ha as vn,hn as yn,ht as bn,ia as xn,io as Sn,jn as Cn,js as wn,ka as Tn,ks as En,kt as Dn,ls as On,m as kn,ms as An,nn as jn,nr as Mn,oa as Nn,or as Pn,pa as Fn,ps as In,qr as Ln,qt as Rn,sr as zn,to as Bn,ts as Vn,ua as Hn,us as A,wr as Un,x as Wn,xi as Gn,xt as Kn,yn as qn,yt as Jn,z as Yn,zn as Xn,zr as Zn}from"./dist-C5NH8F7J.mjs";import{A as Qn,C as $n,E as er,F as tr,I as nr,L as rr,M as ir,N as ar,O as or,P as sr,R as cr,S as lr,T as ur,_ as dr,a as fr,b as pr,c as mr,d as hr,g as gr,h as _r,i as vr,j as yr,k as br,l as xr,n as Sr,o as Cr,p as wr,r as Tr,s as Er,t as Dr,u as Or,v as kr,w as Ar,x as jr,y as Mr,z as Nr}from"./src-xBlfQBhu.mjs";import{n as Pr,r as Fr,t as Ir}from"./dist-bundle-T0gq9zHH.mjs";import{a as Lr,n as Rr,p as zr,s as Br,t as Vr,y as Hr}from"./fs-find-project-root-BYV07wjn.mjs";import{Ct as Ur,D as Wr,G as Gr,I as Kr,J as qr,K as Jr,L as Yr,M as Xr,N as Zr,O as Qr,Q as $r,St as ei,U as ti,V as ni,W as ri,Y as ii,Z as ai,_t as oi,bt as si,d as ci,k as li,q as ui,vt as di,wt as j,xt as fi,yt as pi}from"./init-_MYjUgbc.mjs";import{a as mi,n as hi,o as gi,r as _i,s as vi,t as yi}from"./token-store-Bmb3_0hU.mjs";import{c as bi,i as M,n as N,o as P,r as F,s as I,t as L}from"./colors-r_owlCuY.mjs";import{t as xi}from"./git-credential-get-BOA4DNNp.mjs";import{E as Si,S as Ci,y as wi}from"./start-PPqSRW1B.mjs";import{_ as Ti,d as Ei,f as Di,h as Oi,m as ki,o as Ai,p as ji,v as Mi,y as Ni}from"./registry-probes-D0Wp5e7Z.mjs";import{n as Pi,t as Fi}from"./constants-Ca_9Ar85.mjs";import{n as Ii,t as Li}from"./loader-D0z63VhQ.mjs";import{t as Ri}from"./removal-file-path-yLPrekRN.mjs";import{t as zi}from"./launch-json-removal-Dmz2x-7W.mjs";import{fileURLToPath as Bi}from"node:url";import{basename as Vi,dirname as R,isAbsolute as Hi,join as z,posix as Ui,relative as B,resolve as V,sep as Wi}from"node:path";import Gi from"node:process";import{accessSync as Ki,appendFileSync as qi,closeSync as Ji,constants as Yi,existsSync as H,lstatSync as Xi,mkdirSync as U,mkdtempSync as Zi,readFileSync as W,readdirSync as Qi,realpathSync as $i,renameSync as ea,rmSync as G,statSync as K,unlinkSync as ta,writeFileSync as na}from"node:fs";import{homedir as ra,platform as ia,tmpdir as aa}from"node:os";import{realpath as oa,rm as sa}from"node:fs/promises";import{randomUUID as ca}from"node:crypto";import{execFile as la,execFileSync as ua,execSync as da,spawn as fa,spawnSync as pa}from"node:child_process";import{promisify as ma}from"node:util";import{setTimeout as ha}from"node:timers/promises";import{createInterface as ga}from"node:readline/promises";const _a={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var va;va||={};function ya(e){return oe(_e,e)}function ba(e){return e.created.length>0||e.packSkills?.some(e=>e.pending)===!0||e.requiredPlugins?.some(e=>e.pending)===!0}async function xa(e){let{projectDir:t,contentDir:n,baseConfig:r,targetPath:i,fix:a=!1}=e,o=e.resolvedScope===void 0?rt(i,n):{ok:!0,scope:e.resolvedScope};if(!o.ok)throw Error(o.title);let s=o.scope,c=[],l=yt({projectDir:t,contentDir:n}),u=new Set,d=e=>{u.has(e)||(u.add(e),c.push(e))},f=et(t,r,d),p=te(f,{mode:`lint`}),m=[],h=e=>{m.push(e)},g=new Map,_=e=>{let t=R(e),r=g.get(t);if(r)return r;let i=vt(n,e,d),a=it(f,i);return g.set(t,a),a},v=[],y=!1,b=B(n,s.path),x=b.split(Wi).some(e=>e.startsWith(`.`)&&e!==`..`);s.kind===`file`?v.push(b):(b===``||x||!l.isDirExcluded(b))&&S(s.path);function S(e){let t;try{t=Qi(e,{withFileTypes:!0})}catch(t){y=!0,c.push(`could not read directory ${B(n,e)||`.`}: ${Ca(t)}`);return}for(let r of t){if(r.name.startsWith(`.`))continue;let t=z(e,r.name),i=B(n,t);if(r.isDirectory()){if(l.isDirExcluded(i))continue;S(t)}else if(r.isFile()){if(!Sa(r.name)||l.isExcluded(i))continue;v.push(i)}}}v.sort(),v.length===0&&!y&&c.push(Le);let C=[],w=0,ne=0,re=0;for(let e of v){let t=z(n,e),r;try{r=W(t,`utf-8`)}catch(t){c.push(`could not read ${e}: ${Ca(t)}`);continue}let i=_(e),o=!1;if(a&&i.enabled){let n=Me(r,i,e,h);if(n!==r){let i=Lr(t);try{na(i,n,`utf-8`),ea(i,t),r=n,o=!0,re++}catch(t){try{ta(i)}catch{}c.push(`could not write fix to ${e}: ${Ca(t)}`)}}}let s=await ee(r,i,e,h);for(let e of s)e.severity===`error`?w++:ne++;C.push({file:e,diagnostics:s,fixed:o})}return c.push(...ce(m)),{contentDir:n,files:C,warnings:c,fileCount:v.length,errorCount:w,warningCount:ne,fixedCount:re,ran:p}}function Sa(e){let t=e.toLowerCase();return Te.some(e=>t.endsWith(e))}function Ca(e){return e instanceof Error?e.message:String(e)}function wa(e){return new j(`lint`).description(`Lint markdown content (headless) — whole project, a folder, or a single file`).argument(`[path]`,`Folder or file to lint, relative to where you run the command`).option(`--json`,`Emit structured JSON instead of formatted text`).option(`--fix`,`Auto-fix fixable issues in place (markdownlint rules only)`).option(`--errors-only`,`Exit non-zero only on error-severity problems (findings are warning-severity unless your .markdownlint.* assigns a rule "error")`).action(async(t,n)=>{let r=e(),i=process.cwd(),a=Tn(r,i),o=t===void 0?void 0:Ta(t,rr()),s=rt(o,a);if(!s.ok){let e={type:`urn:ok:error:not-found`,title:t===void 0||s.path===a?s.title:jn(t),status:404,instance:`urn:uuid:${ca()}`};n.json===!0?process.stdout.write(`${JSON.stringify(e,null,2)}\n`):process.stderr.write(`${e.title}\n`),process.exitCode=1;return}let c=r.contentRules,l=await xa({projectDir:i,contentDir:a,baseConfig:c?Ve(c):je,targetPath:o,resolvedScope:s.scope,fix:n.fix===!0});n.json===!0?process.stdout.write(`${JSON.stringify(l,null,2)}\n`):process.stdout.write(`${Oa(l)}\n`),(n.errorsOnly===!0?l.errorCount>0:Ea(l))&&(process.exitCode=1)})}function Ta(e,t){return V(t,e)}function Ea(e){return e.errorCount>0||e.warningCount>0}function Da(e){let t=[L(e.file)+(e.fixed?N(` (fixed)`):``)];for(let n of e.diagnostics){let e=N(`${n.range.start.line+1}:${n.range.start.character+1}`.padEnd(7)),r=n.severity===`error`?F(`error `):I(`warning`);t.push(` ${e} ${r} ${n.message} ${N(`${n.source}/${n.code}`)}`)}return t.push(``),t}function Oa(e){let t=[];for(let n of e.files)n.diagnostics.length>0&&t.push(...Da(n));let n=e.errorCount+e.warningCount;if(e.fileCount===0)t.push(N(`No documents were checked.`));else if(n===0)t.push(P(`✓ No problems in ${e.fileCount} file${e.fileCount===1?``:`s`}.`));else{let r=[`${n} problem${n===1?``:`s`}`];r.push(`${e.errorCount} error${e.errorCount===1?``:`s`}`),r.push(`${e.warningCount} warning${e.warningCount===1?``:`s`}`),t.push(`${F(r[0]??``)} (${r[1]}, ${r[2]}) across ${e.fileCount} file${e.fileCount===1?``:`s`}.`)}e.fixedCount>0&&t.push(N(`Fixed ${e.fixedCount} file${e.fixedCount===1?``:`s`}.`));let r=se(e.ran,e.fileCount);if(t.push(...r.map(e=>N(e))),e.warnings.length>0){t.push(``);for(let n of e.warnings)t.push(pe(n)?N(n):I(`! ${n}`))}return t.join(`
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{a as t,i as n,r,t as i}from"./git-credential-operation-9lLcCrJB.mjs";import{C as a,D as o,L as s,N as c,O as l,P as u,_ as d,a as f,b as p,c as m,d as h,h as g,k as _,o as v,v as y,x as b,y as x}from"./constants-ok-dir-DZ25OS9-.mjs";import{$c as S,Bd as C,Bo as ee,Dd as w,Do as te,Ed as ne,Es as re,F as ie,Fd as ae,Id as T,Jd as oe,Jo as se,Ko as ce,Ml as le,N as ue,Nc as de,Nd as fe,No as pe,Od as E,Pd as me,Ra as he,Sc as ge,Sd as _e,So as ve,Vr as ye,Wd as be,X as xe,Ya as Se,_c as Ce,af as we,au as Te,da as Ee,dc as De,fc as Oe,gl as ke,hu as Ae,io as je,jo as Me,lf as Ne,m as Pe,mf as Fe,nf as Ie,no as Le,oa as Re,p as ze,q as Be,qc as D,qo as Ve,r as He,sl as Ue,uc as We,uf as Ge,vf as Ke,yl as qe}from"./md-manager-BGnqyqi1-B5Gyjk_N.mjs";import{Ut as Je}from"./memoizer-D67BaNBw.mjs";import{$o as Ye,B as Xe,Bi as Ze,Br as Qe,Ci as $e,Dn as et,Ds as tt,Dt as nt,Ea as rt,En as it,Et as at,F as ot,Fa as st,Fr as ct,Fs as lt,Ha as ut,Hi as dt,Ia as O,J as ft,Ji as pt,Jo as mt,Jt as ht,Kn as gt,Kt as _t,La as vt,Ln as yt,Mn as bt,Mr as xt,Na as St,Nn as Ct,No as wt,Nt as Tt,O as Et,Oa as Dt,Os as Ot,Ot as kt,Pa as At,Ps as jt,Pt as Mt,Q as Nt,Qo as Pt,R as Ft,Ri as It,Sa as Lt,T as Rt,Tn as zt,Ts as Bt,Ut as Vt,Vi as Ht,Vo as k,Vs as Ut,W as Wt,Wi as Gt,Wo as Kt,Wt as qt,Xi as Jt,Xo as Yt,Yi as Xt,Yr as Zt,Zo as Qt,_r as $t,aa as en,an as tn,ar as nn,bi as rn,br as an,bs as on,ci as sn,cs as cn,d as ln,ds as un,dt as dn,ei as fn,eo as pn,es as mn,fs as hn,ga as gn,gt as _n,ha as vn,hn as yn,ht as bn,ia as xn,io as Sn,jn as Cn,js as wn,ka as Tn,ks as En,kt as Dn,ls as On,m as kn,ms as An,nn as jn,nr as Mn,oa as Nn,or as Pn,pa as Fn,ps as In,qr as Ln,qt as Rn,sr as zn,to as Bn,ts as Vn,ua as Hn,us as A,wr as Un,x as Wn,xi as Gn,xt as Kn,yn as qn,yt as Jn,z as Yn,zn as Xn,zr as Zn}from"./dist-By4Q8HCV.mjs";import{A as Qn,C as $n,E as er,F as tr,I as nr,L as rr,M as ir,N as ar,O as or,P as sr,R as cr,S as lr,T as ur,_ as dr,a as fr,b as pr,c as mr,d as hr,g as gr,h as _r,i as vr,j as yr,k as br,l as xr,n as Sr,o as Cr,p as wr,r as Tr,s as Er,t as Dr,u as Or,v as kr,w as Ar,x as jr,y as Mr,z as Nr}from"./src-B_q1_C1R.mjs";import{n as Pr,r as Fr,t as Ir}from"./dist-bundle-T0gq9zHH.mjs";import{a as Lr,n as Rr,p as zr,s as Br,t as Vr,y as Hr}from"./fs-find-project-root-BYV07wjn.mjs";import{Ct as Ur,D as Wr,G as Gr,I as Kr,J as qr,K as Jr,L as Yr,M as Xr,N as Zr,O as Qr,Q as $r,St as ei,U as ti,V as ni,W as ri,Y as ii,Z as ai,_t as oi,bt as si,d as ci,k as li,q as ui,vt as di,wt as j,xt as fi,yt as pi}from"./init-DgagwO3Q.mjs";import{a as mi,n as hi,o as gi,r as _i,s as vi,t as yi}from"./token-store-Bmb3_0hU.mjs";import{c as bi,i as M,n as N,o as P,r as F,s as I,t as L}from"./colors-r_owlCuY.mjs";import{t as xi}from"./git-credential-get-BOA4DNNp.mjs";import{E as Si,S as Ci,y as wi}from"./start-BjstUFs5.mjs";import{_ as Ti,d as Ei,f as Di,h as Oi,m as ki,o as Ai,p as ji,v as Mi,y as Ni}from"./registry-probes-B2fn4XJx.mjs";import{n as Pi,t as Fi}from"./constants-DqD-WwtH.mjs";import{n as Ii,t as Li}from"./loader-bqg6WDaz.mjs";import{t as Ri}from"./removal-file-path-HAS5JVGt.mjs";import{t as zi}from"./launch-json-removal-RTdY_4MQ.mjs";import{fileURLToPath as Bi}from"node:url";import{basename as Vi,dirname as R,isAbsolute as Hi,join as z,posix as Ui,relative as B,resolve as V,sep as Wi}from"node:path";import Gi from"node:process";import{accessSync as Ki,appendFileSync as qi,closeSync as Ji,constants as Yi,existsSync as H,lstatSync as Xi,mkdirSync as U,mkdtempSync as Zi,readFileSync as W,readdirSync as Qi,realpathSync as $i,renameSync as ea,rmSync as G,statSync as K,unlinkSync as ta,writeFileSync as na}from"node:fs";import{homedir as ra,platform as ia,tmpdir as aa}from"node:os";import{realpath as oa,rm as sa}from"node:fs/promises";import{randomUUID as ca}from"node:crypto";import{execFile as la,execFileSync as ua,execSync as da,spawn as fa,spawnSync as pa}from"node:child_process";import{setTimeout as ma}from"node:timers/promises";import{promisify as ha}from"node:util";import{createInterface as ga}from"node:readline/promises";const _a={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var va;va||={};function ya(e){return oe(_e,e)}function ba(e){return e.created.length>0||e.packSkills?.some(e=>e.pending)===!0||e.requiredPlugins?.some(e=>e.pending)===!0}async function xa(e){let{projectDir:t,contentDir:n,baseConfig:r,targetPath:i,fix:a=!1}=e,o=e.resolvedScope===void 0?rt(i,n):{ok:!0,scope:e.resolvedScope};if(!o.ok)throw Error(o.title);let s=o.scope,c=[],l=yt({projectDir:t,contentDir:n}),u=new Set,d=e=>{u.has(e)||(u.add(e),c.push(e))},f=et(t,r,d),p=te(f,{mode:`lint`}),m=[],h=e=>{m.push(e)},g=new Map,_=e=>{let t=R(e),r=g.get(t);if(r)return r;let i=vt(n,e,d),a=it(f,i);return g.set(t,a),a},v=[],y=!1,b=B(n,s.path),x=b.split(Wi).some(e=>e.startsWith(`.`)&&e!==`..`);s.kind===`file`?v.push(b):(b===``||x||!l.isDirExcluded(b))&&S(s.path);function S(e){let t;try{t=Qi(e,{withFileTypes:!0})}catch(t){y=!0,c.push(`could not read directory ${B(n,e)||`.`}: ${Ca(t)}`);return}for(let r of t){if(r.name.startsWith(`.`))continue;let t=z(e,r.name),i=B(n,t);if(r.isDirectory()){if(l.isDirExcluded(i))continue;S(t)}else if(r.isFile()){if(!Sa(r.name)||l.isExcluded(i))continue;v.push(i)}}}v.sort(),v.length===0&&!y&&c.push(Le);let C=[],w=0,ne=0,re=0;for(let e of v){let t=z(n,e),r;try{r=W(t,`utf-8`)}catch(t){c.push(`could not read ${e}: ${Ca(t)}`);continue}let i=_(e),o=!1;if(a&&i.enabled){let n=Me(r,i,e,h);if(n!==r){let i=Lr(t);try{na(i,n,`utf-8`),ea(i,t),r=n,o=!0,re++}catch(t){try{ta(i)}catch{}c.push(`could not write fix to ${e}: ${Ca(t)}`)}}}let s=await ee(r,i,e,h);for(let e of s)e.severity===`error`?w++:ne++;C.push({file:e,diagnostics:s,fixed:o})}return c.push(...ce(m)),{contentDir:n,files:C,warnings:c,fileCount:v.length,errorCount:w,warningCount:ne,fixedCount:re,ran:p}}function Sa(e){let t=e.toLowerCase();return Te.some(e=>t.endsWith(e))}function Ca(e){return e instanceof Error?e.message:String(e)}function wa(e){return new j(`lint`).description(`Lint markdown content (headless) — whole project, a folder, or a single file`).argument(`[path]`,`Folder or file to lint, relative to where you run the command`).option(`--json`,`Emit structured JSON instead of formatted text`).option(`--fix`,`Auto-fix fixable issues in place (markdownlint rules only)`).option(`--errors-only`,`Exit non-zero only on error-severity problems (findings are warning-severity unless your .markdownlint.* assigns a rule "error")`).action(async(t,n)=>{let r=e(),i=process.cwd(),a=Tn(r,i),o=t===void 0?void 0:Ta(t,rr()),s=rt(o,a);if(!s.ok){let e={type:`urn:ok:error:not-found`,title:t===void 0||s.path===a?s.title:jn(t),status:404,instance:`urn:uuid:${ca()}`};n.json===!0?process.stdout.write(`${JSON.stringify(e,null,2)}\n`):process.stderr.write(`${e.title}\n`),process.exitCode=1;return}let c=r.contentRules,l=await xa({projectDir:i,contentDir:a,baseConfig:c?Ve(c):je,targetPath:o,resolvedScope:s.scope,fix:n.fix===!0});n.json===!0?process.stdout.write(`${JSON.stringify(l,null,2)}\n`):process.stdout.write(`${Oa(l)}\n`),(n.errorsOnly===!0?l.errorCount>0:Ea(l))&&(process.exitCode=1)})}function Ta(e,t){return V(t,e)}function Ea(e){return e.errorCount>0||e.warningCount>0}function Da(e){let t=[L(e.file)+(e.fixed?N(` (fixed)`):``)];for(let n of e.diagnostics){let e=N(`${n.range.start.line+1}:${n.range.start.character+1}`.padEnd(7)),r=n.severity===`error`?F(`error `):I(`warning`);t.push(` ${e} ${r} ${n.message} ${N(`${n.source}/${n.code}`)}`)}return t.push(``),t}function Oa(e){let t=[];for(let n of e.files)n.diagnostics.length>0&&t.push(...Da(n));let n=e.errorCount+e.warningCount;if(e.fileCount===0)t.push(N(`No documents were checked.`));else if(n===0)t.push(P(`✓ No problems in ${e.fileCount} file${e.fileCount===1?``:`s`}.`));else{let r=[`${n} problem${n===1?``:`s`}`];r.push(`${e.errorCount} error${e.errorCount===1?``:`s`}`),r.push(`${e.warningCount} warning${e.warningCount===1?``:`s`}`),t.push(`${F(r[0]??``)} (${r[1]}, ${r[2]}) across ${e.fileCount} file${e.fileCount===1?``:`s`}.`)}e.fixedCount>0&&t.push(N(`Fixed ${e.fixedCount} file${e.fixedCount===1?``:`s`}.`));let r=se(e.ran,e.fileCount);if(t.push(...r.map(e=>N(e))),e.warnings.length>0){t.push(``);for(let n of e.warnings)t.push(pe(n)?N(n):I(`! ${n}`))}return t.join(`
2
2
  `)}const ka={out:e=>process.stdout.write(`${e}\n`),err:e=>process.stderr.write(`${e}\n`)},Aa=T({title:C().optional(),error:C().optional(),message:C().optional()});function ja(){let e=l();return`OpenKnowledge server is not running — the links validator needs the live backlink index. Start it with \`${e} start\` (or open OK Desktop) and re-run. For headless lint-only checks, use \`${e} lint\`.`}function Ma(e){return new j(`audit`).description(`Unified validation audit (markdown lint + broken internal links) via the running project server`).argument(`[path]`,`Folder or file to audit, relative to where you run the command`).option(`--json`,`Emit the full structured JSON response instead of formatted text`).option(`--errors-only`,`Exit non-zero only on error-severity problems (broken links default to warnings; the project's validation.links setting can raise them to errors)`).action(async(t,n)=>{let r=await Na(t,n,e(),process.cwd(),rr());r!==0&&(process.exitCode=r)})}async function Na(e,t,n,r,i,a=ka){let o=Tn(n,r),s;if(e!==void 0){let t=Pa(e,i,o);if(t===null){if(rt(void 0,o).ok)return a.err(`Path is outside the content directory (${o}): ${e}`),1}else s=t===``?void 0:t}let c=en(O(r));if(!c||c.port<=0)return a.err(ja()),1;let l=`http://127.0.0.1:${c.port}`,u=s===void 0?``:`?path=${encodeURIComponent(s)}`,d;try{d=await fetch(`${l}/api/audit${u}`,{headers:Ut({kind:`cli`,runtimeVersion:dn})})}catch(e){return a.err(`Could not reach the OpenKnowledge server on port ${c.port}: ${String(e)}`),1}if(!d.ok){let e=await d.json().catch(()=>null),n=re.safeParse(e);if(n.success)t.json===!0?a.out(JSON.stringify(n.data,null,2)):a.err(`Audit failed: ${n.data.title}`);else{let t=Aa.safeParse(e),n=t.success?t.data.title??t.data.error??t.data.message:void 0;a.err(`Audit failed: ${n??`server responded with ${d.status}`}`)}return 1}let f=ve.safeParse(await d.json().catch(()=>null));if(!f.success){let e=f.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return a.err(`Audit failed: unexpected response shape from the server. Schema issues: ${e}`),1}let p=f.data;if(t.json===!0)a.out(JSON.stringify(p,null,2));else{let e=p.brokenLinkSuppression?$t(p.brokenLinkSuppression,{surface:`cli`,serverBaseUrl:l}):void 0;a.out([Oa(Fa(p)),...e===void 0?[]:[e]].join(`
3
3
  `))}return+(t.errorsOnly===!0?p.errorCount>0:p.errorCount+p.warningCount>0)}function Pa(e,t,n){let r=B(n,V(t,e));return r===``?``:r.startsWith(`..`)||Hi(r)?null:r.split(Wi).join(`/`)}function Fa(e){return{files:e.files.map(e=>({file:e.file,fixed:!1,diagnostics:e.diagnostics})),warnings:e.warnings,fileCount:e.fileCount,errorCount:e.errorCount,warningCount:e.warningCount,fixedCount:0,ran:e.ran}}const Ia={get:`Lookup credentials from TokenStore (called by git)`,store:`Accept a credential git approved, without saving it (called by git)`,erase:`Accept a credential git rejected, without removing it (called by git)`};function La(e,t){let n=new j(`git-credential`);n.description(`Git credential helper (git credential-helper protocol)`);for(let a of i)n.command(a).description(Ia[a]).action(async()=>{let n=t?.(),i=a===`get`?await xi({getTokenStore:e,log:n}):await r(a,process.stdin);await zr(n),process.exit(i)});return n}function Ra(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function za(e,t,n){let r={baseUrl:Ra(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new Pr(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Ba(e){let t=e.request||Ir,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),za(t,`POST /login/device/code`,n)}async function Va(e){let t=await za(e.request||Ir,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ha(e,t.data.expires_in),n.refreshTokenExpiresAt=Ha(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ha(e,t){return new Date(e+t*1e3).toISOString()}async function Ua(e,t){let n=Wa(e,t.auth);if(n)return n;let{data:r}=await Ba({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Ka(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Wa(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)&&n}async function Ga(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Ka(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Va({...i,clientType:`oauth-app`}):await Va({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Ga(r.interval),Ka(e,t,n,r);if(a===`slow_down`)return await Ga(r.interval+7),Ka(e,t,n,r);throw i}}async function qa(e,t){return Ua(e,{auth:t})}async function Ja(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await Ua(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Ya=`0.0.0-development`;function Xa(e){let t=e.request||Ir.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Ya} ${Fr()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(qa.bind(null,i),{hook:Ja.bind(null,i)})}async function Za(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Xa({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-Dl9Hkg-Q.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Qa(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}function $a(){let e=process.cwd();return Vr(e)?.rootPath??e}function eo(e){return`${h(`global.yml`)}:\n\n git:\n hosts:\n ${e}:\n provider: github\n`}function to(e){return` ${l()} auth token --host ${e} --username <username>`}function no(e){return`If ${e} is not a GitHub host, store an access token for git with:\n\n${to(e)}\n`}function ro(e){return`${F(`Error:`)} ${e} is not a known GitHub host.\nTo use a GitHub Enterprise Server host, declare it in ${eo(e)}\n`+no(e)}function io(e){return x(e,Xt())}function ao(e){return io(e)?null:ro(p(e))}function oo(e){let t=ao(e);t!==null&&(process.stderr.write(t),process.exit(1))}function so(e,t){if(e===null)return`${F(`Error:`)} Cannot determine a GitHub hostname from this project's git remote.\nPass --host <hostname> to target a GitHub host explicitly.
4
4
  `;let n=p(e),r=t?`, or, if ${n} runs GitHub Enterprise Server, declare it in ${eo(n)}\n`:`.
@@ -8,13 +8,13 @@ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{a as t,i as n,r,t as
8
8
  `),process.exit(1));let o=r===`github.com`?void 0:`https://${r}/api/v3`,s=new ls({auth:a,...o?{baseUrl:o}:{}}),c=`unknown`,l,u;try{let{data:e}=await s.users.getAuthenticated();c=e.login,l=e.name??void 0,u=e.email??void 0}catch(e){let t=fs(e,r).message;i?process.stdout.write(`${JSON.stringify({type:`error`,message:t})}\n`):process.stderr.write(`${t}\n`),process.exit(1)}try{await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u})}catch(e){let t=`Could not save the token to the credential store: ${e instanceof Error?e.message:String(e)}`;i?process.stdout.write(`${JSON.stringify({type:`error`,message:t})}\n`):process.stderr.write(`${t}\n`),process.exit(1)}i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function hs(e){return new j(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: the GitHub origin host, or github.com with no origin; required otherwise)`).option(`--json`,`Output JSON`,!1).option(`--token-stdin`,`Read the token from stdin instead of prompting`,!1).action(async t=>{let n=lo(t.host),r=t.tokenStdin?ps:void 0;await ms({host:n,json:t.json},await e(),r)})}async function gs(e,t,n=Si){let r=n(e);return r.available&&r.token?r.token:(await t.get(e))?.token??null}async function _s(e,t){let{host:n,json:r}=e,i=await gs(n,t);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new ls({auth:i,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function vs(e){return new j(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: the GitHub origin host, or github.com with no origin; required otherwise)`).option(`--json`,`Output JSON`,!1).action(async t=>{let n=lo(t.host);await _s({...t,host:n},await e())})}async function ys(e){let{host:t}=e,{touched:n}=await hi(t);if(n.length===0){process.stderr.write(`Not signed in to ${t}\n`);return}process.stderr.write(`✓ Signed out from ${t}\n`),n.includes(`keychain`)&&process.stderr.write(` cleared from OS keychain
9
9
  `),n.includes(`file`)&&process.stderr.write(` cleared from ${yi()}\n`)}function bs(){return new j(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: the GitHub origin host, or github.com with no origin; required otherwise)`).action(async e=>{let t=uo(e.host);await ys({...e,host:t})})}async function xs(e,t,n=Si){let r=n(e);if(r.available&&r.token)return{tier:`A`,token:r.token};let i=await t.get(e);return i==null?{tier:`none`}:{tier:i.gitProtocol===`ssh`?`C`:`B`,token:i.token}}function Ss(e,t,n){return{type:`status`,host:e,backend:t,...n}}async function Cs(e,t){let n=await t.get(e);return n==null?{authenticated:!1}:{authenticated:!1,unverified:!0,login:n.login}}function ws(e,t){return e.unverified===!0?`Token stored for ${e.login} on ${t}. ${t} is not a GitHub host, so OpenKnowledge does not verify it; git uses this credential to push and pull.`:`No token stored for ${t}. Store one with:\n\n${to(t)}`}async function Ts(e,t){let{host:n,json:r}=e,i=await Cs(n,t);r?process.stdout.write(`${JSON.stringify(Ss(n,t.backend,i))}\n`):process.stderr.write(`${ws(i,n)}\n`),process.exit(i.unverified===!0?0:1)}async function Es(e,t){let{host:n,json:r}=e,i=t.backend,a=await xs(n,t);a.tier===`none`&&(r?process.stdout.write(`${JSON.stringify(Ss(n,i,{authenticated:!1}))}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let o=n===`github.com`?void 0:`https://${n}/api/v3`,s=new ls({auth:a.token,...o?{baseUrl:o}:{}});try{let{data:e}=await s.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify(Ss(n,i,{authenticated:!0,tier:a.tier,login:e.login,name:e.name,email:e.email}))}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch(e){let t=fs(e,n);r?process.stdout.write(`${JSON.stringify(Ss(n,i,{authenticated:!1,error:t.message}))}\n`):process.stderr.write(`✗ ${t.message}\n`),process.exit(1)}}function Ds(e){return new j(`status`).description(`Show authentication status`).option(`--host <host>`,`Git hostname (default: the origin host, or github.com with no origin; required when origin has no hostname, such as a local path). A non-GitHub host reports its stored token without verifying it`).option(`--json`,`Output JSON`,!1).action(async t=>{let n=co(t.host);if(n.kind===`other`){await Ts({...t,host:n.host},await e());return}await Es({...t,host:n.host},await e())})}function Os(e,t){return t?process.stdout.write(`${JSON.stringify(e)}\n`):e.type===`error`?process.stderr.write(`${e.message}\n`):process.stderr.write(`✓ Token stored for ${e.login} on ${e.host}\n`),e}async function ks(e,t,n){let{json:r}=e,i=e.host?.trim()??``;if(!i)return Os({type:`error`,message:`A host is required. Pass --host <host>.`},r);if(!y(i))return Os({type:`error`,message:`${i} is not a host name. Pass the host git connects to, with an optional :port and no scheme or path, for example git.example.com or git.example.com:8443.`},r);let a=d(i);if(io(a))return Os({type:`error`,message:`${a} is a GitHub host. Use ${l()} auth pat --host ${a}, which checks the token with GitHub before storing it.`},r);let o=e.username?.trim()??``;if(!o)return Os({type:`error`,message:`A username is required. Pass --username <username>.`},r);let s=await(n??(()=>go({message:`Enter token:`})))();if(!s)return Os({type:`error`,message:`No token provided`},r);try{await t.set(a,o,s,{gitProtocol:`https`})}catch(e){return Os({type:`error`,message:`Could not save the token to the credential store: ${e instanceof Error?e.message:String(e)}`},r)}return Os({type:`complete`,host:a,login:o},r)}function As(e){return new j(`token`).description(`Store an access token for any git host`).option(`--host <host>`,`Git host to store the token for`).option(`--username <username>`,`Username git sends with the token (Bitbucket: x-bitbucket-api-token-auth for an API token, x-token-auth for a repository or workspace access token; oauth2 for GitLab; your Gitea username; any non-empty value for Azure DevOps)`).option(`--json`,`Output JSON`,!1).option(`--token-stdin`,`Read the token from stdin instead of prompting`,!1).action(async t=>{let n=t.tokenStdin?ps:void 0;(await ks({host:t.host,username:t.username,json:t.json},await e(),n)).type===`error`&&process.exit(1)})}function js(e){let t=new j(`auth`);t.description(`Git host authentication management`);let n=e=>_i(void 0,e);return t.addCommand(mo(n)),t.addCommand(Ds(n)),t.addCommand(vs(n)),t.addCommand(bs()),t.addCommand(hs(n)),t.addCommand(As(n)),t.addCommand(La(n,e)),t}function Ms(e,t=ia(),n=Mi){try{t===`darwin`?n(`/usr/bin/open`,[`-R`,e]):n(t===`win32`?`explorer.exe`:`xdg-open`,[R(e)])}catch{}}function Ns(){return new j(`bug-report`).description(`Generate a diagnostic bundle for bug reporting`).option(`--reveal`,`Reveal the bundle in your file manager (default: true)`,!0).option(`--no-reveal`,`Do not reveal the bundle in your file manager`).action(async e=>{try{let{zipPath:t,summary:n}=await $n({level:`standard`,projectDir:process.cwd(),redact:!0,outputPath:er(),logger:gi()});process.stdout.write(`${t}\n`),n.redactedLineCount>0&&process.stderr.write(`ok bug-report: ${n.redactedLineCount} line(s) auto-redacted across ${n.redactions.length} file(s)\n`),e.reveal&&Ms(t)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`ok bug-report: failed — ${t}\n`),process.exitCode=1}})}function Ps(e){return{prune:[{name:`server`,lockPath:e.lockPath,reason:e.status,text:e.text}]}}function Fs(e){switch(e.status){case`read-error`:return{prune:[],refusal:{lockPath:e.lockPath,error:`Cannot read the server lock: ${e.error}. ${ft}`}};case`corrupt`:return e.foreignHost?{prune:[],refusal:{lockPath:e.lockPath,error:jr(e)}}:Ps(e);case`dead-pid`:case`reused-pid`:return Ps(e);case`unverified-owner`:case`foreign-host`:return{prune:[],refusal:{lockPath:e.lockPath,error:jr(e)}};case`alive`:case`missing`:return{prune:[]};default:return e}}const Is={changed:`the lock changed after it was checked, so it was left in place`,missing:`the lock was removed after it was checked`};function Ls(e){let t=Lt(e.lockPath,e.text);if(t!==`removed`)throw Error(Is[t])}function Rs(e){let t=e.inspect??(()=>lr(e.lockDir,`server`,{isAlive:fn})),n=e.log??(e=>console.log(e)),r=e.error??(e=>console.error(e)),i=e.unlink,a=i?e=>i(e.lockPath):Ls,o=Fs(t());if(o.refusal)return r(`${o.refusal.lockPath}: ${o.refusal.error}`),{pruned:[],failed:[{target:{name:`server`,lockPath:o.refusal.lockPath},error:o.refusal.error}]};if(o.prune.length===0)return n(`No stale locks.`),{pruned:[],failed:[]};let s=[],c=[];for(let e of o.prune)try{a(e),s.push(e)}catch(t){c.push({target:e,error:t instanceof Error?t.message:String(t)})}if(s.length>0){let e=s.map(e=>`${e.name} (${e.reason})`).join(`, `);n(`Pruned ${s.length} stale lock${s.length===1?``:`s`}: ${e}`)}return c.length>0&&r(`Failed to prune: ${c.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:s,failed:c}}function zs(e){return new j(`clean`).description(`Prune a stale / corrupt open-knowledge lock file (never touches live locks)`).action(()=>{e(),Rs({lockDir:O(process.cwd())}).failed.length>0&&(process.exitCode=1)})}function Bs(e){return`!${e.map(Ie).join(` `)} auth git-credential`}function Vs(e){return`credential.helper=${Bs(e)}`}function Hs(e,t){let n=`credential.https://${t}.helper`;return[`${n}=`,`${n}=${Bs(e)}`]}async function Us(e,t,n={},r=Si){let i=[`credential.helper=`,Vs(n.selfCliArgs??[`open-knowledge`])];if(!n.skipGhDetect){let t=r(e,{login:n.login});if(t.available&&t.token)return{tier:`A`,gitConfig:i,relayToken:{token:t.token,host:e,...t.resolvedLogin?{login:t.resolvedLogin}:{}}}}let a=(n.credentialHost===void 0?null:await t.get(n.credentialHost))??await t.get(e);return a==null?{tier:`none`,gitConfig:[]}:{tier:a.gitProtocol===`ssh`?`C`:`B`,gitConfig:i}}async function Ws(e,t,n=fetch){let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{return(await n(`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{signal:r.signal,headers:{"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}})).status===200}catch{return!1}finally{clearTimeout(i)}}const Gs=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ks(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of Gs)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function qs(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t.GIT_TERMINAL_PROMPT=`0`,t.LANG=`C`,t.LC_ALL=`C`,t}function Js(e,t=process.env){let n=qs(t);return e.relayToken?(n.OK_GH_TOKEN=e.relayToken.token,n.OK_GH_TOKEN_HOST=e.relayToken.host,e.relayToken.login?n.OK_GH_TOKEN_LOGIN=e.relayToken.login:delete n.OK_GH_TOKEN_LOGIN):(delete n.OK_GH_TOKEN,delete n.OK_GH_TOKEN_HOST,delete n.OK_GH_TOKEN_LOGIN),n}function Ys(e=process.argv,t=process.execPath){let n=e[1];return n?[t,n]:[t]}function Xs(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const Zs=De;async function Qs(e){try{return await e.clone(Xs(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&Zs(t))return e.onFallback(e.branch),await e.clone(Xs(null)),{fellBack:!0};throw t}}function $s(e,t){return{baseDir:e,config:t,unsafe:{allowUnsafeCredentialHelper:!0,allowUnsafePager:!0,allowUnsafeSshCommand:!0,allowUnsafeAskPass:!0,allowUnsafeEditor:!0,allowUnsafeConfigEnvCount:!0}}}function ec(e,t,n){return e===`https`&&t===`github.com`&&n}function tc(e,t){if(e===void 0)return null;let{declaredLogin:n,declaredSource:r}=e,i;switch(r){case`remote-url`:i=`${t.url} names ${n}`;break;case`credential-config`:i=`Your Git credential configuration names ${n}`;break;default:i=`Your Git configuration names ${n}`}return`⚠ ${i}, but the GitHub CLI couldn't confirm that account — ${t.operation} used its active account.\n Run \`gh auth status\` to see which account that is. If ${n} is listed as active, nothing is wrong; confirming an account by name needs GitHub CLI 2.40 or newer.\n`}function nc(e){return tc(e,{url:`The clone URL`,operation:`the clone`})}async function rc(e,t,n={}){let r=kr(e);if(!r)throw Error(`Invalid git URL: ${cc(e)}`);if(e.trim().startsWith(`http://`))return{auth:{tier:`none`,gitConfig:[]}};let i=At(e,{cwd:n.cwd,_readCredentialUrlMatch:n._readCredentialUrlMatch}),a=g(e)??void 0,o=await Us(i.host??r.hostname,t,{selfCliArgs:n.selfCliArgs,login:i.login,credentialHost:a},n._detectGhFn),s=i.login!==void 0&&o.tier===`A`&&!pn(o.relayToken?.login,i.login)?{declaredLogin:i.login,declaredSource:i.source}:void 0;return{auth:o,...s===void 0?{}:{declaredMiss:s}}}function ic(e,t){let n=`${t.owner}/${t.name}`;return e===n||e===`${n}.git`?`https://${t.hostname}/${n}`:e}async function ac(e,t,n,r=process.cwd()){let i=kr(e);if(!i)throw Error(`Invalid git URL: ${cc(e)}`);let a=ic(e,i),o=t.dir?V(r,t.dir):V(r,i.name),s=H(o);if(s&&Qi(o).length>0)throw Error(`Target directory is not empty: ${o}`);_t();let c=mi(),l=i.protocol===`https`&&i.hostname===`github.com`&&await Ws(i.owner,i.name),u=ec(i.protocol,i.hostname,l)?{auth:{tier:`none`,gitConfig:[]}}:await rc(a,c,{selfCliArgs:Ys(),cwd:r,...t._detectGhFn?{_detectGhFn:t._detectGhFn}:{}}),d=u.auth;if(t.onAuthResolved?.({tier:d.tier,login:d.relayToken?.login}),!t.json){let e=nc(u.declaredMiss);e&&process.stderr.write(e)}let f=Js(d),p=$s(r,d.gitConfig),m=A(p).env(f),h=-1;m.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
10
10
  `)){let n=Ks(e);n&&n.pct!==h&&(h=n.pct,q(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await Qs({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:e=>m.clone(a,o,[...e,`--no-checkout`]),onFallback:e=>{q(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
11
- `);let g=A({...p,baseDir:o}).env(f);if((await g.raw([`rev-parse`,`--verify`,`--quiet`,`HEAD^{commit}`])).trim()!==``){try{await qt(g,`HEAD`,f)}catch(e){throw G(s?z(o,`.git`):o,{recursive:!0,force:!0}),e}await g.raw([`checkout`,`--force`,`HEAD`])}try{let{runInit:e}=await import(`./init-D8_giXgq.mjs`),n=await e({cwd:o,projectRootMode:`cwd`,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{oc(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function oc(e){let t=ni(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const sc=/^[A-Za-z0-9._/:@-]+$/;function cc(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)@/i,(e,t,n)=>{let r=n.indexOf(`:`),i=r===-1?n:n.slice(0,r);return i!==``&&$e(i)!==void 0?`${t}${i}@`:t})}function lc(e){return sc.test(e)?e:Ie(e)}function uc(e,t){let n=typeof t==`string`&&t.length>0?` -b ${lc(t)}`:``;return`${l()} clone ${lc(e)}${n}`}function dc(e){let t=We(e.error);if(t.kind!==`auth`)return null;let n=cc(e.url);if(Oe(t)){let t=uc(n,e.branch);return[`✗ Couldn't clone ${n} — authentication is required.`,``,` To fix:`,` 1. Run: ${l()} auth login`,` 2. Then re-run: ${t}`].join(`
11
+ `);let g=A({...p,baseDir:o}).env(f);if((await g.raw([`rev-parse`,`--verify`,`--quiet`,`HEAD^{commit}`])).trim()!==``){try{await qt(g,`HEAD`,f)}catch(e){throw G(s?z(o,`.git`):o,{recursive:!0,force:!0}),e}await g.raw([`checkout`,`--force`,`HEAD`])}try{let{runInit:e}=await import(`./init-CMXr3PqV.mjs`),n=await e({cwd:o,projectRootMode:`cwd`,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{oc(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function oc(e){let t=ni(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const sc=/^[A-Za-z0-9._/:@-]+$/;function cc(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)@/i,(e,t,n)=>{let r=n.indexOf(`:`),i=r===-1?n:n.slice(0,r);return i!==``&&$e(i)!==void 0?`${t}${i}@`:t})}function lc(e){return sc.test(e)?e:Ie(e)}function uc(e,t){let n=typeof t==`string`&&t.length>0?` -b ${lc(t)}`:``;return`${l()} clone ${lc(e)}${n}`}function dc(e){let t=We(e.error);if(t.kind!==`auth`)return null;let n=cc(e.url);if(Oe(t)){let t=uc(n,e.branch);return[`✗ Couldn't clone ${n} — authentication is required.`,``,` To fix:`,` 1. Run: ${l()} auth login`,` 2. Then re-run: ${t}`].join(`
12
12
  `)}return t.subclass===`403`?`✗ Access denied when cloning ${n}${typeof e.principal==`string`&&e.principal.length>0?` (signed in as @${e.principal} — may lack access)`:``}. Check that your account has access to the repository.`:t.subclass===`ssh-auth`?`✗ Couldn't clone ${n} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`:t.subclass===`not-found-as-identity`?`✗ Repository not found when cloning ${n}. It may not exist, or the account used may not have access.${typeof e.resolvedLogin==`string`&&e.resolvedLogin.length>0?` Authenticated as ${e.resolvedLogin}.`:``}`:["✗ Your GitHub token is missing required OAuth scopes — likely the `repo` scope.",``,` To fix:`," 1. Create a token with `repo` scope at https://github.com/settings/tokens",` 2. Run: ${l()} auth pat`,` 3. Then re-run: ${uc(n,e.branch)}`].join(`
13
13
  `)}function fc(e){if(!(e.error instanceof On)||e.error.plugin!==`unsafe`||!e.message.startsWith(`Configuring `))return null;let t=cc(e.url);return[`✗ Couldn't clone ${t} — a Git setting passed in through the GIT_CONFIG_COUNT and GIT_CONFIG_KEY_<n> environment variables was refused:`,` ${e.message}`,``,` To fix:`,` 1. Remove that setting from the GIT_CONFIG_KEY_<n> and GIT_CONFIG_VALUE_<n> variables, or unset GIT_CONFIG_COUNT`,` 2. Then re-run: ${uc(t,e.branch)}`].join(`
14
- `)}function pc(e){let t=e.error instanceof Mt?`The repository has symlinks that are unsafe to check out: ${e.error.describeLinks()}. The clone was removed. Remove or fix these links on the remote, then clone again.`:vn(e.error instanceof Error?e.error.message:String(e.error));if(e.json){e.emit(e.error instanceof Mt?{type:`error`,code:`unsafe-symlinks`,message:`The repository has ${e.error.unsafe.length} symlink(s) that are unsafe to check out. The clone was removed. Remove or fix these links on the remote, then clone again.`,refusedSymlinkPaths:e.error.displayPaths()}:{type:`error`,message:t});return}let n=dc({error:e.error,url:e.url,branch:e.branch,principal:e.principal,resolvedLogin:e.resolvedLogin})??fc({error:e.error,message:t,url:e.url,branch:e.branch});e.printStderr(`${n??`✗ ${t}`}\n`)}async function mc(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function hc(e){let t=We(e.error),n=e.auth?.tier===`A`?e.auth:void 0,r=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){if(n)r=n.login??null;else if(e.auth?.tier!==`none`){let t=kr(e.url);t&&(r=await(e.resolvePrincipal??(e=>mc(mi(),e)))(t.hostname))}}pc({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:r,resolvedLogin:n?.login??null,emit:e.emit,printStderr:e.printStderr})}function gc(e){return new j(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e(),a;try{let o=await ac(t,{json:r.json,dir:n,branch:r.branch??null,onAuthResolved:e=>{a=e}},i);if(r.json)q(!0,{type:`complete`,dir:o});else{process.stderr.write(`✓ Cloned to ${o}\n`),process.chdir(o);let{startCommand:t}=await import(`./start-C1as3B3R.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){if(e instanceof Ft||e instanceof Yn||e instanceof Xe){r.json?q(!0,{type:`error`,message:e.message}):process.stderr.write(`${e.message}\n`),process.exitCode=78;return}await hc({error:e,url:t,branch:r.branch??null,json:r.json,auth:a,emit:e=>q(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var _c=b();const vc=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],...S.map(e=>e.path)];function yc(e){return En({absPath:wn(`project-local`,e),sideline:!1}).diagnostics}function bc(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ii;try{let{sources:n,diagnostics:i,sidelined:a}=r(e.cwd),o=(e.readProjectLocalFn??yc)(e.cwd??process.cwd()),s=[...i,...o],c=n.length===0?`defaults only`:n.join(`, `),l=s.filter(e=>e.code!==`REMOVED_KEY`);l.length===0?t(`✓ Configuration valid (sources: ${c})`):t(`! Configuration loaded, but ${l.length} config layer(s) had issues (sources: ${c})`);for(let e of s)t(``),t(D(e));for(let{from:e,to:n}of a)t(``),t(`Moved ${e} aside to ${n} so defaults could be used. Restore it once fixed.`);return{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function xc(e){let t=W(e,`utf-8`),n=(0,_c.parseDocument)(t);if(n.errors.length>0)throw Error(`Could not parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`);let r=[];for(let e of vc)n.hasIn(e)&&r.push(e.join(`.`));return r}function Sc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cc(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Sc(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}function wc(e){switch(e){case`project`:return[`project`];case`project-local`:return[`project-local`];case`user`:return[`user`];case`both`:return[`project`,`user`];case`all`:return[`project`,`project-local`,`user`]}}async function Tc(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`all`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??jt,s=wc(r).map(t=>({scope:t,absPath:wn(t,a,e.homedirOverride)})),c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!H(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=xc(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Cc(vc.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:D(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}const Ec=`project | project-local | user | all`,Dc=new Set(Object.keys({project:!0,"project-local":!0,user:!0,both:!0,all:!0}));function Oc(e){return e!==`config`}function kc(){let e=new j(`config`).description(`Inspect and maintain OpenKnowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{bc({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*)`).option(`--scope <scope>`,`Which scope to migrate: ${Ec}`,`all`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=String(e.scope);if(!Dc.has(t)){console.error(`Invalid --scope: ${t}. Expected: ${Ec}`),process.exitCode=2;return}(await Tc({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const Ac=[` 1. ${L(`Customize`)} (sidebar) → ${L(`Skills`)}`,` 2. Click the ${L(`+`)} button`,` 3. Click ${L(`Create skill`)}`,` 4. Click ${L(`Upload skill`)}`,` 5. Pick ${L(`openknowledge.skill`)} from Downloads`],jc=M(` Open the Claude Desktop App, then: ${L(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Mc(e){let t=[P(`Built ${e.outputPath}`),N(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(I(` Handoff failed: ${e.handoffError.message}`)),t.push(jc),t.join(`
14
+ `)}function pc(e){let t=e.error instanceof Mt?`The repository has symlinks that are unsafe to check out: ${e.error.describeLinks()}. The clone was removed. Remove or fix these links on the remote, then clone again.`:vn(e.error instanceof Error?e.error.message:String(e.error));if(e.json){e.emit(e.error instanceof Mt?{type:`error`,code:`unsafe-symlinks`,message:`The repository has ${e.error.unsafe.length} symlink(s) that are unsafe to check out. The clone was removed. Remove or fix these links on the remote, then clone again.`,refusedSymlinkPaths:e.error.displayPaths()}:{type:`error`,message:t});return}let n=dc({error:e.error,url:e.url,branch:e.branch,principal:e.principal,resolvedLogin:e.resolvedLogin})??fc({error:e.error,message:t,url:e.url,branch:e.branch});e.printStderr(`${n??`✗ ${t}`}\n`)}async function mc(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function hc(e){let t=We(e.error),n=e.auth?.tier===`A`?e.auth:void 0,r=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){if(n)r=n.login??null;else if(e.auth?.tier!==`none`){let t=kr(e.url);t&&(r=await(e.resolvePrincipal??(e=>mc(mi(),e)))(t.hostname))}}pc({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:r,resolvedLogin:n?.login??null,emit:e.emit,printStderr:e.printStderr})}function gc(e){return new j(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e(),a;try{let o=await ac(t,{json:r.json,dir:n,branch:r.branch??null,onAuthResolved:e=>{a=e}},i);if(r.json)q(!0,{type:`complete`,dir:o});else{process.stderr.write(`✓ Cloned to ${o}\n`),process.chdir(o);let{startCommand:t}=await import(`./start-MRWYWYqt.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){if(e instanceof Ft||e instanceof Yn||e instanceof Xe){r.json?q(!0,{type:`error`,message:e.message}):process.stderr.write(`${e.message}\n`),process.exitCode=78;return}await hc({error:e,url:t,branch:r.branch??null,json:r.json,auth:a,emit:e=>q(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var _c=b();const vc=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],...S.map(e=>e.path)];function yc(e){return En({absPath:wn(`project-local`,e),sideline:!1}).diagnostics}function bc(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ii;try{let{sources:n,diagnostics:i,sidelined:a}=r(e.cwd),o=(e.readProjectLocalFn??yc)(e.cwd??process.cwd()),s=[...i,...o],c=n.length===0?`defaults only`:n.join(`, `),l=s.filter(e=>e.code!==`REMOVED_KEY`);l.length===0?t(`✓ Configuration valid (sources: ${c})`):t(`! Configuration loaded, but ${l.length} config layer(s) had issues (sources: ${c})`);for(let e of s)t(``),t(D(e));for(let{from:e,to:n}of a)t(``),t(`Moved ${e} aside to ${n} so defaults could be used. Restore it once fixed.`);return{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function xc(e){let t=W(e,`utf-8`),n=(0,_c.parseDocument)(t);if(n.errors.length>0)throw Error(`Could not parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`);let r=[];for(let e of vc)n.hasIn(e)&&r.push(e.join(`.`));return r}function Sc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cc(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Sc(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}function wc(e){switch(e){case`project`:return[`project`];case`project-local`:return[`project-local`];case`user`:return[`user`];case`both`:return[`project`,`user`];case`all`:return[`project`,`project-local`,`user`]}}async function Tc(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`all`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??jt,s=wc(r).map(t=>({scope:t,absPath:wn(t,a,e.homedirOverride)})),c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!H(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=xc(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Cc(vc.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:D(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}const Ec=`project | project-local | user | all`,Dc=new Set(Object.keys({project:!0,"project-local":!0,user:!0,both:!0,all:!0}));function Oc(e){return e!==`config`}function kc(){let e=new j(`config`).description(`Inspect and maintain OpenKnowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{bc({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*)`).option(`--scope <scope>`,`Which scope to migrate: ${Ec}`,`all`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=String(e.scope);if(!Dc.has(t)){console.error(`Invalid --scope: ${t}. Expected: ${Ec}`),process.exitCode=2;return}(await Tc({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const Ac=[` 1. ${L(`Customize`)} (sidebar) → ${L(`Skills`)}`,` 2. Click the ${L(`+`)} button`,` 3. Click ${L(`Create skill`)}`,` 4. Click ${L(`Upload skill`)}`,` 5. Pick ${L(`openknowledge.skill`)} from Downloads`],jc=M(` Open the Claude Desktop App, then: ${L(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Mc(e){let t=[P(`Built ${e.outputPath}`),N(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(I(` Handoff failed: ${e.handoffError.message}`)),t.push(jc),t.join(`
15
15
  `)}function Nc(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[M(`OpenKnowledge skill ${L(`v${t}`)} already delivered to Claude Desktop.`),N(` Recorded at ${n} in ${h(`skill-state.yml`)}`),N(` Use ${L(`--force`)} to rebuild and re-open the install dialog.`)].join(`
16
16
  `)}function Pc(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[P(`Built ${e.outputPath}`),N(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),M(` Claude Desktop App opened. Now upload the file manually:`),...Ac,N(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
17
- `)}function Fc(e){return`${F(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Ic(e={}){let t=await tn(e);return t.status===`failed`?{...t,message:Fc(t),exitCode:1}:t.status===`skip-current`?{...t,message:Nc(t),exitCode:0}:t.status===`installed`?{...t,message:Pc(t),exitCode:0}:{...t,message:Mc(t),exitCode:0}}function Lc(){return new j(`cowork`).description(`Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. (Advanced/rarely needed — \`${l()} init\` already wires Claude.)`).option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).option(`--force`,`Bypass the install-state gate and rebuild unconditionally`).action(async e=>{let t=await Ic({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}async function Rc(e,t){let n=ga({input:t??process.stdin,output:process.stderr});try{let t=(await n.question(e)).trim().toLowerCase();return t===`y`||t===`yes`}finally{n.close()}}async function zc(e,t={}){let n=t.probe??gt(),r=t.isAlive??(e=>fn(e,n(e))),i=t.isAlive??sn,a=t.platform??process.platform,o=(e,n)=>(t.readProcessStart??Cr)(e,{platform:a,onNativeFailure:n}),s=lr(e,`server`,{isAlive:r,readProcessStart:o}),c=`Quit OpenKnowledge and stop any OpenKnowledge server processes. Once you have confirmed they have exited, remove the stale lock file at ${s.lockPath} and retry cleanup.`,l=()=>{switch(s.status){case`alive`:case`dead-pid`:case`reused-pid`:case`foreign-host`:return s.lock.pid;case`unverified-owner`:return s.pid;case`missing`:case`corrupt`:case`read-error`:return;default:return s}},u=()=>{let t=l();return{...t===void 0?{}:{lockPid:t},lockDir:e,lockPath:s.lockPath,status:s.status}},d=e=>(gi()?.warn(u(),e),Error(e));if(s.status===`read-error`)throw d(`Cannot read the server lock at ${s.lockPath}: ${s.error}. Restore file and parent-directory access, then retry cleanup.`);let f=s.status===`unverified-owner`||s.status===`foreign-host`||s.status===`corrupt`&&s.foreignHost===!0?s:null,p=f!==null&&f.status!==`unverified-owner`;if(f!==null&&!t.preserveProjectState)throw d(jr(f));if(s.status===`dead-pid`)return{stopped:0,failed:[],skipped:`Skipped stale lock at ${s.lockPath}; its recorded local process ${s.lock.pid} has exited. No server was stopped.`};if(s.status===`reused-pid`)return{stopped:0,failed:[],skipped:`Skipped stale lock at ${s.lockPath}; its recorded process ${s.lock.pid} has exited and that process ID now belongs to another program, which was not signalled. No server was stopped.`};if(s.status===`corrupt`||s.status===`foreign-host`||s.status===`unverified-owner`){let i=s.status===`unverified-owner`,a=i?`unverified`:p?`foreign-owned`:`malformed`,o=await(t.scanProcesses??(()=>Sn(n)))(),l=await oa(e).catch(()=>V(e)),u=o.candidates.filter(e=>e.lockDir===l&&r(e.pid));if(u.length>0)throw d(`Cannot verify shutdown from the ${a} lock at ${s.lockPath}: live process candidates ${u.map(e=>`${e.pid} (${e.source})`).join(`, `)}. No process was signalled. ${c}`);if(o.unavailable.length>0)throw d(`Cannot rule out a live server for ${s.lockPath}: ${o.unavailable.join(`; `)}. Restore process-inspection access and retry cleanup. ${c}`);return{stopped:0,failed:[],skipped:i?`Retained project lock with an unverified owner at ${s.lockPath}; its recorded process ${s.pid} is running locally, but process and listener inspection could not attribute any server to this directory. No process was signalled. Only local application cleanup may proceed; project state is unchanged. No server was stopped.`:p?`Retained foreign-owned project lock at ${s.lockPath}; process and listener inspection found no local server candidate for this directory. Only local application cleanup may proceed; project state is unchanged. No server was stopped.`:`Skipped malformed lock at ${s.lockPath}; process and listener inspection found no live server candidate for this directory. No server was stopped.`}}let m=await Tr({lockDir:e,inspect:()=>s,isAlive:r,readProcessStart:(e,t)=>o(e,t?.onNativeFailure),platform:a,force:!0,refuseHolderStartedAfterLock:!0,log:()=>{},error:()=>{}}),h=m.failed.find(e=>e.unverified!==void 0)?.unverified;if(h!==void 0)switch(h.cause){case`foreign-host`:throw Error(jr({status:`foreign-host`,lockPath:h.lockPath,lock:h.lock}));case`unverified-owner`:throw Error(jr({status:`unverified-owner`,lockPath:h.lockPath,pid:h.pid}));default:throw Error(Dr(h,`it was not signalled.`,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${h.lockPath} and retry cleanup.`,gi()!==void 0))}let g=m.failed.map(e=>({pid:e.target.pid,error:e.error})),_=new Set(m.stopped.map(e=>e.pid)),v=t.timeoutMs??1e4,y=performance.now()+v;for(;_.size>0;){for(let e of _)i(e)||_.delete(e);if(_.size===0)break;let e=y-performance.now();if(e<=0)break;await ha(Math.min(t.pollIntervalMs??50,e))}for(let e of _)r(e)||_.delete(e);for(let e of _)g.push({pid:e,error:`still running ${v}ms after SIGTERM`});return{stopped:m.stopped.length-_.size,failed:g}}function Bc(e){return e?ze.filter(e=>e!==Pe):[...ze]}function Vc(e){return Bc(e).map(e=>`~/.ok/${e}`).join(`, `)}function J(e,t){return e===t?`~`:e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Hc(e){return Wi===`/`?e:e.split(Wi).join(`/`)}function Uc(e,t,n=`This project`){let r=[],i=[O(e)],a=z(e,`.ok`);Ri(z(a,`server.lock`)).kind!==`not-present`&&i.push(a);for(let e of i)r.push({kind:`stop-server`,group:n,label:e===a?`Check the legacy project server lock`:`Stop the project server (if running)`,lockDir:e});let o=new Set;for(let i of ii){let a=ai[i];if(!a.projectConfigPath)continue;let s=a.projectConfigPath(e);o.add(Hc(B(e,s))),r.push({kind:`mcp-entry`,group:n,label:`Remove OK's MCP entry from ${a.label} (${Hc(B(e,s))})`,editorId:i,scope:`project`,cwd:e,home:t,configPath:s})}r.push({kind:`launch-entry`,group:n,label:`Remove OK's entry from .claude/launch.json`,projectRoot:e}),r.push({kind:`git-exclude`,group:n,label:`Remove OK paths from .git/info/exclude`,projectRoot:e});let s=new Set([...Gr(e),...ri(e),...Ge]);for(let t of s){let i=t.replace(/\/$/,``);o.has(i)||i!==`.claude/launch.json`&&r.push({kind:`remove-path`,group:n,label:`Remove ${t}`,path:z(e,i),containWithin:e})}try{r.push({kind:`remove-path`,group:n,label:`Remove the OK shadow repo (.git/ok/)`,path:An(e)})}catch{}let c=z(e,`.ok`);return r.sort((e,t)=>Number(e.kind===`remove-path`&&e.path===c)-Number(t.kind===`remove-path`&&t.path===c)),r.map(e=>e.kind===`stop-server`?e:{...e,requiresStoppedServers:i,...e.kind===`remove-path`?{requiresSuccessfulCleanup:!0}:{}})}function Wc(e,t){return{scope:`deinit`,ops:Uc(e,t)}}function Gc(e){let{home:t,platform:n,host:r,lockDirs:i,marker:a,recentDeinitProjectRoots:o,purgeContent:s}=e,c=[];for(let e of i)c.push({kind:`stop-server`,group:`Running servers`,label:`Stop server at ${J(z(e,`..`,`..`),t)}`,lockDir:e,preserveProjectState:!0});c.push({kind:`keychain-token`,group:`Credentials`,label:`Remove the GitHub credential (${r}) from the OS keychain + ${v}`,host:r}),c.push({kind:`embeddings-key`,group:`Credentials`,label:`Remove all embeddings API keys (${m})`}),c.push(...qc(a,t));for(let e of ii){let n=ai[e],r;try{r=n.configPath(``,t)}catch{continue}c.push({kind:`mcp-entry`,group:`Editor MCP configs`,label:`Remove OK's MCP entry from ${n.label} (${J(r,t)})`,editorId:e,scope:`user`,cwd:t,home:t,configPath:r})}for(let e of hr(t))c.push({kind:`remove-path`,group:`Skill bundles`,label:`Remove ${J(e.path,t)}`,path:e.path});for(let e of o)c.push(...Uc(e,t,`Project: ${Vi(e)}`));c.push(...Jc(t,n,e.env).map(e=>e.kind===`remove-path`?{...e,requiresSuccessfulCleanup:!0}:e));let{userHomeDirName:l}=_();return l===`.ok`?c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:s?`Remove ~/.ok (including user-authored skills; keeping ${Vc(!0)}, shared by every channel)`:`Remove ~/.ok (keeping ${Vc(!1)}, shared by every channel)`,path:Hr(t),preserve:Bc(s)}):(c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:s?`Remove ~/${l}`:`Remove ~/${l} (keeping ~/.ok/${Pe}, shared by every channel)`,path:Hr(t)}),s&&c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:`Remove ~/.ok/${Pe} (user-authored skills, shared by every channel)`,path:z(t,`.ok`,Pe)})),{scope:`uninstall`,ops:c}}function Kc(e){return[z(e,`.zshrc`),z(e,`.bash_profile`),z(e,`.config`,`fish`,`conf.d`,_r())]}function qc(e,t){let n=[],r=new Set([...Kc(t),...e?.rcFiles??[]]);for(let e of r)Ri(e).kind!==`not-present`&&n.push({kind:`shell-block`,group:`Shell PATH`,label:`Strip the OK block from ${J(e,t)}`,rcFile:e});for(let r of e?.extraSymlinks??[])n.push({kind:`extra-symlink`,group:`Shell PATH`,label:`Remove the ok symlink at ${J(r.path,t)}`,path:r.path,target:r.target});return n}function Jc(e,t,n){let r={home:e,platformName:t,env:n},i=sr(r),a=ar(r),o=[{kind:`remove-path`,group:`Application data`,label:`Remove ${J(i,e)}`,path:i}];if(t===`darwin`&&s()===`stable`){let t=sr({...r,productName:ir});o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${J(t,e)} (only if it is OpenKnowledge's)`,path:t,requireOurState:!0})}return o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${J(a,e)}`,path:a}),o}async function Yc(e,t={}){if(t.stopServer!==void 0&&t.scanProcesses!==void 0)throw Error(`runRemoval received both stopServer and scanProcesses. scanProcesses only parameterizes the default stopServer, so a supplied stopServer never reads it and the scan would never run. Supply stopServer to replace shutdown entirely, or scanProcesses to parameterize the default one.`);let n=t.clearToken??hi,r=t.clearEmbeddingsKey??qn,i=new Set(e.ops.flatMap(e=>e.kind===`stop-server`&&!e.preserveProjectState?[V(e.lockDir)]:[])),a=gt(),o=t.scanProcesses??(()=>Sn(a)),s,c={clearToken:n,clearEmbeddingsKey:r,stopServer:t.stopServer??(t=>zc(t,{preserveProjectState:e.scope===`uninstall`&&!i.has(V(t)),probe:a,scanProcesses:()=>s??=o()})),env:t.env??{}},l=async e=>{try{return await Zc(e,c)}catch(t){return{op:e,status:`failed`,detail:t instanceof Error?t.message:String(t)}}},u=new Map;for(let t of e.ops){if(t.kind!==`stop-server`)continue;let e=V(t.lockDir);u.has(e)||u.set(e,await l(t))}let d=[];for(let t of e.ops){if(t.kind===`stop-server`){let e=u.get(V(t.lockDir));e&&d.push({...e,op:t});continue}let e=t.requiresStoppedServers??[...u.keys()],n=e.filter(e=>{let t=u.get(V(e));return!t||t.status===`failed`});if(n.length>0){d.push({op:t,status:`blocked`,detail:`left untouched because server shutdown was not verified (${n.length} server blocker${n.length===1?``:`s`}; see the stop-server failures).`});continue}if(t.kind===`remove-path`&&t.requiresSuccessfulCleanup&&d.some(n=>n.status!==`failed`&&n.status!==`blocked`?!1:!t.requiresStoppedServers||n.op.requiresStoppedServers?.some(t=>e.includes(t)))){d.push({op:t,status:`blocked`,detail:`left untouched so cleanup can be retried after the earlier failures are resolved`});continue}d.push(await l(t))}return{results:d,removed:d.filter(e=>e.status===`removed`),failed:d.filter(e=>e.status===`failed`||e.status===`blocked`)}}async function Xc(e,t=Sr){let n=[];for(let r of e.ops){if(r.kind!==`stop-server`)continue;let e=await t(r.lockDir);e!==null&&e!==0&&n.push(`${e} collaboration client${e===1?``:`s`} (editor window${e===1?``:`s`} or agents) ${e===1?`is`:`are`} connected to the server at ${r.lockDir}. Those windows will stop working, and restarting will NOT recover them — this removes the project state they depend on.`)}return n}async function Zc(e,t){switch(e.kind){case`stop-server`:{let{stopped:n,failed:r,skipped:i}=await t.stopServer(e.lockDir);return r.length>0?{op:e,status:`failed`,detail:`could not stop the server (${r.map(e=>`pid ${e.pid}: ${e.error}`).join(`; `)}); dependent files were left untouched; stop the server and retry cleanup`}:i?{op:e,status:`skipped`,detail:i}:{op:e,status:n>0?`removed`:`not-present`}}case`keychain-token`:{let{touched:n,keychainError:r}=await t.clearToken(e.host);return r?{op:e,status:`failed`,detail:`keychain unreachable (${r}); remove manually: Keychain Access → service "${_().keyringService}"`}:{op:e,status:n.length>0?`removed`:`not-present`}}case`embeddings-key`:{let{touched:n}=await t.clearEmbeddingsKey();return{op:e,status:n.length>0?`removed`:`not-present`}}case`shell-block`:{let t=Ri(e.rcFile);if(t.kind===`not-present`)return{op:e,status:`not-present`};if(t.kind===`declined`&&t.reason===`missing-symlink-target`)return{op:e,status:`skipped`,detail:`left the dangling shell symlink untouched; no target file contains a PATH block to remove: ${e.rcFile}`};if(t.kind===`declined`)return{op:e,status:`failed`,detail:`${Qc(t.reason)}: ${e.rcFile}`};let n;try{n=W(t.path,`utf-8`)}catch(t){return{op:e,status:`failed`,detail:`${Qc(Zr(t))}: ${e.rcFile}`}}let{text:r,changed:i,emptyAfter:a}=dr(n);return i?a&&!t.symlink?(G(e.rcFile,{force:!0}),{op:e,status:`removed`,detail:`file removed (was OK-owned)`}):(Br(t.path,r,{mode:li(t.path)}),{op:e,status:`removed`}):{op:e,status:`not-present`}}case`extra-symlink`:return wr(e.path,e.target)?(ta(e.path),{op:e,status:`removed`}):{op:e,status:`not-present`};case`mcp-entry`:{let n=Ai(ai[e.editorId],e.cwd,e.home,e.configPath,t.env);switch(n.kind){case`removed`:return n.trustDetail?{op:e,status:`removed`,detail:n.trustDetail}:{op:e,status:`removed`};case`not-present`:return{op:e,status:`not-present`};case`left-foreign`:return{op:e,status:`skipped`,detail:`left a non-OK server in place`};case`declined`:if(n.reason===`missing-symlink-target`){let t=e.configPath;return e.editorId===`pi`?{op:e,status:`failed`,detail:`Pi bridge configuration left untouched (missing symlink target); Pi's separate folder trust grant has not been checked or removed. Restore the missing target of the OpenKnowledge bridge symlink at ${t}, or repoint that symlink to the intended bridge file, then retry cleanup`}:{op:e,status:`skipped`,detail:`left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${t}`}}return{op:e,status:`failed`,detail:Qc(n.reason)};default:throw Error(`unhandled mcp-remove outcome: ${n.kind}`)}}case`launch-entry`:{let t=zi(e.projectRoot);switch(t.kind){case`removed`:return{op:e,status:`removed`};case`not-present`:return{op:e,status:`not-present`};case`declined`:return t.reason===`missing-symlink-target`?{op:e,status:`skipped`,detail:`left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${z(e.projectRoot,`.claude`,`launch.json`)}`}:{op:e,status:`failed`,detail:Qc(t.reason)};default:throw Error(`unhandled launch-remove outcome: ${t.kind}`)}}case`git-exclude`:{let t=qr(e.projectRoot,tl(e.projectRoot));if(t.kind===`no-exclude`)switch(t.reason){case`inaccessible`:return{op:e,status:`failed`,detail:`could not write .git/info/exclude (inaccessible)`};case`malformed-pointer`:return{op:e,status:`failed`,detail:`could not locate .git/info/exclude; repair the .git pointer at ${z(e.projectRoot,`.git`)} by restoring permissions or access to its repository, including any mounted volume. If its contents are malformed, restore a valid gitdir: <path> line pointing to the existing Git directory. For a linked worktree, run git worktree repair from the main repository with this worktree's path. If the repository is permanently gone, back up and remove only the stale .git pointer file, then retry cleanup`};case`no-git`:case`no-info-dir`:return{op:e,status:`not-present`}}return{op:e,status:t.removed.length>0?`removed`:`not-present`}}case`remove-path`:return $c(e)}}function Qc(e){switch(e){case`permission-denied`:case`missing-symlink-target`:case`unresolved-symlink`:case`not-a-file`:case`unreadable`:case`disappeared`:return`configuration left untouched: ${Xr(e)}`;case`oversize`:return`configuration left untouched (file is too large to edit safely); back up the file and reduce its size to 10 MiB or less while preserving needed settings, then retry cleanup`;case`duplicate-container`:return`configuration left untouched (duplicate server configuration blocks); combine the duplicate blocks while preserving their settings, then retry cleanup`;case`no-native-writer`:return`configuration left untouched (this install has no format-preserving TOML writer); remove the OpenKnowledge entry manually or reinstall OpenKnowledge, then retry cleanup`;case`unparseable`:return`configuration left untouched (unparseable); repair it and retry cleanup`;default:throw Error(`unhandled configuration decline reason: ${e}`)}}function $c(e){if(e.requireOurState&&!nr(e.path))return{op:e,status:`skipped`,detail:`not verified as OpenKnowledge — left untouched`};e.containWithin&&Yr(e.path,e.containWithin);let t;try{t=Xi(e.path)}catch(e){if(e.code!==`ENOENT`)throw e}return t?t.isSymbolicLink()?(ta(e.path),{op:e,status:`removed`}):e.preserve&&e.preserve.length>0?{op:e,status:el(e.path,e.preserve)?`removed`:`not-present`}:(G(e.path,{recursive:!0,force:!0}),{op:e,status:`removed`}):{op:e,status:`not-present`}}function el(e,t){let n=!1;for(let r of Qi(e)){if(t.includes(r))continue;let i=z(e,r),a=t.flatMap(e=>e.startsWith(`${r}/`)?[e.slice(r.length+1)]:[]);if(a.length>0&&Xi(i).isDirectory()){el(i,a)&&(n=!0);continue}G(i,{recursive:!0,force:!0}),n=!0}return n}function tl(e){let t=new Set([z(e,`.claude`,`launch.json`)]);for(let n of ii){let r=ai[n].projectConfigPath?.(e);r&&t.add(r)}return Gr(e).filter(n=>{let r=z(e,n);if(!t.has(r))return!0;try{return Xi(r),!1}catch(e){if(e.code===`ENOENT`)return!0;throw e}})}function nl(e){let t=new Map;for(let n of e){let e=t.get(n.group)??[];e.push(n),t.set(n.group,e)}return t}function rl(e){if(e.ops.length===0)return N(`Nothing to remove.`);let t=[];for(let[n,r]of nl(e.ops)){t.length>0&&t.push(``),t.push(L(`${n}:`));for(let e of r)t.push(` ${I(`-`)} ${e.label}`)}return t.join(`
17
+ `)}function Fc(e){return`${F(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Ic(e={}){let t=await tn(e);return t.status===`failed`?{...t,message:Fc(t),exitCode:1}:t.status===`skip-current`?{...t,message:Nc(t),exitCode:0}:t.status===`installed`?{...t,message:Pc(t),exitCode:0}:{...t,message:Mc(t),exitCode:0}}function Lc(){return new j(`cowork`).description(`Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. (Advanced/rarely needed — \`${l()} init\` already wires Claude.)`).option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).option(`--force`,`Bypass the install-state gate and rebuild unconditionally`).action(async e=>{let t=await Ic({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}async function Rc(e,t){let n=ga({input:t??process.stdin,output:process.stderr});try{let t=(await n.question(e)).trim().toLowerCase();return t===`y`||t===`yes`}finally{n.close()}}async function zc(e,t={}){let n=t.probe??gt(),r=t.isAlive??(e=>fn(e,n(e))),i=t.isAlive??sn,a=t.platform??process.platform,o=(e,n)=>(t.readProcessStart??Cr)(e,{platform:a,onNativeFailure:n}),s=lr(e,`server`,{isAlive:r,readProcessStart:o}),c=`Quit OpenKnowledge and stop any OpenKnowledge server processes. Once you have confirmed they have exited, remove the stale lock file at ${s.lockPath} and retry cleanup.`,l=()=>{switch(s.status){case`alive`:case`dead-pid`:case`reused-pid`:case`foreign-host`:return s.lock.pid;case`unverified-owner`:return s.pid;case`missing`:case`corrupt`:case`read-error`:return;default:return s}},u=()=>{let t=l();return{...t===void 0?{}:{lockPid:t},lockDir:e,lockPath:s.lockPath,status:s.status}},d=e=>(gi()?.warn(u(),e),Error(e));if(s.status===`read-error`)throw d(`Cannot read the server lock at ${s.lockPath}: ${s.error}. Restore file and parent-directory access, then retry cleanup.`);let f=s.status===`unverified-owner`||s.status===`foreign-host`||s.status===`corrupt`&&s.foreignHost===!0?s:null,p=f!==null&&f.status!==`unverified-owner`;if(f!==null&&!t.preserveProjectState)throw d(jr(f));if(s.status===`dead-pid`)return{stopped:0,failed:[],skipped:`Skipped stale lock at ${s.lockPath}; its recorded local process ${s.lock.pid} has exited. No server was stopped.`};if(s.status===`reused-pid`)return{stopped:0,failed:[],skipped:`Skipped stale lock at ${s.lockPath}; its recorded process ${s.lock.pid} has exited and that process ID now belongs to another program, which was not signalled. No server was stopped.`};if(s.status===`corrupt`||s.status===`foreign-host`||s.status===`unverified-owner`){let i=s.status===`unverified-owner`,a=i?`unverified`:p?`foreign-owned`:`malformed`,o=await(t.scanProcesses??(()=>Sn(n)))(),l=await oa(e).catch(()=>V(e)),u=o.candidates.filter(e=>e.lockDir===l&&r(e.pid));if(u.length>0)throw d(`Cannot verify shutdown from the ${a} lock at ${s.lockPath}: live process candidates ${u.map(e=>`${e.pid} (${e.source})`).join(`, `)}. No process was signalled. ${c}`);if(o.unavailable.length>0)throw d(`Cannot rule out a live server for ${s.lockPath}: ${o.unavailable.join(`; `)}. Restore process-inspection access and retry cleanup. ${c}`);return{stopped:0,failed:[],skipped:i?`Retained project lock with an unverified owner at ${s.lockPath}; its recorded process ${s.pid} is running locally, but process and listener inspection could not attribute any server to this directory. No process was signalled. Only local application cleanup may proceed; project state is unchanged. No server was stopped.`:p?`Retained foreign-owned project lock at ${s.lockPath}; process and listener inspection found no local server candidate for this directory. Only local application cleanup may proceed; project state is unchanged. No server was stopped.`:`Skipped malformed lock at ${s.lockPath}; process and listener inspection found no live server candidate for this directory. No server was stopped.`}}let m=await Tr({lockDir:e,inspect:()=>s,isAlive:r,readProcessStart:(e,t)=>o(e,t?.onNativeFailure),platform:a,force:!0,refuseHolderStartedAfterLock:!0,log:()=>{},error:()=>{}}),h=m.failed.find(e=>e.unverified!==void 0)?.unverified;if(h!==void 0)switch(h.cause){case`foreign-host`:throw Error(jr({status:`foreign-host`,lockPath:h.lockPath,lock:h.lock}));case`unverified-owner`:throw Error(jr({status:`unverified-owner`,lockPath:h.lockPath,pid:h.pid}));default:throw Error(Dr(h,`it was not signalled.`,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${h.lockPath} and retry cleanup.`,gi()!==void 0))}let g=m.failed.map(e=>({pid:e.target.pid,error:e.error})),_=new Set(m.stopped.map(e=>e.pid)),v=t.timeoutMs??1e4,y=performance.now()+v;for(;_.size>0;){for(let e of _)i(e)||_.delete(e);if(_.size===0)break;let e=y-performance.now();if(e<=0)break;await ma(Math.min(t.pollIntervalMs??50,e))}for(let e of _)r(e)||_.delete(e);for(let e of _)g.push({pid:e,error:`still running ${v}ms after SIGTERM`});return{stopped:m.stopped.length-_.size,failed:g}}function Bc(e){return e?ze.filter(e=>e!==Pe):[...ze]}function Vc(e){return Bc(e).map(e=>`~/.ok/${e}`).join(`, `)}function J(e,t){return e===t?`~`:e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Hc(e){return Wi===`/`?e:e.split(Wi).join(`/`)}function Uc(e,t,n=`This project`){let r=[],i=[O(e)],a=z(e,`.ok`);Ri(z(a,`server.lock`)).kind!==`not-present`&&i.push(a);for(let e of i)r.push({kind:`stop-server`,group:n,label:e===a?`Check the legacy project server lock`:`Stop the project server (if running)`,lockDir:e});let o=new Set;for(let i of ii){let a=ai[i];if(!a.projectConfigPath)continue;let s=a.projectConfigPath(e);o.add(Hc(B(e,s))),r.push({kind:`mcp-entry`,group:n,label:`Remove OK's MCP entry from ${a.label} (${Hc(B(e,s))})`,editorId:i,scope:`project`,cwd:e,home:t,configPath:s})}r.push({kind:`launch-entry`,group:n,label:`Remove OK's entry from .claude/launch.json`,projectRoot:e}),r.push({kind:`git-exclude`,group:n,label:`Remove OK paths from .git/info/exclude`,projectRoot:e});let s=new Set([...Gr(e),...ri(e),...Ge]);for(let t of s){let i=t.replace(/\/$/,``);o.has(i)||i!==`.claude/launch.json`&&r.push({kind:`remove-path`,group:n,label:`Remove ${t}`,path:z(e,i),containWithin:e})}try{r.push({kind:`remove-path`,group:n,label:`Remove the OK shadow repo (.git/ok/)`,path:An(e)})}catch{}let c=z(e,`.ok`);return r.sort((e,t)=>Number(e.kind===`remove-path`&&e.path===c)-Number(t.kind===`remove-path`&&t.path===c)),r.map(e=>e.kind===`stop-server`?e:{...e,requiresStoppedServers:i,...e.kind===`remove-path`?{requiresSuccessfulCleanup:!0}:{}})}function Wc(e,t){return{scope:`deinit`,ops:Uc(e,t)}}function Gc(e){let{home:t,platform:n,host:r,lockDirs:i,marker:a,recentDeinitProjectRoots:o,purgeContent:s}=e,c=[];for(let e of i)c.push({kind:`stop-server`,group:`Running servers`,label:`Stop server at ${J(z(e,`..`,`..`),t)}`,lockDir:e,preserveProjectState:!0});c.push({kind:`keychain-token`,group:`Credentials`,label:`Remove the GitHub credential (${r}) from the OS keychain + ${v}`,host:r}),c.push({kind:`embeddings-key`,group:`Credentials`,label:`Remove all embeddings API keys (${m})`}),c.push(...qc(a,t));for(let e of ii){let n=ai[e],r;try{r=n.configPath(``,t)}catch{continue}c.push({kind:`mcp-entry`,group:`Editor MCP configs`,label:`Remove OK's MCP entry from ${n.label} (${J(r,t)})`,editorId:e,scope:`user`,cwd:t,home:t,configPath:r})}for(let e of hr(t))c.push({kind:`remove-path`,group:`Skill bundles`,label:`Remove ${J(e.path,t)}`,path:e.path});for(let e of o)c.push(...Uc(e,t,`Project: ${Vi(e)}`));c.push(...Jc(t,n,e.env).map(e=>e.kind===`remove-path`?{...e,requiresSuccessfulCleanup:!0}:e));let{userHomeDirName:l}=_();return l===`.ok`?c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:s?`Remove ~/.ok (including user-authored skills; keeping ${Vc(!0)}, shared by every channel)`:`Remove ~/.ok (keeping ${Vc(!1)}, shared by every channel)`,path:Hr(t),preserve:Bc(s)}):(c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:s?`Remove ~/${l}`:`Remove ~/${l} (keeping ~/.ok/${Pe}, shared by every channel)`,path:Hr(t)}),s&&c.push({kind:`remove-path`,group:`Global directory`,requiresSuccessfulCleanup:!0,label:`Remove ~/.ok/${Pe} (user-authored skills, shared by every channel)`,path:z(t,`.ok`,Pe)})),{scope:`uninstall`,ops:c}}function Kc(e){return[z(e,`.zshrc`),z(e,`.bash_profile`),z(e,`.config`,`fish`,`conf.d`,_r())]}function qc(e,t){let n=[],r=new Set([...Kc(t),...e?.rcFiles??[]]);for(let e of r)Ri(e).kind!==`not-present`&&n.push({kind:`shell-block`,group:`Shell PATH`,label:`Strip the OK block from ${J(e,t)}`,rcFile:e});for(let r of e?.extraSymlinks??[])n.push({kind:`extra-symlink`,group:`Shell PATH`,label:`Remove the ok symlink at ${J(r.path,t)}`,path:r.path,target:r.target});return n}function Jc(e,t,n){let r={home:e,platformName:t,env:n},i=sr(r),a=ar(r),o=[{kind:`remove-path`,group:`Application data`,label:`Remove ${J(i,e)}`,path:i}];if(t===`darwin`&&s()===`stable`){let t=sr({...r,productName:ir});o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${J(t,e)} (only if it is OpenKnowledge's)`,path:t,requireOurState:!0})}return o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${J(a,e)}`,path:a}),o}async function Yc(e,t={}){if(t.stopServer!==void 0&&t.scanProcesses!==void 0)throw Error(`runRemoval received both stopServer and scanProcesses. scanProcesses only parameterizes the default stopServer, so a supplied stopServer never reads it and the scan would never run. Supply stopServer to replace shutdown entirely, or scanProcesses to parameterize the default one.`);let n=t.clearToken??hi,r=t.clearEmbeddingsKey??qn,i=new Set(e.ops.flatMap(e=>e.kind===`stop-server`&&!e.preserveProjectState?[V(e.lockDir)]:[])),a=gt(),o=t.scanProcesses??(()=>Sn(a)),s,c={clearToken:n,clearEmbeddingsKey:r,stopServer:t.stopServer??(t=>zc(t,{preserveProjectState:e.scope===`uninstall`&&!i.has(V(t)),probe:a,scanProcesses:()=>s??=o()})),env:t.env??{}},l=async e=>{try{return await Zc(e,c)}catch(t){return{op:e,status:`failed`,detail:t instanceof Error?t.message:String(t)}}},u=new Map;for(let t of e.ops){if(t.kind!==`stop-server`)continue;let e=V(t.lockDir);u.has(e)||u.set(e,await l(t))}let d=[];for(let t of e.ops){if(t.kind===`stop-server`){let e=u.get(V(t.lockDir));e&&d.push({...e,op:t});continue}let e=t.requiresStoppedServers??[...u.keys()],n=e.filter(e=>{let t=u.get(V(e));return!t||t.status===`failed`});if(n.length>0){d.push({op:t,status:`blocked`,detail:`left untouched because server shutdown was not verified (${n.length} server blocker${n.length===1?``:`s`}; see the stop-server failures).`});continue}if(t.kind===`remove-path`&&t.requiresSuccessfulCleanup&&d.some(n=>n.status!==`failed`&&n.status!==`blocked`?!1:!t.requiresStoppedServers||n.op.requiresStoppedServers?.some(t=>e.includes(t)))){d.push({op:t,status:`blocked`,detail:`left untouched so cleanup can be retried after the earlier failures are resolved`});continue}d.push(await l(t))}return{results:d,removed:d.filter(e=>e.status===`removed`),failed:d.filter(e=>e.status===`failed`||e.status===`blocked`)}}async function Xc(e,t=Sr){let n=[];for(let r of e.ops){if(r.kind!==`stop-server`)continue;let e=await t(r.lockDir);e!==null&&e!==0&&n.push(`${e} collaboration client${e===1?``:`s`} (editor window${e===1?``:`s`} or agents) ${e===1?`is`:`are`} connected to the server at ${r.lockDir}. Those windows will stop working, and restarting will NOT recover them — this removes the project state they depend on.`)}return n}async function Zc(e,t){switch(e.kind){case`stop-server`:{let{stopped:n,failed:r,skipped:i}=await t.stopServer(e.lockDir);return r.length>0?{op:e,status:`failed`,detail:`could not stop the server (${r.map(e=>`pid ${e.pid}: ${e.error}`).join(`; `)}); dependent files were left untouched; stop the server and retry cleanup`}:i?{op:e,status:`skipped`,detail:i}:{op:e,status:n>0?`removed`:`not-present`}}case`keychain-token`:{let{touched:n,keychainError:r}=await t.clearToken(e.host);return r?{op:e,status:`failed`,detail:`keychain unreachable (${r}); remove manually: Keychain Access → service "${_().keyringService}"`}:{op:e,status:n.length>0?`removed`:`not-present`}}case`embeddings-key`:{let{touched:n}=await t.clearEmbeddingsKey();return{op:e,status:n.length>0?`removed`:`not-present`}}case`shell-block`:{let t=Ri(e.rcFile);if(t.kind===`not-present`)return{op:e,status:`not-present`};if(t.kind===`declined`&&t.reason===`missing-symlink-target`)return{op:e,status:`skipped`,detail:`left the dangling shell symlink untouched; no target file contains a PATH block to remove: ${e.rcFile}`};if(t.kind===`declined`)return{op:e,status:`failed`,detail:`${Qc(t.reason)}: ${e.rcFile}`};let n;try{n=W(t.path,`utf-8`)}catch(t){return{op:e,status:`failed`,detail:`${Qc(Zr(t))}: ${e.rcFile}`}}let{text:r,changed:i,emptyAfter:a}=dr(n);return i?a&&!t.symlink?(G(e.rcFile,{force:!0}),{op:e,status:`removed`,detail:`file removed (was OK-owned)`}):(Br(t.path,r,{mode:li(t.path)}),{op:e,status:`removed`}):{op:e,status:`not-present`}}case`extra-symlink`:return wr(e.path,e.target)?(ta(e.path),{op:e,status:`removed`}):{op:e,status:`not-present`};case`mcp-entry`:{let n=Ai(ai[e.editorId],e.cwd,e.home,e.configPath,t.env);switch(n.kind){case`removed`:return n.trustDetail?{op:e,status:`removed`,detail:n.trustDetail}:{op:e,status:`removed`};case`not-present`:return{op:e,status:`not-present`};case`left-foreign`:return{op:e,status:`skipped`,detail:`left a non-OK server in place`};case`declined`:if(n.reason===`missing-symlink-target`){let t=e.configPath;return e.editorId===`pi`?{op:e,status:`failed`,detail:`Pi bridge configuration left untouched (missing symlink target); Pi's separate folder trust grant has not been checked or removed. Restore the missing target of the OpenKnowledge bridge symlink at ${t}, or repoint that symlink to the intended bridge file, then retry cleanup`}:{op:e,status:`skipped`,detail:`left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${t}`}}return{op:e,status:`failed`,detail:Qc(n.reason)};default:throw Error(`unhandled mcp-remove outcome: ${n.kind}`)}}case`launch-entry`:{let t=zi(e.projectRoot);switch(t.kind){case`removed`:return{op:e,status:`removed`};case`not-present`:return{op:e,status:`not-present`};case`declined`:return t.reason===`missing-symlink-target`?{op:e,status:`skipped`,detail:`left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${z(e.projectRoot,`.claude`,`launch.json`)}`}:{op:e,status:`failed`,detail:Qc(t.reason)};default:throw Error(`unhandled launch-remove outcome: ${t.kind}`)}}case`git-exclude`:{let t=qr(e.projectRoot,tl(e.projectRoot));if(t.kind===`no-exclude`)switch(t.reason){case`inaccessible`:return{op:e,status:`failed`,detail:`could not write .git/info/exclude (inaccessible)`};case`malformed-pointer`:return{op:e,status:`failed`,detail:`could not locate .git/info/exclude; repair the .git pointer at ${z(e.projectRoot,`.git`)} by restoring permissions or access to its repository, including any mounted volume. If its contents are malformed, restore a valid gitdir: <path> line pointing to the existing Git directory. For a linked worktree, run git worktree repair from the main repository with this worktree's path. If the repository is permanently gone, back up and remove only the stale .git pointer file, then retry cleanup`};case`no-git`:case`no-info-dir`:return{op:e,status:`not-present`}}return{op:e,status:t.removed.length>0?`removed`:`not-present`}}case`remove-path`:return $c(e)}}function Qc(e){switch(e){case`permission-denied`:case`missing-symlink-target`:case`unresolved-symlink`:case`not-a-file`:case`unreadable`:case`disappeared`:return`configuration left untouched: ${Xr(e)}`;case`oversize`:return`configuration left untouched (file is too large to edit safely); back up the file and reduce its size to 10 MiB or less while preserving needed settings, then retry cleanup`;case`duplicate-container`:return`configuration left untouched (duplicate server configuration blocks); combine the duplicate blocks while preserving their settings, then retry cleanup`;case`no-native-writer`:return`configuration left untouched (this install has no format-preserving TOML writer); remove the OpenKnowledge entry manually or reinstall OpenKnowledge, then retry cleanup`;case`unparseable`:return`configuration left untouched (unparseable); repair it and retry cleanup`;default:throw Error(`unhandled configuration decline reason: ${e}`)}}function $c(e){if(e.requireOurState&&!nr(e.path))return{op:e,status:`skipped`,detail:`not verified as OpenKnowledge — left untouched`};e.containWithin&&Yr(e.path,e.containWithin);let t;try{t=Xi(e.path)}catch(e){if(e.code!==`ENOENT`)throw e}return t?t.isSymbolicLink()?(ta(e.path),{op:e,status:`removed`}):e.preserve&&e.preserve.length>0?{op:e,status:el(e.path,e.preserve)?`removed`:`not-present`}:(G(e.path,{recursive:!0,force:!0}),{op:e,status:`removed`}):{op:e,status:`not-present`}}function el(e,t){let n=!1;for(let r of Qi(e)){if(t.includes(r))continue;let i=z(e,r),a=t.flatMap(e=>e.startsWith(`${r}/`)?[e.slice(r.length+1)]:[]);if(a.length>0&&Xi(i).isDirectory()){el(i,a)&&(n=!0);continue}G(i,{recursive:!0,force:!0}),n=!0}return n}function tl(e){let t=new Set([z(e,`.claude`,`launch.json`)]);for(let n of ii){let r=ai[n].projectConfigPath?.(e);r&&t.add(r)}return Gr(e).filter(n=>{let r=z(e,n);if(!t.has(r))return!0;try{return Xi(r),!1}catch(e){if(e.code===`ENOENT`)return!0;throw e}})}function nl(e){let t=new Map;for(let n of e){let e=t.get(n.group)??[];e.push(n),t.set(n.group,e)}return t}function rl(e){if(e.ops.length===0)return N(`Nothing to remove.`);let t=[];for(let[n,r]of nl(e.ops)){t.length>0&&t.push(``),t.push(L(`${n}:`));for(let e of r)t.push(` ${I(`-`)} ${e.label}`)}return t.join(`
18
18
  `)}function il(e){return e.replaceAll(`
19
19
  `,`
20
20
  `)}function al(e){let t=e.removed.length,n=e.failed.filter(e=>e.status!==`blocked`),r=e.results.filter(e=>e.status===`blocked`),i=n.length,a=e.results.filter(e=>e.status===`not-present`).length,o=e.results.filter(e=>e.status===`skipped`),s=[];s.push(e.failed.length>0?I(`Removed ${t} item${t===1?``:`s`}, ${i} could not be removed.`):P(`✓ Removed ${t} item${t===1?``:`s`}.`)),r.length>0&&s.push(I(` ${r.length} dependent items left untouched; resolve the failures below and retry.`)),a>0&&s.push(N(` ${a} already absent.`));for(let t of e.removed)t.detail!==void 0&&s.push(` ${I(`·`)} ${t.op.label} — ${N(il(t.detail))}`);for(let e of o)s.push(` ${I(`·`)} ${e.op.kind===`stop-server`?`Skipped`:`Left in place`}: ${e.op.label}${e.detail?` — ${N(il(e.detail))}`:``}`);if(i>0){s.push(``),s.push(F(`Could not remove:`));for(let e of n)s.push(` ${F(`✗`)} ${e.op.label}${e.detail?` — ${il(e.detail)}`:``}`)}return s.join(`
@@ -43,7 +43,7 @@ ws.addEventListener('error', () => process.exit(1));
43
43
  setTimeout(() => process.exit(2), ${t+1e4});
44
44
  `),i}async function Rl(e,t,n,r,i){let a=Ll(e,t,z(r,`cpu.cpuprofile`)),o=!1,s=fa(process.execPath,[a],k({stdio:`ignore`})),c=setInterval(()=>{let e=Nl(n);e&&i(e)},1e3);await new Promise(e=>{s.once(`close`,t=>{o=t===0,e()}),setTimeout(()=>{s.kill(),e()},t+12e3)}),clearInterval(c);try{G(z(a,`..`),{recursive:!0,force:!0})}catch{}return o}function zl(e){let t;try{t=JSON.parse(e)}catch{return`(could not parse profile)`}let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map;for(let e of t.nodes)for(let t of e.children??[])r.set(t,e.id);let i=new Map;for(let e of t.samples??[])i.set(e,(i.get(e)??0)+1);let a=t.samples?.length??0,o=t.endTime!=null&&t.startTime!=null?((t.endTime-t.startTime)/1e3).toFixed(2):`?`,s=[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10),c=[`samples ${a} duration_ms ${o}`,``,`Top leaf nodes`];for(let[e,t]of s){let r=n.get(e);if(!r)continue;let i=a>0?(t/a*100).toFixed(1):`0.0`,{functionName:o,url:s,lineNumber:l,columnNumber:u}=r.callFrame;c.push(` ${t} ${i}% id=${e} ${o||`(anonymous)`} ${s}:${l}:${u} hit=${r.hitCount??0}`)}c.push(``,`Top stacks`);let l=e=>{let t=[],i=e;for(;i!=null;){let e=n.get(i);if(!e)break;let{functionName:a,url:o,lineNumber:s,columnNumber:c}=e.callFrame;t.unshift(` ${a||`(anonymous)`} ${o} ${s} ${c}`),i=r.get(i)}return t};for(let[e,t]of s.slice(0,5)){let n=a>0?(t/a*100).toFixed(1):`0.0`;c.push(``,`--- ${t} ${n}%`,...l(e))}return c.join(`
45
45
  `)}async function Bl(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??Mn,s=t.inspect??(e=>lr(e,`server`)),c=t.resolveCommand??dt,l=t.resolveUsage??Gt,u=t.collectLsofFn??Pl,d=t.getEndpoints??Il,f=t.profiler??Rl,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(Y.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e);if(t.status!==`missing`&&t.status!==`corrupt`&&t.status!==`read-error`&&t.status!==`unverified-owner`&&t.status!==`reused-pid`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let b=new Date().toISOString().replace(/[:.]/g,`-`),x=e.output?e.output:v?z(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):z(process.cwd(),`ok-diagnose-${n}-${b}`);try{U(x,{recursive:!0})}catch(e){a(Y.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(Y.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{na(z(x,e),t),a(` wrote ${e}`)},C=c(n),ee=l(n);S(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:C,usage:ee,lockInfo:y},null,2)),a(` sampling lsof`);let w=u(n);if(w&&S(`lsof.txt`,w),!i){let e=w?Fl(w).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(Y.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){S(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,x,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(Y.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
46
- `)}\n`);try{S(`stacks.txt`,zl(W(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(Y.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(Y.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(Y.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${Y.default.bold(x)}`)}async function Vl(e){let t=ga({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Hl(e){let t=Zi(z(aa(),`ok-bundle-process-`));return await Bl({pid:e,output:t}),t}function Ul(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Wl(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Gl(e){let{summary:t,manifest:n}=e;return t.redacted?t.contentDirVisible?`masked as <CONTENT_DIR>, but still present in some files`:`masked as <CONTENT_DIR>`:t.contentDirVisible?`visible (${n.contentDir.absolutePath})`:`not present`}function Kl(e,t){let n=e.manifest.redaction.secretScrub;return n===void 0?Y.default.yellow(t>0?`NOT scrubbed (--no-redact): tokens and keys ship verbatim, crash reports excepted`:`NOT scrubbed (--no-redact): tokens and keys ship verbatim`):`scrubbed known credential formats (${n.redactedLineCount} line(s) across ${n.redactions.length} file(s))`}function ql(e,t,n,r,i){let{summary:a,manifest:o}=t;e(``),e(Y.default.bold(`ok diagnose bundle — what leaves this machine`)),e(``),e(` Files: ${a.fileCount}`),e(` Total size: ${Ul(a.totalBytes)} uncompressed`),e(` Document names: included in cleartext (${a.docNameCount} doc.name occurrence(s) in telemetry)`),e(` Content-dir path: ${Gl(t)}`),e(` Credentials: ${Kl(t,a.stagedDiagnosticReports)}`),e(` Server status: ${o.serverStatus}`),e(` macOS crash reports: ${yr(r,a.stagedDiagnosticReports)}`),a.stagedDiagnosticReports>0&&(e(` each carrying machine details macOS puts in every report: the`),e(` account uid, the Mac model, and the name of the process that`),e(` launched this app, which on a managed machine can be internal`),e(` tooling.`),e(` Rewritten on the way in: escaped path separators normalised so`),e(` the scrub can read them, and the identifiers that would link`),e(` this machine's bundles to each other replaced.`),e(` Not byte-identical to the files macOS wrote, on any tier and`),e(` regardless of --no-redact. A report of ours still names the`),e(` processes it was running alongside.`)),e(` OS termination log: ${br(i)}`),e(` Output: ${n}`),e(``)}async function Jl(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Vl,i=t.runProcessDiagnose??Hl,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=R(o);if(!H(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);U(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(Y.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=e.redact!==!1,l=Qn(t.diagnosticReportsDir??z(ra(),`Library`,`Logs`,`DiagnosticReports`),a()),u=await or(t.osTerminationEvidenceDeps),d=await Ar({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:c,scrubSecrets:c,diagnosticReports:l,osTerminationEvidence:u,deps:t.collectDeps});try{return d.manifest.serverStatus===`not-running`&&n(Y.default.yellow(` server not running — live state unavailable`)),ql(n,d,o,l,u),e.yes!==!0&&!Wl(await r(`Write bundle? [y/N]: `))?(n(Y.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await ur({collected:d,outputPath:o}),n(Y.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(d.cleanup(),s!==void 0)try{G(s,{recursive:!0,force:!0})}catch{}}}function Yl(){let e=new j(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(Y.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(Y.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Bl({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Ml()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,`Include \`${l()} diagnose process <pid>\` output under process/ in the bundle`).option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--no-redact`,`Write a raw bundle: skip credential scrubbing and content-dir path masking`).option(`--redact`,`Scrub credentials and mask the content-dir path (the default)`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(Y.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-CIxtIlMB.mjs`),{resolveContentDir:r}=await import(`./dist-eiP2xn_A.mjs`),i=process.cwd(),{config:a}=n(i);await Jl({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(Y.default.red(t)),process.exit(1)}}),e}async function Xl(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await go({message:`Enter embeddings provider API key:`})).trim()}function Zl(e){return xn(e)}async function Ql(e,t){let n=await St(Xn(),e,t);return n.apiKey?{present:!0,notRequired:!1,source:n.source}:{present:!1,notRequired:n.keyless,source:null}}async function $l(e){try{let t=en(O(e));if(!t||t.port<=0||!sn(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=ye.safeParse(await n.json());return r.success?r.data:null}catch{return null}}function eu(e,t){if(!e)return`unavailable (search stays lexical)`;let n=Re(t);return n===`restart_required`?`RESTART REQUIRED (provider vector dimensions changed repeatedly)`:n===`incapable`?`CONFIGURATION ERROR (remove search.semantic.dimensions to use the model's own size)`:n===`provider_error`?t?.providerErrorReason===`warm`?`temporarily unavailable (provider initialization failed)`:t?.providerErrorReason===`corpus`?`partially unavailable (corpus indexing requests failed)`:t?.providerErrorReason===`query`?`temporarily unavailable (query embedding failed)`:`temporarily unavailable (provider error)`:`AVAILABLE`}function tu(){return new j(`set-key`).description(`Store the embeddings API key for THIS project's configured endpoint`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async e=>{let t=await Xl();if(!t){process.stderr.write(`No key provided.
46
+ `)}\n`);try{S(`stacks.txt`,zl(W(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(Y.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(Y.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(Y.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${Y.default.bold(x)}`)}async function Vl(e){let t=ga({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Hl(e){let t=Zi(z(aa(),`ok-bundle-process-`));return await Bl({pid:e,output:t}),t}function Ul(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Wl(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Gl(e){let{summary:t,manifest:n}=e;return t.redacted?t.contentDirVisible?`masked as <CONTENT_DIR>, but still present in some files`:`masked as <CONTENT_DIR>`:t.contentDirVisible?`visible (${n.contentDir.absolutePath})`:`not present`}function Kl(e,t){let n=e.manifest.redaction.secretScrub;return n===void 0?Y.default.yellow(t>0?`NOT scrubbed (--no-redact): tokens and keys ship verbatim, crash reports excepted`:`NOT scrubbed (--no-redact): tokens and keys ship verbatim`):`scrubbed known credential formats (${n.redactedLineCount} line(s) across ${n.redactions.length} file(s))`}function ql(e,t,n,r,i){let{summary:a,manifest:o}=t;e(``),e(Y.default.bold(`ok diagnose bundle — what leaves this machine`)),e(``),e(` Files: ${a.fileCount}`),e(` Total size: ${Ul(a.totalBytes)} uncompressed`),e(` Document names: included in cleartext (${a.docNameCount} doc.name occurrence(s) in telemetry)`),e(` Content-dir path: ${Gl(t)}`),e(` Credentials: ${Kl(t,a.stagedDiagnosticReports)}`),e(` Server status: ${o.serverStatus}`),e(` macOS crash reports: ${yr(r,a.stagedDiagnosticReports)}`),a.stagedDiagnosticReports>0&&(e(` each carrying machine details macOS puts in every report: the`),e(` account uid, the Mac model, and the name of the process that`),e(` launched this app, which on a managed machine can be internal`),e(` tooling.`),e(` Rewritten on the way in: escaped path separators normalised so`),e(` the scrub can read them, and the identifiers that would link`),e(` this machine's bundles to each other replaced.`),e(` Not byte-identical to the files macOS wrote, on any tier and`),e(` regardless of --no-redact. A report of ours still names the`),e(` processes it was running alongside.`)),e(` OS termination log: ${br(i)}`),e(` Output: ${n}`),e(``)}async function Jl(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Vl,i=t.runProcessDiagnose??Hl,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=R(o);if(!H(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);U(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(Y.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=e.redact!==!1,l=Qn(t.diagnosticReportsDir??z(ra(),`Library`,`Logs`,`DiagnosticReports`),a()),u=await or(t.osTerminationEvidenceDeps),d=await Ar({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:c,scrubSecrets:c,diagnosticReports:l,osTerminationEvidence:u,deps:t.collectDeps});try{return d.manifest.serverStatus===`not-running`&&n(Y.default.yellow(` server not running — live state unavailable`)),ql(n,d,o,l,u),e.yes!==!0&&!Wl(await r(`Write bundle? [y/N]: `))?(n(Y.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await ur({collected:d,outputPath:o}),n(Y.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(d.cleanup(),s!==void 0)try{G(s,{recursive:!0,force:!0})}catch{}}}function Yl(){let e=new j(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(Y.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(Y.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Bl({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Ml()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,`Include \`${l()} diagnose process <pid>\` output under process/ in the bundle`).option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--no-redact`,`Write a raw bundle: skip credential scrubbing and content-dir path masking`).option(`--redact`,`Scrub credentials and mask the content-dir path (the default)`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(Y.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-B_W8tqBx.mjs`),{resolveContentDir:r}=await import(`./dist-Ttulen40.mjs`),i=process.cwd(),{config:a}=n(i);await Jl({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(Y.default.red(t)),process.exit(1)}}),e}async function Xl(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await go({message:`Enter embeddings provider API key:`})).trim()}function Zl(e){return xn(e)}async function Ql(e,t){let n=await St(Xn(),e,t);return n.apiKey?{present:!0,notRequired:!1,source:n.source}:{present:!1,notRequired:n.keyless,source:null}}async function $l(e){try{let t=en(O(e));if(!t||t.port<=0||!sn(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=ye.safeParse(await n.json());return r.success?r.data:null}catch{return null}}function eu(e,t){if(!e)return`unavailable (search stays lexical)`;let n=Re(t);return n===`restart_required`?`RESTART REQUIRED (provider vector dimensions changed repeatedly)`:n===`incapable`?`CONFIGURATION ERROR (remove search.semantic.dimensions to use the model's own size)`:n===`provider_error`?t?.providerErrorReason===`warm`?`temporarily unavailable (provider initialization failed)`:t?.providerErrorReason===`corpus`?`partially unavailable (corpus indexing requests failed)`:t?.providerErrorReason===`query`?`temporarily unavailable (query embedding failed)`:`temporarily unavailable (provider error)`:`AVAILABLE`}function tu(){return new j(`set-key`).description(`Store the embeddings API key for THIS project's configured endpoint`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async e=>{let t=await Xl();if(!t){process.stderr.write(`No key provided.
47
47
  `),process.exitCode=1;return}let n=V(e.cwd??process.cwd()),{baseUrl:r}=Zl(n);try{await Xn().setForProject(n,r,t)}catch(e){process.stderr.write(`Failed to store the embeddings key: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1;return}process.stderr.write(`✓ Embeddings API key stored for ${r}\n (kept in ${h(m)}, 0600, this machine only — never in the project).\n Enable semantic search with \`${l()} embeddings enable\`, or in\n OK Desktop → Settings → This project → Search.
48
48
  `)})}function nu(){return new j(`clear-key`).description(`Remove the embeddings API key for THIS project's configured endpoint`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async e=>{let t=V(e.cwd??process.cwd()),{baseUrl:n}=Zl(t),r;try{r=await Xn().clearForProject(t,n)}catch(e){process.stderr.write(`Failed to clear the embeddings key: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1;return}if(!r){process.stderr.write(`No stored embeddings key found for ${n}.\n`);return}process.stderr.write(`✓ Embeddings API key cleared for ${n}.\n`)})}function ru(){return new j(`list`).description(`List every project + endpoint that has a stored embeddings key`).action(async()=>{let e=await Xn().listProjects();if(e.length===0){process.stderr.write(`No project embeddings keys stored.
49
49
  `);return}let t=[`Stored embeddings keys (this machine):`,``];for(let{projectKey:n,endpoints:r}of e){t.push(` ${n}`);for(let{endpoint:e,hint:n}of r)t.push(` ${e} → ${n?`••••${n}`:`set`}`)}process.stdout.write(`${t.join(`
@@ -60,7 +60,7 @@ ${a}`,d++}else Yd(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e
60
60
  `,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
61
61
  `,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Jd(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
62
62
  ${i}`,d++;return}if(Yd(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);l=r.includes(`\0`)?void 0:r;return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
63
- ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Gd(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Gd(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Jd(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Yd(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Xd=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=qd({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};const Zd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Qd=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},$d=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ju(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Zd}async _authThenStart(){if(!this._authProvider)throw new md(`No auth provider`);let e;try{e=await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new md;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Au(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Qd(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Xd({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Qt.parse(JSON.parse(e.data));Vn(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new md(`No auth provider`);if(await wd(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new md(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:mn(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Qd(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Od(o);if(this._resourceMetadataUrl=t,this._scope=n,await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new md;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Od(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Qd(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new md;return this.send(e)}}throw new Qd(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ye(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c){if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Qt.parse(e)):[Qt.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Qd(-1,`Unexpected content type: ${l}`)}else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Qd(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function ef(e){return`${e} Server.app`}function tf(e){return`${e} Helper`}ef(o),tf(o);function nf(e){let t=Ui.basename(e);return Ui.join(Ui.dirname(e),`..`,`Frameworks`,ef(t),`Contents`,`MacOS`,tf(t))}const rf=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function af(e){if(e.platform!==`darwin`||!rf.test(e.execPath))return null;let t=nf(e.execPath);return e.exists(t)?t:null}function of(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??H,a=r[1];return a?{command:af({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function sf(){return`Run \`${l()} start\` in the target project, then retry this tool. Do not fall back to native file edits for OpenKnowledge content.`}function cf(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function lf(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function uf(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function df(e,t){return`http://${uf(e)}:${t}/mcp`}function ff(e){return`${e}/mcp`}function pf(e){return e.replace(/^http/,`ws`)}function mf(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function hf(e,t){if(e&&e.draining!==!0&&t(e.pid))return Gn(e,{fallbackHost:`127.0.0.1`})??void 0}function gf(e){if(!H(e))return``;let t=Ue(W(e,`utf-8`)).trim();return t.length>8192?`…${t.slice(-8192)}`:t}function _f(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}\n${sf()}`}function vf(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function yf(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function bf(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function xf(e){let t=e.readLock??(()=>en(e.lockDir)),n=e.isAlive??sn,r=e.sleep??(e=>ha(e)),i=e.spawn??fa,a=e.readErrorLog??gf,o=e.openErrorLog??(async t=>(await Ht(e.projectDir,{authorityRegistryPath:e.authorityRegistryPath}),tt(t,process.pid))),s=e.closeFd??Ji,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return df(He,t)}let u=t(),d=hf(u,n);if(d!==void 0)return ff(d);if(e.envAutoStart===`0`)throw new ln(`OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start. ${sf()}`);if(u!==null&&u.draining===!0&&n(u.pid)){let e=Date.now(),i=e+c,a=!0;for(;Date.now()<i;){let e=t();if(e===null||e.draining!==!0||!n(e.pid)){a=!1;break}await r(l)}console.error(`[mcp-shim] waited ${Date.now()-e}ms for a draining predecessor server${a?` (timed out — proceeding anyway)`:``}`);let o=hf(t(),n);if(o!==void 0)return ff(o)}H(e.lockDir)||U(e.lockDir,{recursive:!0});let f=Ot(e.projectDir),p;try{p=await o(f)}catch(e){throw Error(`spawn failed: could not prepare server-start diagnostics: ${e instanceof Error?e.message:String(e)}\n${sf()}`,{cause:e})}let m,h,g=of();try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],windowsHide:!0,cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}\n${sf()}`)}await r(l);let e=hf(t(),n);if(e!==void 0)return ff(e)}if(h){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}\n${sf()}`)}throw Error(_f(c,a(f)))}function Sf(e,t){if(e.portOverride!==void 0)return mf(t);let n=e.readLock??(()=>en(e.lockDir)),r=e.isAlive??sn,i=hf(n(),r);if(i!==void 0)return pf(i)}async function Cf(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new xu(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new $d(new URL(e),{fetch:cf(r),requestInit:{headers:{...Ut({kind:`mcp`,runtimeVersion:dn}),...t.connectionId===void 0?{}:{[Nt]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let c=Promise.resolve();i.onmessage=e=>{c=c.then(async()=>{try{await a.send(e)}catch(t){let r=vf(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(bf(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=yf(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function wf(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Cf,r=await xf(e),i=e.createConnectionId?.()??ca(),a=!1,o=(e.startKeepalive??_u)({connectionId:i,pid:process.pid,resolveWsUrl:async()=>Sf(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}const Tf=/^mcp\.\d{4}-\d{2}-\d{2}\.log$/;function Ef(){return z(Hr(),`logs`)}function Df(e,t=()=>new Date){try{let n=t().getTime(),r=Qi(e).filter(e=>Tf.test(e)).flatMap(t=>{try{let n=K(z(e,t));return[{name:t,mtime:n.mtimeMs,size:n.size}]}catch{return[]}}),i=[];for(let t of r)if(n-t.mtime>6048e5)try{ta(z(e,t.name))}catch{}else i.push(t);i.sort((e,t)=>e.mtime-t.mtime);let a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{ta(z(e,t.name)),a-=t.size}catch{}}}catch{}}function Of(e={}){let t=e.logsDir??Ef(),n=e.now??(()=>new Date),r=e.pruneDelayMs??5e3;r<=0?Df(t,n):setTimeout(()=>Df(t,n),r).unref?.();let i=0,a=!1;return{write(e){if(!(i>=5))try{a||=(U(t,{recursive:!0}),!0);let r=n().toISOString(),o=z(t,`mcp.${r.slice(0,10)}.log`);qi(o,`${r} ${e}`),i=0}catch{a=!1,i++}}}}const kf=ma(la);async function Af(e){try{let{stdout:t}=await kf(`git`,[`-C`,e,`worktree`,`list`,`--porcelain`],k({timeout:2e3}));return t.split(`
63
+ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Gd(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Gd(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Jd(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Yd(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Xd=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=qd({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};const Zd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Qd=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},$d=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ju(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Zd}async _authThenStart(){if(!this._authProvider)throw new md(`No auth provider`);let e;try{e=await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new md;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Au(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Qd(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Xd({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Qt.parse(JSON.parse(e.data));Vn(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new md(`No auth provider`);if(await wd(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new md(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:mn(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Qd(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Od(o);if(this._resourceMetadataUrl=t,this._scope=n,await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new md;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Od(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Qd(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await wd(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new md;return this.send(e)}}throw new Qd(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ye(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c){if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Qt.parse(e)):[Qt.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Qd(-1,`Unexpected content type: ${l}`)}else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Qd(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function ef(e){return`${e} Server.app`}function tf(e){return`${e} Helper`}ef(o),tf(o);function nf(e){let t=Ui.basename(e);return Ui.join(Ui.dirname(e),`..`,`Frameworks`,ef(t),`Contents`,`MacOS`,tf(t))}const rf=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function af(e){if(e.platform!==`darwin`||!rf.test(e.execPath))return null;let t=nf(e.execPath);return e.exists(t)?t:null}function of(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??H,a=r[1];return a?{command:af({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function sf(){return`Run \`${l()} start\` in the target project, then retry this tool. Do not fall back to native file edits for OpenKnowledge content.`}function cf(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function lf(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function uf(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function df(e,t){return`http://${uf(e)}:${t}/mcp`}function ff(e){return`${e}/mcp`}function pf(e){return e.replace(/^http/,`ws`)}function mf(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function hf(e,t){if(e&&e.draining!==!0&&t(e.pid))return Gn(e,{fallbackHost:`127.0.0.1`})??void 0}function gf(e){if(!H(e))return``;let t=Ue(W(e,`utf-8`)).trim();return t.length>8192?`…${t.slice(-8192)}`:t}function _f(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}\n${sf()}`}function vf(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function yf(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function bf(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function xf(e){let t=e.readLock??(()=>en(e.lockDir)),n=e.isAlive??sn,r=e.sleep??(e=>ma(e)),i=e.spawn??fa,a=e.readErrorLog??gf,o=e.openErrorLog??(async t=>(await Ht(e.projectDir,{authorityRegistryPath:e.authorityRegistryPath}),tt(t,process.pid))),s=e.closeFd??Ji,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return df(He,t)}let u=t(),d=hf(u,n);if(d!==void 0)return ff(d);if(e.envAutoStart===`0`)throw new ln(`OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start. ${sf()}`);if(u!==null&&u.draining===!0&&n(u.pid)){let e=Date.now(),i=e+c,a=!0;for(;Date.now()<i;){let e=t();if(e===null||e.draining!==!0||!n(e.pid)){a=!1;break}await r(l)}console.error(`[mcp-shim] waited ${Date.now()-e}ms for a draining predecessor server${a?` (timed out — proceeding anyway)`:``}`);let o=hf(t(),n);if(o!==void 0)return ff(o)}H(e.lockDir)||U(e.lockDir,{recursive:!0});let f=Ot(e.projectDir),p;try{p=await o(f)}catch(e){throw Error(`spawn failed: could not prepare server-start diagnostics: ${e instanceof Error?e.message:String(e)}\n${sf()}`,{cause:e})}let m,h,g=of();try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],windowsHide:!0,cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}\n${sf()}`)}await r(l);let e=hf(t(),n);if(e!==void 0)return ff(e)}if(h){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}\n${sf()}`)}throw Error(_f(c,a(f)))}function Sf(e,t){if(e.portOverride!==void 0)return mf(t);let n=e.readLock??(()=>en(e.lockDir)),r=e.isAlive??sn,i=hf(n(),r);if(i!==void 0)return pf(i)}async function Cf(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new xu(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new $d(new URL(e),{fetch:cf(r),requestInit:{headers:{...Ut({kind:`mcp`,runtimeVersion:dn}),...t.connectionId===void 0?{}:{[Nt]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let c=Promise.resolve();i.onmessage=e=>{c=c.then(async()=>{try{await a.send(e)}catch(t){let r=vf(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(bf(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=yf(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function wf(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Cf,r=await xf(e),i=e.createConnectionId?.()??ca(),a=!1,o=(e.startKeepalive??_u)({connectionId:i,pid:process.pid,resolveWsUrl:async()=>Sf(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}const Tf=/^mcp\.\d{4}-\d{2}-\d{2}\.log$/;function Ef(){return z(Hr(),`logs`)}function Df(e,t=()=>new Date){try{let n=t().getTime(),r=Qi(e).filter(e=>Tf.test(e)).flatMap(t=>{try{let n=K(z(e,t));return[{name:t,mtime:n.mtimeMs,size:n.size}]}catch{return[]}}),i=[];for(let t of r)if(n-t.mtime>6048e5)try{ta(z(e,t.name))}catch{}else i.push(t);i.sort((e,t)=>e.mtime-t.mtime);let a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{ta(z(e,t.name)),a-=t.size}catch{}}}catch{}}function Of(e={}){let t=e.logsDir??Ef(),n=e.now??(()=>new Date),r=e.pruneDelayMs??5e3;r<=0?Df(t,n):setTimeout(()=>Df(t,n),r).unref?.();let i=0,a=!1;return{write(e){if(!(i>=5))try{a||=(U(t,{recursive:!0}),!0);let r=n().toISOString(),o=z(t,`mcp.${r.slice(0,10)}.log`);qi(o,`${r} ${e}`),i=0}catch{a=!1,i++}}}}const kf=ha(la);async function Af(e){try{let{stdout:t}=await kf(`git`,[`-C`,e,`worktree`,`list`,`--porcelain`],k({timeout:2e3}));return t.split(`
64
64
  `).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function jf(e){let t=V(e);for(;;){if(Rr(t))return t;let n=R(t);if(n===t)throw Error(`No OpenKnowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${f}\`).`);t=n}}function Mf(e){try{let t=new URL(e);return t.protocol===`file:`?Bi(t):void 0}catch{return}}async function Nf(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Mf(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Pf(e,t,n,r=jf){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function Ff(e){let t=Of(),n={write:e=>(t.write(e),process.stderr.write(e))},r=e.spawnTimeoutMs??lf(process.env.OK_MCP_SPAWN_TIMEOUT_MS),i=e.envAutoStart??process.env.OK_MCP_AUTOSTART,a=Li({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),o=new Yt({name:Ce,version:dn});Qe(o);let s=ca(),c={current:{connectionId:s,displayName:s,colorSeed:s}},l=new Map,u=e=>{if(l.has(e))return;let t=Un(e),r=c.current,i=_u({connectionId:s,pid:process.pid,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Sf({lockDir:t},``),log:t=>n.write(`[mcp] keepalive[${e}]: ${t}\n`)});l.set(e,i)},d=()=>Nf({getClientCapabilities:()=>o.server.getClientCapabilities(),listRoots:()=>o.server.listRoots(),log:e=>n.write(`[mcp] ${e}\n`)}),f,p=!1,m=async e=>{if(p)return;p=!0;let t=await Af(e);if(t<=1){p=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${t} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{n.write(`[mcp] ${r}\n`),await o.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},h=async e=>{let t=await Pf(e,f,d);if(f=t.nextSticky??f,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an OpenKnowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&m(t.projectDir),t.projectDir},g=async e=>{let t=await Pf(e,f,d);if(f=t.nextSticky??f,t.projectDir===void 0)return;t.viaRootGuess&&m(t.projectDir);let n=t.projectDir,o=await a(n),s=await xf({projectDir:n,lockDir:Un(n),contentDir:Tn(o,n),envAutoStart:i,...r===void 0?{}:{timeoutMs:r}});return u(n),s.replace(/\/mcp$/,``)};o.server.oninitialized=()=>{let e=o.server.getClientVersion(),t=Bn(e?.name,s);c.current={connectionId:s,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},gn(o,{serverUrl:g,resolveCwd:h,config:a,identityRef:c,isHostedAgent:ge(process.env)}),Zn(o);let _=new xu,v=!1,y,b,x=async()=>{if(v)return;v=!0,y?.stop(),b?.stop();for(let e of l.values())try{e.close()}catch(e){n.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}l.clear();let e=await Promise.allSettled([o.close(),_.close()]);for(let t of e)if(t.status===`rejected`){let e=t.reason;n.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await o.connect(_),n.write(`[mcp] global stdio server ready (per-call project routing)
65
65
  `);let S=!1,C=()=>{S||(S=!0,setTimeout(()=>{n.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
66
66
  `),process.exit(1)},5e3).unref(),x().finally(()=>{process.exit(0)}))};process.once(`SIGINT`,C),process.once(`SIGTERM`,C),process.stdin.on(`end`,()=>{n.write(`[mcp] stdin end — host disconnected, shutting down
@@ -77,7 +77,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
77
77
  `).replace(/\n+$/,``);return e.endsWith(`
78
78
  `)?`${c}\n`:c}function yp(e){return e.replace(/\r\n|\r|\n/g,`<br>`).replace(/\|/g,`\\|`)}function bp(e){return/\s/.test(e)?`<${e}>`:e}function xp(e,t={}){let{header:n,rows:r}=Wf(e),i=n.length;if(i===0)return{table:``,columns:0,wide:!1};let a=t.wideThreshold??15,o=t.titleColumn??0;return{table:[`| ${n.map(yp).join(` | `)} |`,`| ${n.map(()=>`---`).join(` | `)} |`,...r.map(e=>`| ${n.map((n,r)=>{let i=e[r]??``,a=yp(i);if(r===o&&t.linkForTitle&&i.trim()!==``){let e=t.linkForTitle(i);if(e)return`[${a}](${bp(e)})`}return a}).join(` | `)} |`)].join(`
79
79
  `),columns:i,wide:i>a}}function Sp(e,t){let n=e.match(/^#\s+(.+)$/m);return n?n[1].trim():t}function Cp(e,t){return`# ${e}\n\n${t}\n`}const wp=[`links`,`frontmatter`,`callouts`,`images`,`tables`],Tp=/\.mdx?$/i;function Ep(e){return{isNotionExport:e,transforms:{links:0,frontmatter:0,callouts:0,images:0,tables:0},assetsExtracted:0,stubsCreated:0,csvsRemoved:0,wideTables:[],ambiguousTitleLinks:0,unreadable:[],filesChanged:0}}function Dp(e,t={}){let n=t.selected??new Set(wp),r=dp(e);if(!r&&!t.force)return{changes:[],assets:[],deletions:[],report:Ep(!1)};let i=Ep(r),a=cp(e),o=$f(a,{onUnreadable:e=>i.unreadable.push(e)}),s=n.has(`tables`),c=new Map,l=new Set;for(let e of o){e.stubPath&&l.add(e.stubPath);for(let t of e.rowFiles)c.set(t,e)}let u=[],d=[],f=[];for(let e of a){if(!Tp.test(e)||s&&l.has(e))continue;let r;try{r=W(e,`utf8`)}catch{i.unreadable.push(e);continue}let a=r,o=(e,t)=>{a!==t&&(i.transforms[e]+=1)};if(n.has(`images`)){let n=a,r=Uf(a,Vi(e),{strip:t.stripBase64});a=r.markdown;for(let t of r.assets)d.push({path:z(R(e),t.filename),bytes:t.bytes});i.assetsExtracted+=r.assets.length,o(`images`,n)}if(n.has(`callouts`)){let e=a;a=zf(a),o(`callouts`,e)}if(n.has(`frontmatter`)){let t=c.get(e);if(t){let e=a;a=vp(a,t.propertyKeys),o(`frontmatter`,e)}}if(n.has(`links`)){let e=a;a=sp(a,{redirectCsv:s}),o(`links`,e)}a!==r&&u.push({path:e,content:a})}if(s)for(let e of o){let r=xp(e.csvText,{linkForTitle:t=>{let n=Xf(e.folderIndex,t);return n.ambiguous&&(i.ambiguousTitleLinks+=1),n.path?B(R(e.stubTargetPath),n.path):null}});if(r.columns===0)continue;let a=e.stubPath??e.stubTargetPath,o=null;if(e.stubPath)try{o=W(e.stubPath,`utf8`)}catch{i.unreadable.push(e.stubPath);continue}let c=Cp(o===null?e.fallbackTitle:Sp(o,e.fallbackTitle),r.table);n.has(`links`)&&(c=sp(c,{redirectCsv:s})),r.wide&&i.wideTables.push(a),o===null?(u.push({path:a,content:c}),i.stubsCreated+=1,i.transforms.tables+=1):c!==o&&(u.push({path:a,content:c}),i.transforms.tables+=1),t.removeCsv&&(f.push(e.csvPath),i.csvsRemoved+=1)}return i.filesChanged=new Set(u.map(e=>e.path)).size,{changes:u,assets:d,deletions:f,report:i}}function Op(e){for(let t of e.assets)U(R(t.path),{recursive:!0}),na(t.path,t.bytes);for(let t of e.changes)U(R(t.path),{recursive:!0}),na(t.path,t.content,`utf8`);for(let t of e.deletions)try{ta(t)}catch(e){if(e.code!==`ENOENT`)throw e}}const kp={images:`Inline base64 images extracted`,callouts:`Notion <aside> callouts converted`,frontmatter:`Row properties lifted to frontmatter`,tables:`Databases rendered as tables`,links:`Internal links decoded`},Ap=[`images`,`callouts`,`frontmatter`,`tables`,`links`];function jp(e,t){let n=[];n.push(t.applied?`Applied Notion cleanup in ${t.dir}`:`Dry run — no changes written (${t.dir})`);for(let t of Ap)n.push(` ${kp[t]}: ${e.transforms[t]}`);return n.push(` Assets written: ${e.assetsExtracted}`),e.stubsCreated>0&&n.push(` Database pages created (CSVs without a stub): ${e.stubsCreated}`),e.csvsRemoved>0&&n.push(` CSV files removed: ${e.csvsRemoved}`),n.push(` Files changed: ${e.filesChanged}`),e.ambiguousTitleLinks>0&&n.push(` Ambiguous title links left as plain text: ${e.ambiguousTitleLinks}`),e.wideTables.length>0&&n.push(` Wide tables (>15 columns): ${e.wideTables.length}`),e.unreadable.length>0&&n.push(` Skipped unreadable files: ${e.unreadable.length}`),!t.applied&&e.filesChanged+e.assetsExtracted+e.csvsRemoved>0&&(n.push(``),n.push(`Re-run with --apply to write these changes.`)),n.join(`
80
- `)}function Mp(e,t){return JSON.stringify({applied:t.applied,...e},null,2)}function Np(e){let t=new Set(wp);return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{if(!t.has(e))throw Error(`Unknown transform "${e}". Valid transforms: ${wp.join(`, `)}`);return e})}function Pp(e,t){let n=new Set(wp);if(e&&(n=new Set(Np(e))),t)for(let e of Np(t))n.delete(e);return n}function Fp(){let e=new j(`migrate`).description(`Migrate content from other tools into Open Knowledge`);return e.command(`notion [dir]`).description(`Clean up a Notion "Markdown & CSV" export in place (dry-run unless --apply)`).option(`--apply`,`write changes to disk (default: dry-run preview)`).option(`--strip-base64`,`delete inline base64 images instead of extracting them to files`).option(`--remove-csv`,`delete each "_all.csv" once its table page exists (destructive)`).option(`--only <transforms>`,`run only these transforms (comma-separated: links,frontmatter,callouts,images,tables)`).option(`--skip <transforms>`,`skip these transforms (comma-separated)`).option(`--force`,`run even if the directory is not detected as a Notion export`).option(`--json`,`print a machine-readable JSON report`).action((e,t)=>{let n=V(e??process.cwd()),r;try{r=Pp(t.only,t.skip)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let i=Dp(n,{selected:r,stripBase64:t.stripBase64??!1,removeCsv:t.removeCsv??!1,force:t.force??!1}),{report:a}=i;if(!a.isNotionExport&&!t.force){t.json?console.log(JSON.stringify({refused:!0,reason:`not-a-notion-export`,dir:n},null,2)):console.error(`Not a Notion export: ${n}\nNo id-suffixed pages, "_all.csv", or inline base64 images were found. Re-run with --force to override.`),process.exitCode=2;return}if(t.apply)try{Op(i)}catch(e){console.error(`Failed to apply changes: ${e instanceof Error?e.message:String(e)}`),process.exitCode=4;return}console.log(t.json?Mp(a,{applied:t.apply??!1}):jp(a,{applied:t.apply??!1,dir:n})),a.filesChanged===0&&a.assetsExtracted===0&&i.deletions.length===0?process.exitCode=1:t.apply&&(a.ambiguousTitleLinks>0||a.wideTables.length>0)&&(process.exitCode=3)}),e}function Ip(e){return Object.values(a).some(({protocolScheme:t})=>e.startsWith(`${t}://`))}function Lp(e,t,n){return t===`darwin`?n&&Ip(e)?{command:`/usr/bin/open`,args:[`-a`,n,e]}:{command:`/usr/bin/open`,args:[e]}:t===`win32`?e.startsWith(`http://`)||e.startsWith(`https://`)?{command:`explorer.exe`,args:[e]}:{command:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{command:`xdg-open`,args:[e]}}function Rp(e,t={}){let n=Lp(e,t.platform??process.platform,t.desktopBundlePath);return Ni(n.command,n.args,{spawn:t.spawn,env:t.env,timeoutMs:t.timeoutMs})}function zp(e,t,n=process.platform){let r=Lp(t,n).command;switch(e){case`not-installed`:return`${r} is not installed or cannot be executed`;case`timeout`:return`${r} did not start in time`;case`spawn-error`:return`${r} could not be started`}}function Bp(e=()=>ki(Ei())){return{detectDesktopApp:()=>Di(e()),resolveBaseUrl:e=>ut({lockDir:O(e)}).baseUrl,classifyName:(e,t)=>{let n=z(e,t);try{return K(n).isDirectory()?`folder`:`doc`}catch(e){let t=e?.code;return t!==`ENOENT`&&t!==`ENOTDIR`&&process.stderr.write(`[ok open] statSync failed for ${n} (${t??`unknown`}); treating as a doc\n`),`doc`}},openTarget:Rp,findAncestorProject:e=>Vr(R(V(e)))?.rootPath??null,isProjectRoot:e=>Vr(e)?.distance===0,enclosingProject:e=>Vr(V(e))?.rootPath??null,log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Vp(e){return e.startsWith(`/`)||e.includes(`\\`)||e.split(`/`).includes(`..`)}function Hp(e){return e.error(`No OpenKnowledge desktop app found and no UI is running. Install it from https://openknowledge.ai/download, or run \`${l()} start\` to serve the editor, then retry.`),1}async function Up(e,t,n,r,i,a){let o=await i.openTarget(e,a?{desktopBundlePath:a}:{});if(!o.ok)return i.error(`Could not open ${e}: ${zp(o.reason,e)}.`),1;if(i.log(t),!r)return i.log(`Working directory: ${n} (not an OpenKnowledge project).`),0;i.log(`Project: ${n}`);let s=i.findAncestorProject(n);return s!==null&&i.log(`Note: this project (${n}) is nested inside another OpenKnowledge project at ${s}. Pass --project to choose explicitly.`),0}async function Wp(e,t,n){let r=t.project!==void 0,i=r?null:n.enclosingProject(process.cwd()),a=V(t.project??i??process.cwd()),o=r||i!==null,s=e.replace(/\/+$/,``);if(r&&!n.isProjectRoot(a))return n.error(`Cannot open with --project ${a}: no .ok/config.yml there, so it is not an OpenKnowledge project.`),1;if(!s)return n.error(`Nothing to open: pass a doc, folder, or skill name (e.g. \`${l()} open specs/foo/SPEC\`).`),1;if(Vp(s))return n.error(`Invalid name "${s}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(t.skill===!0){let e=t.scope??`project`;if(!de.includes(e))return n.error(`Invalid --scope "${t.scope}": expected one of ${de.join(`, `)}.`),1;let r=n.detectDesktopApp();if(r)return Up(`${r.protocolScheme}://open?project=${encodeURIComponent(a)}&doc=${encodeURIComponent(`__skill__/${e}/${s}`)}`,`Opening skill ${s} (${e}) in the OpenKnowledge desktop app.`,a,o,n,r.bundlePath);let i=n.resolveBaseUrl(a);if(i){let t=`${i}/#/${zn(e,s)}`;return Up(t,`Opening skill ${s} (${e}) in your browser: ${t}`,a,o,n)}return Hp(n)}let c=/\/+$/.test(e)||n.classifyName(a,s)===`folder`,u=n.detectDesktopApp();if(c){if(u)return Up(`${u.protocolScheme}://open?project=${encodeURIComponent(a)}&folder=${encodeURIComponent(s)}`,`Opening folder ${s} in the OpenKnowledge desktop app.`,a,o,n,u.bundlePath);let e=n.resolveBaseUrl(a);if(e){let t=`${e}/#/${Pn(s)}`;return Up(t,`Opening folder ${s} in your browser: ${t}`,a,o,n)}return Hp(n)}if(u)return Up(`${u.protocolScheme}://open?project=${encodeURIComponent(a)}&doc=${encodeURIComponent(s)}`,`Opening ${s} in the OpenKnowledge desktop app.`,a,o,n,u.bundlePath);let d=n.resolveBaseUrl(a);if(d){let e=`${d}/#/${nn(s)}`;return Up(e,`Opening ${s} in your browser: ${e}`,a,o,n)}return Hp(n)}function Gp(){return new j(`open`).description(`Open a doc, folder, or skill in the OK Desktop app (falls back to the browser UI). Docs and folders are auto-detected — no flag needed.`).argument(`<name>`,`Doc path (specs/foo/SPEC), folder path (specs/foo or specs/foo/), or a skill name with --skill`).option(`--skill`,`Open <name> as a skill in the skill editor`).option(`--scope <scope>`,`Skill scope when --skill is set: ${de.join(` | `)}`,`project`).option(`--project <dir>`,`Project root (defaults to the project enclosing the current directory)`).action(async(e,t)=>{process.exitCode=await Wp(e,t,Bp())})}function Kp(e){return new j(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-h0nWv2-p.mjs`),r=e(),i=process.cwd(),a=Tn(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function qp(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function Jp(e){let[t,...n]=e;return t!==void 0&&n.length===0?t:`origin`}async function Yp(e,t){try{let n=(await e.raw([`symbolic-ref`,`--quiet`,`--short`,`HEAD`])).trim(),r=n===``?``:(await e.raw([`for-each-ref`,`--format=%(${t===`push`?`push`:`upstream`}:remotename)`,`refs/heads/${n}`])).trim(),i=r===``?Jp((await e.raw([`remote`])).split(`
80
+ `)}function Mp(e,t){return JSON.stringify({applied:t.applied,...e},null,2)}function Np(e){let t=new Set(wp);return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{if(!t.has(e))throw Error(`Unknown transform "${e}". Valid transforms: ${wp.join(`, `)}`);return e})}function Pp(e,t){let n=new Set(wp);if(e&&(n=new Set(Np(e))),t)for(let e of Np(t))n.delete(e);return n}function Fp(){let e=new j(`migrate`).description(`Migrate content from other tools into Open Knowledge`);return e.command(`notion [dir]`).description(`Clean up a Notion "Markdown & CSV" export in place (dry-run unless --apply)`).option(`--apply`,`write changes to disk (default: dry-run preview)`).option(`--strip-base64`,`delete inline base64 images instead of extracting them to files`).option(`--remove-csv`,`delete each "_all.csv" once its table page exists (destructive)`).option(`--only <transforms>`,`run only these transforms (comma-separated: links,frontmatter,callouts,images,tables)`).option(`--skip <transforms>`,`skip these transforms (comma-separated)`).option(`--force`,`run even if the directory is not detected as a Notion export`).option(`--json`,`print a machine-readable JSON report`).action((e,t)=>{let n=V(e??process.cwd()),r;try{r=Pp(t.only,t.skip)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let i=Dp(n,{selected:r,stripBase64:t.stripBase64??!1,removeCsv:t.removeCsv??!1,force:t.force??!1}),{report:a}=i;if(!a.isNotionExport&&!t.force){t.json?console.log(JSON.stringify({refused:!0,reason:`not-a-notion-export`,dir:n},null,2)):console.error(`Not a Notion export: ${n}\nNo id-suffixed pages, "_all.csv", or inline base64 images were found. Re-run with --force to override.`),process.exitCode=2;return}if(t.apply)try{Op(i)}catch(e){console.error(`Failed to apply changes: ${e instanceof Error?e.message:String(e)}`),process.exitCode=4;return}console.log(t.json?Mp(a,{applied:t.apply??!1}):jp(a,{applied:t.apply??!1,dir:n})),a.filesChanged===0&&a.assetsExtracted===0&&i.deletions.length===0?process.exitCode=1:t.apply&&(a.ambiguousTitleLinks>0||a.wideTables.length>0)&&(process.exitCode=3)}),e}function Ip(e){return Object.values(a).some(({protocolScheme:t})=>e.startsWith(`${t}://`))}function Lp(e,t,n){return t===`darwin`?n&&Ip(e)?{command:`/usr/bin/open`,args:[`-a`,n,e]}:{command:`/usr/bin/open`,args:[e]}:t===`win32`?e.startsWith(`http://`)||e.startsWith(`https://`)?{command:`explorer.exe`,args:[e]}:{command:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{command:`xdg-open`,args:[e]}}function Rp(e,t={}){let n=Lp(e,t.platform??process.platform,t.desktopBundlePath);return Ni(n.command,n.args,{spawn:t.spawn,env:t.env,timeoutMs:t.timeoutMs})}function zp(e,t,n=process.platform){let r=Lp(t,n).command;switch(e){case`not-installed`:return`${r} is not installed or cannot be executed`;case`timeout`:return`${r} did not start in time`;case`spawn-error`:return`${r} could not be started`}}function Bp(e=()=>ki(Ei())){return{detectDesktopApp:()=>Di(e()),resolveBaseUrl:e=>ut({lockDir:O(e)}).baseUrl,classifyName:(e,t)=>{let n=z(e,t);try{return K(n).isDirectory()?`folder`:`doc`}catch(e){let t=e?.code;return t!==`ENOENT`&&t!==`ENOTDIR`&&process.stderr.write(`[ok open] statSync failed for ${n} (${t??`unknown`}); treating as a doc\n`),`doc`}},openTarget:Rp,findAncestorProject:e=>Vr(R(V(e)))?.rootPath??null,isProjectRoot:e=>Vr(e)?.distance===0,enclosingProject:e=>Vr(V(e))?.rootPath??null,log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Vp(e){return e.startsWith(`/`)||e.includes(`\\`)||e.split(`/`).includes(`..`)}function Hp(e){return e.error(`No OpenKnowledge desktop app found and no UI is running. Install it from https://openknowledge.ai/download, or run \`${l()} start\` to serve the editor, then retry.`),1}async function Up(e,t,n,r,i,a){let o=await i.openTarget(e,a?{desktopBundlePath:a}:{});if(!o.ok)return i.error(`Could not open ${e}: ${zp(o.reason,e)}.`),1;if(i.log(t),!r)return i.log(`Working directory: ${n} (not an OpenKnowledge project).`),0;i.log(`Project: ${n}`);let s=i.findAncestorProject(n);return s!==null&&i.log(`Note: this project (${n}) is nested inside another OpenKnowledge project at ${s}. Pass --project to choose explicitly.`),0}async function Wp(e,t,n){let r=t.project!==void 0,i=r?null:n.enclosingProject(process.cwd()),a=V(t.project??i??process.cwd()),o=r||i!==null,s=e.replace(/\/+$/,``);if(r&&!n.isProjectRoot(a))return n.error(`Cannot open with --project ${a}: no .ok/config.yml there, so it is not an OpenKnowledge project.`),1;if(!s)return n.error(`Nothing to open: pass a doc, folder, or skill name (e.g. \`${l()} open specs/foo/SPEC\`).`),1;if(Vp(s))return n.error(`Invalid name "${s}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(t.skill===!0){let e=t.scope??`project`;if(!de.includes(e))return n.error(`Invalid --scope "${t.scope}": expected one of ${de.join(`, `)}.`),1;let r=n.detectDesktopApp();if(r)return Up(`${r.protocolScheme}://open?project=${encodeURIComponent(a)}&doc=${encodeURIComponent(`__skill__/${e}/${s}`)}`,`Opening skill ${s} (${e}) in the OpenKnowledge desktop app.`,a,o,n,r.bundlePath);let i=n.resolveBaseUrl(a);if(i){let t=`${i}/#/${zn(e,s)}`;return Up(t,`Opening skill ${s} (${e}) in your browser: ${t}`,a,o,n)}return Hp(n)}let c=/\/+$/.test(e)||n.classifyName(a,s)===`folder`,u=n.detectDesktopApp();if(c){if(u)return Up(`${u.protocolScheme}://open?project=${encodeURIComponent(a)}&folder=${encodeURIComponent(s)}`,`Opening folder ${s} in the OpenKnowledge desktop app.`,a,o,n,u.bundlePath);let e=n.resolveBaseUrl(a);if(e){let t=`${e}/#/${Pn(s)}`;return Up(t,`Opening folder ${s} in your browser: ${t}`,a,o,n)}return Hp(n)}if(u)return Up(`${u.protocolScheme}://open?project=${encodeURIComponent(a)}&doc=${encodeURIComponent(s)}`,`Opening ${s} in the OpenKnowledge desktop app.`,a,o,n,u.bundlePath);let d=n.resolveBaseUrl(a);if(d){let e=`${d}/#/${nn(s)}`;return Up(e,`Opening ${s} in your browser: ${e}`,a,o,n)}return Hp(n)}function Gp(){return new j(`open`).description(`Open a doc, folder, or skill in the OK Desktop app (falls back to the browser UI). Docs and folders are auto-detected — no flag needed.`).argument(`<name>`,`Doc path (specs/foo/SPEC), folder path (specs/foo or specs/foo/), or a skill name with --skill`).option(`--skill`,`Open <name> as a skill in the skill editor`).option(`--scope <scope>`,`Skill scope when --skill is set: ${de.join(` | `)}`,`project`).option(`--project <dir>`,`Project root (defaults to the project enclosing the current directory)`).action(async(e,t)=>{process.exitCode=await Wp(e,t,Bp())})}function Kp(e){return new j(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-uakaw7R6.mjs`),r=e(),i=process.cwd(),a=Tn(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function qp(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function Jp(e){let[t,...n]=e;return t!==void 0&&n.length===0?t:`origin`}async function Yp(e,t){try{let n=(await e.raw([`symbolic-ref`,`--quiet`,`--short`,`HEAD`])).trim(),r=n===``?``:(await e.raw([`for-each-ref`,`--format=%(${t===`push`?`push`:`upstream`}:remotename)`,`refs/heads/${n}`])).trim(),i=r===``?Jp((await e.raw([`remote`])).split(`
81
81
  `).map(e=>e.trim()).filter(e=>e!==``)):r,a=(await e.raw([`remote`,`get-url`,...t===`push`?[`--push`]:[],i])).trim();return a===``?null:a}catch{return null}}function Xp(e){let t=/^https:\/\/(?:[^/?#@]*@)?([^/?#@]+)/i.exec(e)?.[1];return t!==void 0&&t===p(t)?t:null}const Zp=[/Authentication failed for '([^']+)'/g,/unable to access '([^']+)'/g,/repository '([^']+)' not found/g,/could not read (?:Username|Password) for '([^']+)'/g];function Qp(e,t){return Zp.some(n=>Array.from(e.matchAll(n)).some(e=>Xp(e[1])===t))}function $p(e){let t={...process.env},n=Object.create(t);for(let r of new Set([...Object.keys(t),...Object.keys(e)]))e[r]!==t[r]&&(n[r]=e[r]);return n}async function em(e,t,n){let r={git:A({baseDir:e})},i=t===null?null:Xp(t);if(t===null||i===null||kr(t)===null||!x(i,Xt()))return r;let{auth:a,declaredMiss:o}=await rc(t,n.tokenStore,{cwd:e,...n.detectGh?{_detectGhFn:n.detectGh}:{}});return a.tier===`none`?r:{git:A($s(e,Hs(Ys(),i))).env($p(Js(a))),signIn:{host:i,tier:a.tier},...o===void 0?{}:{declaredMiss:o}}}function tm(e,t,n){if(n.kind!==`auth`)return null;let{host:r}=t,i=t.tier===`A`,a=i?`The ${e} offered the GitHub CLI's sign-in for ${r}, which OpenKnowledge relays in place of your git credential helpers for that host; a ~/.netrc entry or a password in the remote URL is used before it.`:`The ${e} offered OpenKnowledge's GitHub sign-in for ${r} in place of your git credential helpers for that host; a ~/.netrc entry or a password in the remote URL is used before it.`;switch(n.subclass){case`no-credential`:case`401`:case`unknown-auth`:return`${a} If that sign-in has expired or was revoked, run: ${i?`gh auth login --hostname ${r}`:`${l()} auth login --host ${r}`}`;case`403`:return`${a} If ${r} denied that account access, check that it has access to the repository.`;case`not-found-as-identity`:return`${a} If ${r} reported the repository as not found, it may not exist, or that account may not have access.`;case`scope-mismatch`:return`${a} If its token is missing a required OAuth scope, likely repo, ${i?`run: gh auth refresh --hostname ${r} --scopes repo`:`create a token with that scope at https://${r}/settings/tokens and run: ${l()} auth pat --host ${r}`}`;case`ssh-auth`:return null;default:return n.subclass}}async function nm(e,t,n){try{return await n(e.git)}catch(n){let r=n instanceof Error?n.message:String(n),i=e.signIn===void 0||!Qp(r,e.signIn.host)?null:tm(t,e.signIn,We(n));throw i===null?n:Error(`${r.trimEnd()}\n${i}`,{cause:n})}}async function rm(e){await e.fetch();let t=(await e.raw([`rev-parse`,`--verify`,`--quiet`,`@{upstream}^{commit}`])).trim();if(t!==``){let n=(await e.raw([`rev-parse`,`--symbolic-full-name`,`@{upstream}`])).trim();return{commit:t,trackingRef:n.startsWith(`refs/`)?n:null}}let n=(await e.raw([`symbolic-ref`,`--quiet`,`--short`,`HEAD`])).trim();if(n===``)throw Error(`not on a branch, so there is nothing to pull into; switch to a branch first, for example: git switch main`);let r=(await e.raw([`config`,`--get`,`branch.${n}.merge`])).trim(),i=(await e.raw([`config`,`--get`,`branch.${n}.remote`])).trim()||`origin`;if(r===``)throw Error(`no upstream configured for branch "${n}"; set one with: git branch --set-upstream-to=${i}/${n} ${n}`);await e.fetch(i,r);let a=(await e.raw([`rev-parse`,`--verify`,`--quiet`,`FETCH_HEAD^{commit}`])).trim();if(a===``)throw Error(`could not resolve the fetched ${r}`);return{commit:a,trackingRef:null}}function im(e){switch(e){case`requires-newer-git`:return[`update-git`];case`unverifiable-target`:return[`readable-folder`,`fix-link`];case`outside-repository`:case`repository-root`:case`private-state`:case`secret-file`:case`inside-private-state`:return[`fix-link`];default:return e}}const am={"update-git":`Update Git to ${Jn} or newer.`,"readable-folder":`If a folder on the way is unreadable on this machine, make it readable.`,"fix-link":`Remove or fix these links on the remote, or fix your own local change to them, then pull again.`};function om(e){if(e instanceof Mt){let t=new Set(e.unsafe.flatMap(({reason:e})=>im(e))),n=Object.entries(am).filter(([e])=>t.has(e)).map(([,e])=>e);return t.has(`fix-link`)||n.push(`Then pull again.`),`incoming symlinks are unsafe to check out: ${e.describeLinks()}. ${n.join(` `)}`}return e instanceof Error?e.message:String(e)}async function sm(e,t,n=process.cwd()){let r=e.op??`sync`,i=O(n),a=en(i);if(a&&a.port>0){let t=`http://127.0.0.1:${a.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${a.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...Ut({kind:`cli`,runtimeVersion:dn})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}qp(e.json,{type:`triggered`,op:r,port:a.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let o=A({baseDir:n}),s={tokenStore:e.tokenStore??mi(),detectGh:e._detectGhFn},c=async t=>{let i=await em(n,t,s),a=tc(i.declaredMiss,{url:`The remote URL`,operation:`ok ${r}`});return a===null||(e.json?qp(!0,{type:`warning`,message:a.trimEnd()}):process.stderr.write(a)),i},l;if(r===`sync`||r===`pull`){qp(e.json,{type:`step`,step:`pull`});let t=await Yp(o,`pull`);l={url:t,remote:await c(t)};let n=await nm(l.remote,`pull`,rm);await Rn(o,n.commit,`merge`);let{trackingRef:r}=n;r!==null&&await ht(o,{name:r,trackingRef:r,commit:n.commit});let i=await o.pull(`.`,r??n.commit);qp(e.json,{type:`pull`,summary:i.summary}),e.json||process.stderr.write(` pull: ${i.summary.changes} changes\n`)}if(r===`sync`||r===`push`){qp(e.json,{type:`step`,step:`push`});let t=await Yp(o,`push`);await nm(l!==void 0&&l.url===t?l.remote:await c(t),`push`,e=>e.push()),qp(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
82
82
  `)}qp(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function cm(e){return new j(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await sm({json:t.json,op:`sync`},e())}catch(e){let n=om(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function lm(e){return new j(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await sm({json:t.json,op:`pull`},e())}catch(e){let n=om(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function um(e){return new j(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await sm({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}const dm={existsSync:e=>H(e),isDirectory:e=>{try{return K(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>Qi(e),readFileSync:e=>W(e),writeFileSync:(e,t)=>{na(e,t)},mkdirSync:(e,t)=>{U(e,t)},rmSync:(e,t)=>{G(e,t)}},fm={resolveProjectBundledSkillDir:()=>Dt(`project`,{checkDesktop:!1}),resolveUserBundledSkillDir:e=>Dt(e,{checkDesktop:!1}),readBundledVersion:()=>Nn(),readRecordedVersion:e=>Hn(e,`cli-hosts`),writeRecordedVersion:(e,t)=>mt(e,`cli-hosts`,t,`cli-start`),recordEvent:e=>Fn(e),readBundleDecision:(e,t)=>pt(e,t),writeBundleDecision:(e,t,n)=>Kt(e,t,n),removeBundleFromDisk:(e,t)=>Or(e,t)};function pm(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function mm(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(R(t),{recursive:!0}),hm(e,t,n)}function hm(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=z(e,r),a=z(t,r);n.isDirectory(i)?hm(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function gm(e,t,n){return n.existsSync(z(e,`.agents`,`skills`,t))||Fe.some(r=>n.existsSync(z(e,r.skillsRoot,t)))}function _m(e,t,n,r,i,a){let o=[],s=z(e,`.agents`,`skills`,t);if(gm(e,t,r)){r.existsSync(s)&&o.push({kind:`central`,path:s,outcome:`skipped-present`});for(let n of Fe){let i=z(e,n.skillsRoot,t);if(i!==s){if(!r.existsSync(z(e,n.hostDir))){o.push({kind:`host`,editorId:n.editorId,hostDir:n.hostDir,path:i,outcome:`skipped-host-absent`});continue}r.existsSync(i)&&o.push({kind:`host`,editorId:n.editorId,hostDir:n.hostDir,path:i,outcome:`skipped-present`})}}return{entries:o,anyWritten:!1,anyDestinationSucceeded:!0}}let c=r.existsSync(z(e,`.agents`));if(c&&r.existsSync(s))o.push({kind:`central`,path:s,outcome:`skipped-present`});else if(c)try{mm(n,s,r),o.push({kind:`central`,path:s,outcome:`written`}),i({event:`user-skill-reclaim-central-written`,scope:`user`,path:s,preexisting:!1,version:a})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({kind:`central`,path:s,outcome:`failed`,error:t}),i({event:`user-skill-reclaim-central-failed`,scope:`user`,path:s,error:t})}for(let c of Fe){let l=z(e,c.hostDir),u=z(e,c.skillsRoot,t);if(u===s){o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`skipped-collapsed-with-central`});continue}if(!r.existsSync(l)){o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`skipped-host-absent`});continue}if(r.existsSync(u)){o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`skipped-present`});continue}try{mm(n,u,r),o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`written`}),i({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:c.editorId,hostDir:c.hostDir,path:u,preexisting:!1,version:a})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`failed`,error:t}),i({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:c.editorId,hostDir:c.hostDir,path:u,error:t})}}return{entries:o,anyWritten:o.some(e=>e.outcome===`written`),anyDestinationSucceeded:o.some(e=>e.outcome===`written`||e.outcome===`skipped-present`)}}function vm(e,t){if(!e)return!1;try{return t.existsSync(e)?t.readFileSync(e).toString(`utf8`).includes(`# ok-mcp-`):!1}catch{return!1}}function ym(e,t,n,r){if(!e||!t)return!1;let i;try{i=e.configPath(n,r)}catch{return!1}let a=e=>z(yn(R(e)),Vi(e));return a(t)===a(i)}function bm(e,t,n,r,i){let a;try{a=n.resolveProjectBundledSkillDir()}catch(e){return i({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let o=[];for(let n of $r){let s=z(e,n.hostDir,`skills`,`open-knowledge`),c=z(s,`SKILL.md`);if(r.existsSync(c)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`present`});continue}let l=ai[n.editorId],u=l?.projectConfigPath?.(e);if(ym(l,u,e,t)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`skipped-global-collision`}),i({event:`project-skill-reclaim-skipped-global-collision`,scope:`project`,editorId:n.editorId,path:s});continue}if(!vm(u,r)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`no-token`}),i({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:n.editorId,path:s});continue}try{Kr(s,e),mm(a,s,r),o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`created`}),i({event:`project-skill-reclaim-created`,scope:`project`,editorId:n.editorId,path:s})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`failed`,error:t}),i({event:`project-skill-reclaim-failed`,scope:`project`,editorId:n.editorId,path:s,error:t})}}return{outcome:`done`,entries:o}}async function xm(e,t,n,r){let i=e=>{t.recordEvent(e).catch(()=>{})},a=()=>new Date().toISOString(),o;try{o=await t.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return r({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let s;try{s=await t.readRecordedVersion(e)}catch(e){r({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),s=null}let c=[],l=null;for(let e of Tt)try{c.push({id:e,sourceDir:t.resolveUserBundledSkillDir(e)})}catch(e){l=e instanceof Error?e.message:String(e)}if(c.length===0)return r({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:l??`no user-global bundles`}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,reason:`bundle-missing:${l}`}),{outcome:`skipped`,reason:`bundle-missing`};let u=[];for(let i of c){let a=kn[i.id],o=gm(e,a,n),s=await t.readBundleDecision(e,a).catch(()=>null);if(!xe(s,{installedOnDisk:o})){if(o)try{t.removeBundleFromDisk(e,i.id),r({event:`user-skill-reclaim-bundle-declined-removed`,scope:`user`,bundle:i.id})}catch(e){r({event:`user-skill-reclaim-bundle-remove-failed`,scope:`user`,bundle:i.id,error:e instanceof Error?e.message:String(e)})}continue}if(s===null&&o)try{await t.writeBundleDecision(e,a,!0)}catch(e){r({event:`user-skill-reclaim-grandfather-write-failed`,scope:`user`,bundle:i.id,error:e instanceof Error?e.message:String(e)})}u.push(i)}if(u.length===0)return{outcome:`skipped`,reason:`all-bundles-declined`};let d=u.every(t=>gm(e,kn[t.id],n));if(s!==null&&s===o&&d)return r({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:o}),{outcome:`skipped`,reason:`version-current`};let f=[],p=c.length===Tt.length,m=[];for(let{id:t,sourceDir:i}of u){let a=_m(e,kn[t],i,n,r,o);f.push(...a.entries),m.push({id:t,anyWritten:a.anyWritten,landed:a.anyDestinationSucceeded,centralFailed:a.entries.some(e=>e.kind===`central`&&e.outcome===`failed`),hostFailed:a.entries.some(e=>e.kind===`host`&&e.outcome===`failed`)})}let h=m.some(e=>e.centralFailed),g=m.every(e=>e.landed);if(p&&g&&!h){let n=null;try{await t.writeRecordedVersion(e,o),r({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:o})}catch(e){n=e instanceof Error?e.message:String(e),r({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:o,error:n})}for(let{id:e,anyWritten:t}of m)i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:e,outcome:n===null?t?`installed`:`skip-current`:`failed`,version:o,...n===null?{}:{reason:`state-write-failed:${n}`}})}else{p||i({ts:a(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,version:o,reason:`bundle-unresolved`});for(let{id:e,centralFailed:t,hostFailed:n}of m)!t&&!n||i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:e,outcome:`failed`,version:o,reason:n?`all-writes-failed`:`central-write-failed`})}return{outcome:`done`,version:o,entries:f}}async function Sm(e){let t=e.logger??pm,n=e.fs??dm,r=e.home??ra(),i={...fm,...e.deps};if(e.reclaimDisableEnv===`1`)return t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`};let a=bm(e.projectDir,r,i,n,t),o=await xm(r,i,n,t),s=xr(r),c=[],l=!1,u=!1;if(s.skillDirs.length>0||s.emptyDirs.length>0){if(e.confirmLegacyCleanup&&await e.confirmLegacyCleanup(s)){try{c=mr(r,s)}catch(e){u=!0,t({event:`legacy-fanout-cleanup-refused`,scope:`user`,error:e instanceof Error?e.message:String(e)})}for(let e of c)t({event:`legacy-fanout-path-removed`,scope:`user`,path:e})}else l=!0,t({event:`legacy-fanout-cleanup-declined`,scope:`user`})}return{status:`done`,project:a,user:o,legacySwept:c,legacyCleanupDeclined:l,legacyCleanupFailed:u}}function Cm(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`&&e.user.reason!==`all-bundles-declined`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function wm(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`present`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length,o=e.project.entries.filter(e=>e.outcome===`skipped-global-collision`).length;t.push(` Project: ${n} present, ${r} created, ${i} no-token, ${a} failed.`),o>0&&t.push(` Skipped ${o} host(s) whose project config path is their user-global config (not a project directory).`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-present`).length,i=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,a=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} present, ${i} skipped, ${a} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return e.legacySwept.length>0?t.push(` Cleanup: removed ${e.legacySwept.length} path(s) from a pre-0.42 install.`):e.legacyCleanupFailed?t.push(` Cleanup: failed — see logs; pre-0.42 directories left in place.`):e.legacyCleanupDeclined&&t.push(` Cleanup: declined — pre-0.42 directories left in place.`),t.join(`
83
83
  `)}function Tm(){return new j(`repair-skills`).description(`Restore missing project skill copies and repair user-global bundles for installed AI editors. Existing project skills are preserved; run \`${l()} init\` to refresh them.`).option(`-y, --yes`,`Skip the confirmation prompt for removing directories left by a pre-0.42 install.`).action(async e=>{let t=await Sm({projectDir:V(process.cwd()),reclaimDisableEnv:process.env.OK_RECLAIM_DISABLE??null,confirmLegacyCleanup:t=>Em(t,{yes:e.yes===!0})});process.stdout.write(`${wm(t)}\n`),process.exitCode=Cm(t)})}async function Em(e,t){let n=ra(),r=e=>`~/${B(n,e)}`,i=t.input??process.stdin,a=[``,L(`A previous version of OpenKnowledge installed its skill into agent tools you may never have used.`),N(`(Versions before 0.42 wrote to every host a third-party installer knew about — see issue #820.)`)];if(e.skillDirs.length>0&&a.push(``,`${L(`Remove OpenKnowledge skills:`)} ${e.skillDirs.length}`,...e.skillDirs.map(e=>` ${r(e)}`)),e.emptyDirs.length>0){let t=e.skillDirs.length>0?`Then remove these, which hold nothing else once the above are gone:`:`Remove these empty directories, left behind by that install:`;a.push(``,`${L(t)} ${e.emptyDirs.length}`,...e.emptyDirs.map(e=>` ${r(e)}`))}if(a.push(``,N(`Nothing outside these paths is touched. A directory that still holds anything is kept.`)),process.stdout.write(`${a.join(`
@@ -89,7 +89,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
89
89
  `);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function Im(e){return new j(`name-check`).description(`Check if owner/name is available on GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Fm(t,await e())})}async function Lm(e){try{let t=[],n=await e.users.getAuthenticated();t.push({login:n.data.login,kind:`user`,avatarUrl:n.data.avatar_url});for await(let n of e.paginate.iterator(e.orgs.listMembershipsForAuthenticatedUser,{state:`active`,per_page:100}))for(let e of n.data)(e.permissions?.can_create_repository===!0||e.role===`admin`)&&t.push({login:e.organization.login,kind:`org`,avatarUrl:e.organization.avatar_url??void 0});return{kind:`ok`,owners:t}}catch(e){return e.status===401?{kind:`auth-required`}:{kind:`network`}}}async function Rm(e,t){let{host:n,json:r}=e;oo(n);let i=await gs(n,t);if(i==null){if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=await Lm(new ls({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function zm(e){return new j(`owners`).description(`List GitHub owners eligible to host a new repository`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Rm(t,await e())})}function Bm(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
90
90
  `)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function Vm(e){let{octokit:t,ownerLogin:n,ownerKind:r,name:i,visibility:a,description:o}=e,s=a===`private`;if(r===`user`){let{data:e}=await t.repos.createForAuthenticatedUser({name:i,private:s,...o?{description:o}:{}});return{cloneUrl:e.clone_url,defaultBranch:e.default_branch??`main`}}let{data:c}=await t.repos.createInOrg({org:n,name:i,visibility:a,...o?{description:o}:{}});return{cloneUrl:c.clone_url,defaultBranch:c.default_branch??`main`}}async function Hm(e,t,n){try{let{data:r}=await e.repos.get({owner:t,repo:n});return{cloneUrl:r.clone_url,defaultBranch:r.default_branch??`main`}}catch{return null}}async function Um(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function Wm(e,t){return t===void 0?A($s(e,[])).env(qs()):A($s(e,Hs(Ys(),t.host))).env(Js({relayToken:t}))}function Gm(e){if(!e.startsWith(`https://`))return!1;try{return new URL(e).hostname===`github.com`}catch{return!1}}const Km={ensureOkScaffold:e=>{ct(e)},gitFactory:Wm};async function qm(e){let t={...Km,...e.deps},n=V(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await Um(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:Bm(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n),a=z(n,`.git`);if(!H(a))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let o;try{o=await Vm({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(Bm(t)===`name-conflict`){let t=await Hm(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};o=t}else return{kind:`error`,code:Bm(t)}}try{await i.addRemote(`origin`,o.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let s=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{s=!0}if(s)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let c=Gm(o.cloneUrl)?t.gitFactory(n,{token:e.token,host:`github.com`}):i;try{await c.raw([`push`,o.cloneUrl,`HEAD:refs/heads/${o.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${o.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:o.cloneUrl,defaultBranch:o.defaultBranch}}}function Jm(e,t){if(!e){t.kind===`ok`?process.stdout.write(`✓ Published ${t.value.cloneUrl}\n`):(process.stderr.write(`✗ share publish failed: ${t.code}\n`),process.exit(1));return}if(t.kind===`ok`){process.stdout.write(`${JSON.stringify({type:`publish`,...t.value})}\n`);return}process.stdout.write(`${JSON.stringify({type:`error`,code:t.code})}\n`)}async function Ym(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;if(oo(n),Zt(s)){process.stderr.write(`${new Wt(V(s)).message}\n`),process.exitCode=64;return}if(Ln(s)){process.stderr.write(`${new ot(V(s)).message}\n`),process.exitCode=64;return}let l=await gs(n,t);if(l==null){Jm(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new ls({auth:l,...u?{baseUrl:u}:{}});try{da(`git config user.email`,k({cwd:s,stdio:`ignore`}))}catch{process.env.GIT_AUTHOR_NAME??=`OpenKnowledge`,process.env.GIT_AUTHOR_EMAIL??=`noreply@inkeep.com`,process.env.GIT_COMMITTER_NAME??=`OpenKnowledge`,process.env.GIT_COMMITTER_EMAIL??=`noreply@inkeep.com`}Jm(c,await qm({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function Xm(e){return new j(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
91
91
  `),process.exit(1)),await Ym(t,await e())})}function Zm(){let e=new j(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let t=()=>_i();return e.addCommand(zm(t)),e.addCommand(Im(t)),e.addCommand(Xm(t)),e}function Qm(e){if(e.length!==0){process.stderr.write(` Cleared ${e.length} stale entry(s) left by an older version:\n`);for(let t of e)process.stderr.write(` ${t}\n`)}}function $m(){return new j(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=V(e.project??process.cwd()),n=Gr(t),r=ni(t,n);if(r.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:r.tracked,remediation:r.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${r.remediation}\n`);process.exitCode=1;return}if(r.kind===`no-exclude`){eh(e.json,t,r.reason);return}let i=ui(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:i,appended:r.appended,alreadyPresent:r.alreadyPresent,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(r.appended.length===0){if(r.removed.length>0){process.stderr.write(`${P(`✓`)} ${L(`Sharing mode is already`)} ${P(`local-only`)}${L(`.`)}\n`),Qm(r.removed);return}process.stderr.write(`${L(`Sharing mode is already`)} ${P(`local-only`)} ${L(`— nothing to do.`)}\n`);return}process.stderr.write(`${P(`✓`)} ${L(`Sharing mode set to`)} ${P(`local-only`)}\n`),process.stderr.write(` Added ${r.appended.length} path(s) to ${L(`.git/info/exclude`)} (per-clone, not committed).\n`),Qm(r.removed)})}function eh(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${I({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function th(){return new j(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=V(e.project??process.cwd()),n=ui(t),r=Gr(t),i=qr(t,r);if(i.kind===`no-exclude`){nh(e.json,t,i.reason);return}let a=ui(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:a,removed:i.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){if(i.removed.length>0){process.stderr.write(`${P(`✓`)} ${M(`Sharing mode is already`)} ${L(`shared`)}${M(`.`)}\n`),Qm(i.removed);return}process.stderr.write(`${M(`Sharing mode is already`)} ${L(`shared`)} ${M(`— nothing to do.`)}\n`);return}process.stderr.write(`${P(`✓`)} ${L(`Sharing mode set to`)} ${P(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${L(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function nh(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${I({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function rh(){return new j(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=V(e.project??process.cwd()),n=ui(t),r=[...ti(t)],i=Jr(t,Gr(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`OpenKnowledge sharing mode: ${ih(n)}`),a.push(``),a.push(`Excluded from git via ${L(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${M(`${l()} config-sharing ${n===`local-only`?`share`:`unshare`}`)}`),process.stdout.write(`${a.join(`
92
- `)}\n`)})}function ih(e){switch(e){case`shared`:return P(`shared`);case`local-only`:return P(`local-only`);case`no-git`:return I(`no-git (not a git repository)`)}}function ah(){let e=new j(`config-sharing`);return e.description(`Manage OpenKnowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(th()),e.addCommand($m()),e.addCommand(rh()),e}const oh=new Set([`--cwd`,`--log-level`,`--project`,`--scope`]);function sh(e){let t=[],n=null,r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`--help`||o===`-h`||o===`--version`||o===`-V`){i=!0;break}if(oh.has(o)){let t=e[a+1]??null;o===`--cwd`&&(n=t),o===`--project`&&(r=t),a++;continue}if(o.startsWith(`--cwd=`)){n=o.slice(6);continue}if(o.startsWith(`--project=`)){r=o.slice(10);continue}o.startsWith(`-`)||t.push(o)}return{operands:t,cwd:n,project:r,sawTerminalFlag:i}}function ch(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function lh(e){return/\.(md|mdx)$/i.test(e)}function uh(e,t){if(lh(t))return!0;try{return K(e).isFile()}catch(t){let n=t?.code;return n!==`ENOENT`&&n!==`ENOTDIR`&&process.stderr.write(`[ok] statSync failed for ${e} (${n??`unknown`}); treating as non-fileish\n`),!1}}function dh(e,t){let n=sh(e);if(n.sawTerminalFlag)return null;let r=n.cwd?t.resolvePath(t.cwd,n.cwd):t.cwd,i=ch(n.operands,{knownSubcommands:t.knownSubcommands,isFileish:e=>t.isFileish(t.resolvePath(r,e),e)});return i===null?null:{absPath:t.resolvePath(r,i),projectRoot:n.project===null?null:t.resolvePath(r,n.project)}}function fh(e=()=>ki(Ei())){return{prepare:Ze,detectDesktopApp:()=>Di(e()),openTarget:Rp,runProjectOpen:(e,t)=>Wp(e,{project:t},Bp()),runBrowserOpen:e=>mh(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function ph(e,t,n={}){let r;try{r=t.prepare(e,{projectRoot:n.projectRoot})}catch(e){if(e instanceof nt||e instanceof at||e instanceof kt||e instanceof Dn)return t.error(e.message),1;throw e}if(r.mode===`project`)return await t.runProjectOpen(r.docName,r.projectRoot);let i=t.detectDesktopApp();if(i){let e=`${i.protocolScheme}://open?file=${encodeURIComponent(r.canonicalFilePath)}`,n=await t.openTarget(e,{desktopBundlePath:i.bundlePath});return n.ok?(t.log(`Opening ${r.singleDocRelPath} in the OpenKnowledge desktop app.`),0):(t.error(`Could not open the OpenKnowledge desktop app: ${zp(n.reason,e)}.`),1)}return await t.runBrowserOpen(r),0}async function mh(e){let{createEphemeralProjectDir:t}=await import(`./dist-eiP2xn_A.mjs`),{loadConfig:n}=await import(`./src-BA_wxupY.mjs`),{bootStartServer:r,resolveBundledReactShellDir:i,resolveHost:a}=await import(`./start-C1as3B3R.mjs`),{openBrowser:o}=await import(`./open-browser-Bdh6sD0e.mjs`),s=i();s||(process.stderr.write("OpenKnowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let c=t(e.contentDir),l=!1,u,d=async e=>{if(!l){l=!0;try{await u?.destroy(`external-signal`,{signal:e})}catch{}try{await sa(c,{recursive:!0,force:!0})}catch{}}},f=e=>{d(e).then(()=>process.exit(0))};process.once(`SIGINT`,f),process.once(`SIGTERM`,f);let{config:p}=n(c),m=a({},process.env);try{u=await r({config:p,cwd:c,host:m,port:0,projectDir:c,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:s,idleThresholdMs:6e5})}catch(t){await d(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let h=`http://${m}:${u.port}/#/${nn(e.docName)}`;process.env.OK_SINGLE_FILE_NO_OPEN===`1`?process.stdout.write(`Serving ${e.singleDocRelPath} (headless) at: ${h}\n`):(process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${h}\n`),process.stdout.write(`Press Ctrl-C to close the session.
92
+ `)}\n`)})}function ih(e){switch(e){case`shared`:return P(`shared`);case`local-only`:return P(`local-only`);case`no-git`:return I(`no-git (not a git repository)`)}}function ah(){let e=new j(`config-sharing`);return e.description(`Manage OpenKnowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(th()),e.addCommand($m()),e.addCommand(rh()),e}const oh=new Set([`--cwd`,`--log-level`,`--project`,`--scope`]);function sh(e){let t=[],n=null,r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`--help`||o===`-h`||o===`--version`||o===`-V`){i=!0;break}if(oh.has(o)){let t=e[a+1]??null;o===`--cwd`&&(n=t),o===`--project`&&(r=t),a++;continue}if(o.startsWith(`--cwd=`)){n=o.slice(6);continue}if(o.startsWith(`--project=`)){r=o.slice(10);continue}o.startsWith(`-`)||t.push(o)}return{operands:t,cwd:n,project:r,sawTerminalFlag:i}}function ch(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function lh(e){return/\.(md|mdx)$/i.test(e)}function uh(e,t){if(lh(t))return!0;try{return K(e).isFile()}catch(t){let n=t?.code;return n!==`ENOENT`&&n!==`ENOTDIR`&&process.stderr.write(`[ok] statSync failed for ${e} (${n??`unknown`}); treating as non-fileish\n`),!1}}function dh(e,t){let n=sh(e);if(n.sawTerminalFlag)return null;let r=n.cwd?t.resolvePath(t.cwd,n.cwd):t.cwd,i=ch(n.operands,{knownSubcommands:t.knownSubcommands,isFileish:e=>t.isFileish(t.resolvePath(r,e),e)});return i===null?null:{absPath:t.resolvePath(r,i),projectRoot:n.project===null?null:t.resolvePath(r,n.project)}}function fh(e=()=>ki(Ei())){return{prepare:Ze,detectDesktopApp:()=>Di(e()),openTarget:Rp,runProjectOpen:(e,t)=>Wp(e,{project:t},Bp()),runBrowserOpen:e=>mh(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function ph(e,t,n={}){let r;try{r=t.prepare(e,{projectRoot:n.projectRoot})}catch(e){if(e instanceof nt||e instanceof at||e instanceof kt||e instanceof Dn)return t.error(e.message),1;throw e}if(r.mode===`project`)return await t.runProjectOpen(r.docName,r.projectRoot);let i=t.detectDesktopApp();if(i){let e=`${i.protocolScheme}://open?file=${encodeURIComponent(r.canonicalFilePath)}`,n=await t.openTarget(e,{desktopBundlePath:i.bundlePath});return n.ok?(t.log(`Opening ${r.singleDocRelPath} in the OpenKnowledge desktop app.`),0):(t.error(`Could not open the OpenKnowledge desktop app: ${zp(n.reason,e)}.`),1)}return await t.runBrowserOpen(r),0}async function mh(e){let{createEphemeralProjectDir:t}=await import(`./dist-Ttulen40.mjs`),{loadConfig:n}=await import(`./src-BjiiSghS.mjs`),{bootStartServer:r,resolveBundledReactShellDir:i,resolveHost:a}=await import(`./start-MRWYWYqt.mjs`),{openBrowser:o}=await import(`./open-browser-kL892VYi.mjs`),s=i();s||(process.stderr.write("OpenKnowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let c=t(e.contentDir),l=!1,u,d=async e=>{if(!l){l=!0;try{await u?.destroy(`external-signal`,{signal:e})}catch{}try{await sa(c,{recursive:!0,force:!0})}catch{}}},f=e=>{d(e).then(()=>process.exit(0))};process.once(`SIGINT`,f),process.once(`SIGTERM`,f);let{config:p}=n(c),m=a({},process.env);try{u=await r({config:p,cwd:c,host:m,port:0,projectDir:c,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:s,idleThresholdMs:6e5})}catch(t){await d(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let h=`http://${m}:${u.port}/#/${nn(e.docName)}`;process.env.OK_SINGLE_FILE_NO_OPEN===`1`?process.stdout.write(`Serving ${e.singleDocRelPath} (headless) at: ${h}\n`):(process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${h}\n`),process.stdout.write(`Press Ctrl-C to close the session.
93
93
  `),o(h)),await new Promise(()=>{})}function hh(){let e=new j(`skills`).description(`Manage Open Knowledge skills for this project.`);return e.command(`installed`).description(`List every skill installed across all your agents (read-only).`).option(`--json`,`Emit the raw enumeration as JSON.`).action(e=>{let t=V(process.cwd()),n=In(Vr(t)?.rootPath??t),r=cn({projectDir:n}),i={...r,skills:r.skills.filter(e=>lt(e.provenance,n))};if(e.json){process.stdout.write(`${JSON.stringify(i,null,2)}\n`);return}if(i.skills.length===0){process.stdout.write(`${N(`No installed skills found across any agent.`)}\n`);return}process.stdout.write(`${L(`${i.skills.length} installed skill(s):`)}\n`);for(let e of i.skills){let t=e.provenance.version?N(` v${e.provenance.version}`):``,n=[e.inert.commands&&`commands`,e.inert.hooks&&`hooks`,e.inert.mcp&&`mcp`].filter(Boolean),r=n.length>0?N(` [${n.join(`, `)}]`):``;process.stdout.write(` ${P(e.name)}${t} ${N(e.sourceHarnesses.join(`, `))}${r}\n`)}process.stdout.write(`\n${L(`${i.packs.length} pack(s):`)}\n`);for(let e of i.packs)process.stdout.write(` ${M(e.name)} ${N(`v${e.version}`)} — ${e.skills.length} skill(s)\n`)}),e.command(`import <source>`).description(`Import a skill into this project as versioned content (github owner/repo, a git URL, or a local path).`).option(`--skill <name>`,`Pick one skill from a multi-skill source.`).option(`--scope <scope>`,`project (default) or global.`,`project`).action(async(e,t)=>{let n=O(process.cwd()),r=lr(n,`server`);if(r.status!==`alive`){process.stderr.write(`${F(`Error:`)} no running Open Knowledge server for this project. Start it with ${L(`${l()} start`)} and retry.\n`),process.exitCode=1;return}let i;try{i=await fetch(`http://127.0.0.1:${r.lock.port}/api/skill/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({source:e,...t.skill?{skill:t.skill}:{},scope:t.scope===`global`?`global`:`project`})})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${F(`Error:`)} could not reach the server: ${t}\n`),process.exitCode=1;return}let a=await i.json().catch(()=>({}));if(!i.ok){let e=typeof a.title==`string`?a.title:void 0,t=typeof a.detail==`string`?a.detail:void 0,n=e?t?`${e} (${t})`:e:t??`HTTP ${i.status}`;process.stderr.write(`${F(`Import failed:`)} ${n}\n`),process.exitCode=1;return}let o=a.name;if(a.alreadyImported){process.stdout.write(`${M(`Already imported:`)} ${L(o)} (identical content).\n`);return}let s=a.provenance??{},c=a.collisionRenamedFrom;process.stdout.write(`${P(`Imported`)} ${L(o)}${c?N(` (renamed from ${c} — name was taken)`):``} from ${N(s.source??e)}${s.publisher?N(` · ${s.publisher}`):``}.\n${N(`Saved as versioned content in this project's skill home. Scripts shown, never run. Use the skill's install menu (or the install MCP verb) to add it to your other editors.`)}\n`);for(let e of a.warnings??[])process.stdout.write(` ${N(`! ${e}`)}\n`)}),e}function gh(e){return{server:_h(`server`,e),ui:e.status===`alive`&&rn(e.lock)?{name:`ui`,state:`alive`,pid:e.lock.pid,port:e.lock.port,startedAt:e.lock.startedAt,host:e.lock.hostname,alive:!0,servedByServer:!0}:{name:`ui`,state:`missing`,alive:!1}}}function _h(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`read-error`:return{name:e,state:`read-error`,alive:`unknown`};case`unverified-owner`:return{name:e,state:`unverified-owner`,pid:t.pid,alive:`unknown`};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:case`reused-pid`:return{name:e,state:t.status,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function vh(e){return`${yh(e.server)}\n${yh(e.ui)}`}function yh(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`${l()} clean\``:e.state===`read-error`?`${t} lock file unreadable — restore file and parent-directory access, then retry`:e.state===`unverified-owner`?`${t} unverified owner (lock records no machine) pid=${e.pid} is alive locally; server identity unknown`:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`${l()} clean\``:e.state===`reused-pid`?`${t} stale (pid=${e.pid} now belongs to another process); run \`${l()} clean\``:e.servedByServer===!0?`${t} served by server pid=${e.pid} port=${e.port}`:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function bh(e){let t=e.inspect??(()=>lr(e.lockDir,`server`)),n=e.log??(e=>console.log(e)),r=gh(t());return e.json?n(JSON.stringify(r,null,2)):n(vh(r)),r}function xh(e){return new j(`status`).description(`Show whether the server and UI are running for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),bh({lockDir:O(process.cwd()),json:t.json===!0})})}function Sh(e){if(e.yes===!0||e.json===!0)return!1;let t=e.stdinIsTTY??process.stdin.isTTY,n=e.stdoutIsTTY??process.stdout.isTTY;return t===!0&&n===!0}async function Ch(e,t){let n=ga({input:e.input,output:e.output});try{return(await n.question(t)).trim()}finally{n.close()}}async function wh(e={}){let t={input:e.input??process.stdin,output:e.output??process.stderr};t.output.write(N(`
94
94
  What you share is sent to the OpenKnowledge team.
95
95
  `));let n=await Wr({message:`Before you go, mind sharing why? (optional)`,default:null,pageSize:he.length+1,choices:[...he.map(e=>({name:e.label,value:e.value})),{name:`Skip, I'd rather not say`,value:null}]},t);if(n===null)return{};let r=await Ch(t,N(`Anything else we should know? (optional) `)),i=await Ch(t,N(`Email, if we may follow up (optional) `));return{reason:n,note:r||void 0,email:i||void 0}}async function Th(e){if(!Sh(e))return`not-prompted`;let t;try{t=await(e.collect??(()=>wh(e)))()}catch{return`failed`}return ie(t)?((e.output??process.stderr).write(`\n${L(`Thank you. We read every response.`)}\n\n`),(await(e.submit??Be)({...t,source:`cli_uninstall`,appVersion:e.appVersion,platform:e.platform})).ok?`submitted`:`undelivered`):`skipped`}function Eh(e,t,n=Ah,r=H,i={}){let o=[],s=i.platform??process.platform,l=i.env??process.env,d=ji(Ti(l,i.execPath??process.execPath)).map(e=>a[e]);if(s===`darwin`)for(let t of d)for(let n of[`/Applications`,z(e,`Applications`)]){let e=z(n,`${t.productName}.app`);r(e)&&o.push({method:`app`,label:`${t.productName} (${e})`,instruction:`Move ${e} to the Trash (or: rm -rf "${e}")`})}else if(s===`win32`){let e=l.LOCALAPPDATA;if(e)for(let t of d)for(let n of u(t)){let i=z(e,`Programs`,n,c(t));if(r(i)){o.push({method:`app`,label:`${t.productName} (${i})`,instruction:`Uninstall from Windows Settings → Apps → Installed apps → ${t.productName}`});break}}}else if(s===`linux`){let e=i.queryPackageDatabase??Dh;for(let t of d){let n=`/opt/${t.productName}`,i=z(n,t.linuxExecutableName);if(r(i)){let{deb:r,rpm:a}=t.linuxPackageNames,s=kh(i,e);o.push({method:`app`,label:`${t.productName} (${n})`,instruction:`Remove with your package manager: ${s===null?`sudo apt remove ${r} (Debian/Ubuntu), ${Oh(a)}`:s.format===`deb`?`sudo apt remove ${s.name}`:Oh(s.name)}`})}}}return n([`ls`,`-g`,`--depth=0`,`@inkeep/open-knowledge`])?.includes(`@inkeep/open-knowledge@`)&&o.push({method:`npm-global`,label:`npm global install`,instruction:`npm uninstall -g @inkeep/open-knowledge`}),t&&/[/\\]_npx[/\\]/.test(t)&&o.push({method:`npx`,label:`npx (ephemeral)`,instruction:`Nothing to uninstall — npx runs from a temporary cache. (Optional: npm cache clean --force)`}),o}function Dh(e,t){try{return ua(e,t,k({encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}))}catch{return null}}function Oh(e){return`sudo dnf remove ${e} (Fedora/RHEL) or sudo zypper remove ${e} (openSUSE)`}function kh(e,t){let n=t(`dpkg-query`,[`-S`,e])?.split(`
package/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{i as e,n as t,r as n}from"./git-credential-operation-9lLcCrJB.mjs";e(import.meta.url);const r=t(process.argv.slice(2));if(r===`get`){let{runGitCredentialGet:e}=await import(`./git-credential-helper-DY8W25nc.mjs`);process.exit(await e())}r!==null&&process.exit(await n(r,process.stdin)),await import(`./compile-B66Xl_UG.mjs`),await import(`./cli-CApr5vJh.mjs`);export{};
2
+ import{i as e,n as t,r as n}from"./git-credential-operation-9lLcCrJB.mjs";e(import.meta.url);const r=t(process.argv.slice(2));if(r===`get`){let{runGitCredentialGet:e}=await import(`./git-credential-helper-DY8W25nc.mjs`);process.exit(await e())}r!==null&&process.exit(await n(r,process.stdin)),await import(`./compile-B66Xl_UG.mjs`),await import(`./cli-BWG-Aq4r.mjs`);export{};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-B5Gyjk_N.mjs";var e=`0.88.9-beta.5`;const t=`config.yml`,n=e;export{n,t};