@inkeep/open-knowledge 0.61.2 → 0.61.3
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.
- package/dist/{acp-harness-probe-Bc-CWfz4.mjs → acp-harness-probe-t1lJvQ4a.mjs} +2 -2
- package/dist/cli.mjs +11 -11
- package/dist/constants-D3GZn-dk.mjs +2 -0
- package/dist/{fs-traced-1KTQL4h-.mjs → fs-traced-2B_-YK-g.mjs} +6 -6
- package/dist/fs-traced-DjggEXdh.mjs +1 -0
- package/dist/{git-handle-BnzI58ud.mjs → git-handle-CdQzaja5.mjs} +2 -2
- package/dist/git-handle-Clxj9fr-.mjs +1 -0
- package/dist/index.mjs +161 -161
- package/dist/{init-DDW2aJXW.mjs → init-5SqrHOkp.mjs} +3 -3
- package/dist/init-C7HKweMR.mjs +1 -0
- package/dist/{launch-json-removal-J6AggXic.mjs → launch-json-removal-DM5PCMXP.mjs} +2 -2
- package/dist/{loader-D_NNhPbU.mjs → loader-DsWNpxDe.mjs} +2 -2
- package/dist/loader-Osy-rk3T.mjs +1 -0
- package/dist/md-manager-DbxE4WzN.mjs +2 -0
- package/dist/{open-browser-CB0sbYH4.mjs → open-browser-xN9OlX1t.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/preview-DAuizf4r.mjs +1 -0
- package/dist/{preview-46yeY8SC.mjs → preview-DMJ3NAED.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-rkVFPeGI.js → ActivityModeContent-Cn-W_Pc9.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-UM3yi_Jj.js → AgentDiffPane-fqyn3qqK.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-DbKx5B2j.js → AgentThreadClientBinder-BUL6vwPz.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-SvCCpq_g.js → CodeMirrorPropInput-ZXKkJFOY.js} +1 -1
- package/dist/public/assets/{DocumentContext-BrlDlUx7.js → DocumentContext-CuOcLr_j.js} +7 -7
- package/dist/public/assets/{EditorModeToggle-Coj-pKbp.js → EditorModeToggle-rmR5bMw6.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-CMQPWKxH.js → EnableSyncConfirmDialog-IKFvLJ0s.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-Ct_C78n1.js → ExcalidrawDocEditor-DUdD1MdF.js} +1 -1
- package/dist/public/assets/FeedbackForm-DzgyNjac.js +1 -0
- package/dist/public/assets/{GraphPanel-C4IPsveQ.js → GraphPanel-BdYMWZaF.js} +1 -1
- package/dist/public/assets/{ImportSkillDialog-BUIlH24A.js → ImportSkillDialog-Cf9s-UGN.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-Q1gGaOab.js → LintConfigEditor-DkncZJhY.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-EYfMUx3g.js +1 -0
- package/dist/public/assets/ManagedArtifactProperties-mqQVguq0.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-DBbbNWFO.js → MermaidDocEditor-DLpabb88.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DfLhrMek.js → PropertyDisplayRow-CPeDXIFD.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-D5SrIAvZ.js → ReportBugDialogBody-CCniAzNT.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-CkKt8e-E.js → SchemaConfigEditor-_uHnWU3w.js} +1 -1
- package/dist/public/assets/{SessionsHost-DxbKcTfw.js → SessionsHost-DXGYsgWh.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-BaPG44Cx.js → SettingsDialogBody-75kVL106.js} +5 -5
- package/dist/public/assets/{ShareBranchSwitchDialog-BvkvEHCc.js → ShareBranchSwitchDialog-DgbDAJil.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-C9KNKynH.js → ShareReceiveDialog-DmClGCLD.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-CwqxBbfk.js → ShareReceiveMissDialog-DAxO28Lj.js} +1 -1
- package/dist/public/assets/{SkillCostValue-BvB_BW1x.js → SkillCostValue-zpzjADcj.js} +1 -1
- package/dist/public/assets/{SkillEditBanner-D0gTinuX.js → SkillEditBanner-BCRYQ3e4.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-Cb7qSrC0.js → SkillInstallMenu-QQXII2hZ.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-IRuhZu-j.js → SkillOriginInline-BoAKWsbK.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-6i3dV6vs.js → SkillToolbarControls-ovUDGFiC.js} +1 -1
- package/dist/public/assets/{SlidesToolbarControls-D5EykdNJ.js → SlidesToolbarControls-BBIxMkk8.js} +1 -1
- package/dist/public/assets/{SourceEditor-p9dgTOkJ.js → SourceEditor-fE2VSQ8J.js} +1 -1
- package/dist/public/assets/{TerminalPanel-cl3V5Lv6.js → TerminalPanel-Cy4HfKYz.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BoxazHdg.js → TerminalWindowApp-C6AUY1UG.js} +1 -1
- package/dist/public/assets/{TextDocEditor-DOoM8Kxy.js → TextDocEditor-dLRRDXfg.js} +1 -1
- package/dist/public/assets/{ThreadView-BxvEDVSr.js → ThreadView-D9Fbdpxf.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BPuM41-O.js → TimelineDiffPane-DNnhFpvU.js} +1 -1
- package/dist/public/assets/{agent-diff-store-D7oOrlOa.js → agent-diff-store-CZQtUCXL.js} +1 -1
- package/dist/public/assets/auth-state-cache-CvhGKn1-.js +11 -0
- package/dist/public/assets/{client-version-DPop7QlO.js → client-version-CaChkiCH.js} +1 -1
- package/dist/public/assets/{comment-chips-BSXPyCs1.js → comment-chips-DVNORTJ8.js} +1 -1
- package/dist/public/assets/config-provider-oAAIxoES.js +5 -0
- package/dist/public/assets/{dist-YRM6aCj22.js → dist-DKOit9IV2.js} +192 -192
- package/dist/public/assets/{doc-paths-DHGjMfMc.js → doc-paths-DqOWEocR.js} +1 -1
- package/dist/public/assets/{documents-events-Dh2E-mNH.js → documents-events-CswIH8-8.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-8KZtqBfU.js → file-tree-adapter-Ye2De3V1.js} +1 -1
- package/dist/public/assets/{file-tree-utils-mm4DWltG.js → file-tree-utils-DeewwZEM.js} +1 -1
- package/dist/public/assets/{folder-config-api-ReDuYJ0J.js → folder-config-api-DzbfltNv.js} +1 -1
- package/dist/public/assets/i18n-Ds_Fl5Hd.js +1 -0
- package/dist/public/assets/index-TaCyw6y_.js +2098 -0
- package/dist/public/assets/{lint-config-client-DDlKZf1J.js → lint-config-client-Dwop4dqP.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-Cn61TsP6.js → markdownlint-rule-browser-DH858hZX.js} +1 -1
- package/dist/public/assets/navigation-targets-jpdo1ZgU.js +1 -0
- package/dist/public/assets/{open-managed-artifact-tab-DI0a5-3C.js → open-managed-artifact-tab-CgNN9QbB.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-BQWmsZRi.js → pending-receive-nav-store-fsDdvtOj.js} +1 -1
- package/dist/public/assets/{progress-DKgTQ0Qz.js → progress-CHBPaNjc.js} +1 -1
- package/dist/public/assets/{prop-types-aV6oiD-U.js → prop-types-Cw5N-nOD.js} +1 -1
- package/dist/public/assets/{receive-store-D1fi7HMJ.js → receive-store-DFDJ0T_F.js} +1 -1
- package/dist/public/assets/{selection-context-4KGHvsgP.js → selection-context-CS5s5L53.js} +1 -1
- package/dist/public/assets/{skill-actions-BndTKw4P.js → skill-actions-CONIft3w.js} +1 -1
- package/dist/public/assets/{skill-scope-TpOVvXXj.js → skill-scope-C_bc3f6T.js} +1 -1
- package/dist/public/assets/{skills-api-Ci4vZCl_.js → skills-api-B3AiUodv.js} +1 -1
- package/dist/public/assets/{src-Dyjlw1SL.js → src-Dn75jB9p.js} +1 -1
- package/dist/public/assets/{tag-pill-input-ltY20AtL.js → tag-pill-input-BFR_8nvj.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-Bq0cHa0H.js → target-navigation-intent-5nit-2Ve.js} +1 -1
- package/dist/public/assets/{terminal-cli-display-MwCkMfQx.js → terminal-cli-display-DQFap0a9.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-cj2KCTDl.js → terminal-launch-events-DxtBCSNL.js} +1 -1
- package/dist/public/assets/{terminal-telemetry-ElOB2Hsl.js → terminal-telemetry-Cq512ASb.js} +1 -1
- package/dist/public/assets/typing-burst-detector-Bhy83GCZ.js +8 -0
- package/dist/public/assets/{uninstall-CJfdIccl.js → uninstall-VS8HkqWd.js} +1 -1
- package/dist/public/assets/{use-activity-panel-AklD6yAB.js → use-activity-panel-BPQcffqO.js} +1 -1
- package/dist/public/assets/{use-apply-config-color-theme-zpd8fyW1.js → use-apply-config-color-theme-DT9ZBAuW.js} +1 -1
- package/dist/public/assets/{use-collab-url-BIoe0OLV.js → use-collab-url-CaC2gD2v.js} +1 -1
- package/dist/public/assets/{use-live-xterm-theme-BgtSx-n3.js → use-live-xterm-theme-xXp1UYmJ.js} +1 -1
- package/dist/public/assets/{use-open-skill-CLhiKLe2.js → use-open-skill-DdfCbjRH.js} +1 -1
- package/dist/public/assets/{use-popular-skills-CSwbHrqM.js → use-popular-skills-DRwm43Dp.js} +1 -1
- package/dist/public/assets/{use-settings-route-BuFQqdtV.js → use-settings-route-BGxa3SPN.js} +1 -1
- package/dist/public/assets/{use-skill-origin-CbbiS8DZ.js → use-skill-origin-CnlwuiEX.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-GezhypT9.js → use-terminal-enabled-B3CRPNAH.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-DyOMjIES.js → use-timeline-entry-diff-Cta4x9Tk.js} +1 -1
- package/dist/public/assets/{use-workspace-C3C8xAY5.js → use-workspace-CQYB3HLR.js} +1 -1
- package/dist/public/index.html +45 -45
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-CEDu8wqf.mjs → repair-launch-json-Ul9-Kphl.mjs} +2 -2
- package/dist/{repair-mcp-configs-Bf5i53AU.mjs → repair-mcp-configs-DI9-mCNA.mjs} +2 -2
- package/dist/repair-skills-C4NosCCh.mjs +1 -0
- package/dist/{repair-skills-Cs-CbtpF.mjs → repair-skills-DySL7Lc9.mjs} +2 -2
- package/dist/{resolve-project-root-BD_5TDzP.mjs → resolve-project-root-BDV317uB.mjs} +2 -2
- package/dist/{server-lock-DCzdk2Up.mjs → server-lock-BFHu2BWp.mjs} +2 -2
- package/dist/server-lock-DzPLyikk.mjs +1 -0
- package/dist/{skill-teardown-TMX-h8on.mjs → skill-teardown-DTg2NyL3.mjs} +2 -2
- package/dist/{sleep-DXvB05wr.mjs → sleep-DhRrtbfG.mjs} +6 -6
- package/dist/src-B9XENgF4.mjs +357 -0
- package/dist/{src-D28v5dI-.mjs → src-BMc6VYxR.mjs} +1 -1
- package/dist/{src-BUvdZk4h.mjs → src-BpAtKjdr.mjs} +3 -3
- package/dist/src-C49kugTg.mjs +1 -0
- package/dist/{src-vJKK8Bgd.mjs → src-C8z0M4Ib.mjs} +71 -71
- package/dist/start-De77XKSr.mjs +1 -0
- package/dist/{start-oZSin_Cq.mjs → start-R7eR24jP.mjs} +3 -3
- package/package.json +5 -5
- package/dist/constants-DwCeIiph.mjs +0 -2
- package/dist/fs-traced-Dak_kryQ.mjs +0 -1
- package/dist/git-handle-M-kQfBzM.mjs +0 -1
- package/dist/init-BF-FV5qg.mjs +0 -1
- package/dist/loader-CnYTkLbq.mjs +0 -1
- package/dist/md-manager-C7XAJMWr.mjs +0 -2
- package/dist/preview-DCrZ6Og7.mjs +0 -1
- package/dist/public/assets/FeedbackForm-CYAmtIjK.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-B4xOs3fA.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-DUIo-gDU.js +0 -1
- package/dist/public/assets/auth-state-cache-1gTw3GkH.js +0 -11
- package/dist/public/assets/config-provider-CYqYSyJg.js +0 -5
- package/dist/public/assets/i18n-BQpXlvfY.js +0 -1
- package/dist/public/assets/index-dbxZtLCX.js +0 -2098
- package/dist/public/assets/navigation-targets-CFQds_7M.js +0 -1
- package/dist/public/assets/typing-burst-detector-kXx1cN6a.js +0 -8
- package/dist/repair-skills-Bn47U59J.mjs +0 -1
- package/dist/server-lock-CV9U-jz6.mjs +0 -1
- package/dist/src-DUFkX7vo.mjs +0 -1
- package/dist/src-Dm-FGyIz.mjs +0 -357
- package/dist/start-CuUojA75.mjs +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{o as e}from"./chunk-DTipWd-i.mjs";import{At as t,
|
|
2
|
+
import{o as e}from"./chunk-DTipWd-i.mjs";import{At as t,Ct as n,E as r,It as i,M as a,Mt as o,St as s,T as c,Ut as l,_t as u,a as d,c as f,jt as p,kt as m,nn as h,p as g,pt as _,xt as v,zt as y}from"./sleep-DhRrtbfG.mjs";import{Aa as b,Bo as x,Bs as S,Bt as C,Ec as ee,Ho as te,J as ne,Ls as re,Ms as ie,Ns as ae,Vo as oe,Vt as se,Xs as ce,as as le,bs as ue,ca as de,hc as fe,is as pe,k as me,ka as he,ks as ge,ps as _e,pt as ve,qa as ye,qo as be,sa as xe,st as Se,vs as Ce,ws as we}from"./src-B9XENgF4.mjs";import{$ as Te,Ci as w,Cn as Ee,Da as De,Ea as Oe,F as ke,Fn as Ae,Ft as je,Ht as Me,I as Ne,It as Pe,J as Fe,L as Ie,Lt as Le,Mi as Re,Mr as ze,Oa as Be,P as Ve,Pn as He,Pr as Ue,Pt as We,Q as Ge,Si as Ke,Ta as qe,Vt as Je,Wr as Ye,X as Xe,Yt as Ze,Z as Qe,_ as $e,_n as et,_t as tt,a as nt,at as rt,bn as it,ci as at,dt as ot,ei as T,f as st,fi as ct,ft as lt,ht as ut,ii as dt,in as ft,ir as pt,ji as mt,jr as ht,kr as gt,lt as _t,mt as vt,n as yt,nn as bt,ot as xt,p as St,pi as Ct,pt as wt,r as Tt,rt as Et,si as Dt,st as Ot,t as kt,tn as At,ut as jt,w as Mt,wi as Nt,xi as Pt}from"./src-C8z0M4Ib.mjs";import{A as E,F as Ft,I as It,k as Lt}from"./fs-traced-2B_-YK-g.mjs";import{s as Rt}from"./git-handle-CdQzaja5.mjs";import{S as zt,a as Bt,b as D,d as Vt,r as Ht}from"./server-lock-BFHu2BWp.mjs";import{_ as Ut,a as Wt,b as O,r as Gt,s as Kt,v as qt}from"./resolve-project-root-BDV317uB.mjs";import{b as Jt,c as Yt,d as Xt,f as Zt,g as Qt,h as $t,i as en,l as tn,m as nn,n as rn,o as an,p as on,r as sn,t as cn,u as ln,v as un,y as dn}from"./src-BpAtKjdr.mjs";import{c as fn,i as k,n as A,o as j,r as M,s as N,t as P}from"./colors-DSyAT9Cz.mjs";import{a as pn,c as mn,d as hn,i as gn,l as _n,p as vn,r as yn,s as bn,u as xn}from"./acp-harness-probe-t1lJvQ4a.mjs";import{n as Sn,r as Cn,t as wn}from"./dist-bundle-EXrl9_Zm.mjs";import{A as Tn,B as En,C as Dn,D as On,F as kn,I as An,L as jn,M as Mn,N as Nn,P as Pn,R as Fn,S as In,V as Ln,j as Rn,k as zn,u as Bn,w as Vn,z as Hn}from"./init-5SqrHOkp.mjs";import{n as Un,t as Wn}from"./constants-D3GZn-dk.mjs";import{n as Gn,t as Kn}from"./loader-DsWNpxDe.mjs";import{g as qn,y as Jn}from"./start-R7eR24jP.mjs";import{i as Yn}from"./skill-teardown-DTg2NyL3.mjs";import{t as Xn}from"./launch-json-removal-DM5PCMXP.mjs";import{n as Zn}from"./repair-skills-DySL7Lc9.mjs";import{execFile as Qn,execFileSync as $n,execSync as er,spawn as tr,spawnSync as nr}from"node:child_process";import{basename as rr,dirname as F,isAbsolute as ir,join as I,posix as ar,relative as L,resolve as R,sep as or}from"node:path";import sr from"node:process";import{fileURLToPath as cr}from"node:url";import{accessSync as lr,appendFileSync as ur,closeSync as dr,constants as fr,existsSync as z,lstatSync as pr,mkdirSync as B,mkdtempSync as mr,openSync as hr,readFileSync as V,readdirSync as gr,realpathSync as _r,renameSync as vr,rmSync as yr,statSync as H,unlinkSync as U,writeFileSync as br}from"node:fs";import{homedir as xr,platform as Sr,tmpdir as Cr}from"node:os";import{rm as wr}from"node:fs/promises";import{randomUUID as Tr}from"node:crypto";import{setTimeout as Er}from"node:timers/promises";import{promisify as Dr}from"node:util";import{createInterface as Or}from"node:readline/promises";const kr={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 Ar;(function(e){})(Ar||={});function jr(e){return l(u,e)}async function Mr(e){let{projectDir:t,contentDir:n,baseConfig:r,targetPath:i,fix:a=!1}=e,o=[],s=Ye({projectDir:t,contentDir:n}),c=new Set,l=e=>{c.has(e)||(c.add(e),o.push(e))},u=ze(t,r,l),d=new Map,f=e=>{let t=F(e),r=d.get(t);if(r)return r;let i=ht(u,Ue(n,e,l));return d.set(t,i),i},p=[],m=Nr(i,n);m.kind===`file`?p.push(L(n,m.path)):h(m.path);function h(e){let t;try{t=gr(e,{withFileTypes:!0})}catch(t){o.push(`could not read directory ${L(n,e)||`.`}: ${Fr(t)}`);return}for(let r of t){if(r.name.startsWith(`.`))continue;let t=I(e,r.name),i=L(n,t);if(r.isDirectory()){if(s.isDirExcluded(i))continue;h(t)}else if(r.isFile()){if(!Pr(r.name)||s.isExcluded(i))continue;p.push(i)}}}p.sort();let g=[],_=0,v=0,y=0;for(let e of p){let t=I(n,e),r;try{r=V(t,`utf-8`)}catch(t){o.push(`could not read ${e}: ${Fr(t)}`);continue}let i=f(e),s=!1;if(a&&i.enabled){let n=xe(r,i);if(n!==r){let i=`${t}.tmp.${process.pid}.${Date.now()}`;try{br(i,n,`utf-8`),vr(i,t),r=n,s=!0,y++}catch(t){try{U(i)}catch{}o.push(`could not write fix to ${e}: ${Fr(t)}`)}}}let c=await de(r,i,e);for(let e of c)e.severity===`error`?_++:v++;g.push({file:e,diagnostics:c,fixed:s})}return{contentDir:n,files:g,warnings:o,fileCount:p.length,errorCount:_,warningCount:v,fixedCount:y}}function Nr(e,t){if(e===void 0||e===``)return{kind:`dir`,path:t};let n=ir(e)?e:R(t,e);try{if(H(n).isFile())return{kind:`file`,path:n}}catch{}return{kind:`dir`,path:n}}function Pr(e){let t=e.toLowerCase();return S.some(e=>t.endsWith(e))}function Fr(e){return e instanceof Error?e.message:String(e)}function Ir(e){return new O(`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=Ke(r,i),o=t===void 0?void 0:Lr(t,un()),s=r.contentRules,c=await Mr({projectDir:i,contentDir:a,baseConfig:s?b(s):ye,targetPath:o,fix:n.fix===!0});n.json===!0?process.stdout.write(`${JSON.stringify(c,null,2)}\n`):process.stdout.write(`${Br(c)}\n`),(n.errorsOnly===!0?c.errorCount>0:Rr(c))&&(process.exitCode=1)})}function Lr(e,t){return R(t,e)}function Rr(e){return e.errorCount>0||e.warningCount>0}function zr(e){let t=[P(e.file)+(e.fixed?A(` (fixed)`):``)];for(let n of e.diagnostics){let e=A(`${n.range.start.line+1}:${n.range.start.character+1}`.padEnd(7)),r=n.severity===`error`?M(`error `):N(`warning`);t.push(` ${e} ${r} ${n.message} ${A(`${n.source}/${n.code}`)}`)}return t.push(``),t}function Br(e){let t=[];for(let n of e.files)n.diagnostics.length>0&&t.push(...zr(n));for(let n of e.warnings)t.push(N(`! ${n}`));e.warnings.length>0&&t.push(``);let n=e.errorCount+e.warningCount;if(n===0)t.push(j(`✓ 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(`${M(r[0]??``)} (${r[1]}, ${r[2]}) across ${e.fileCount} file${e.fileCount===1?``:`s`}.`)}return e.fixedCount>0&&t.push(A(`Fixed ${e.fixedCount} file${e.fixedCount===1?``:`s`}.`)),t.join(`
|
|
3
3
|
`)}const Vr={out:e=>process.stdout.write(`${e}\n`),err:e=>process.stderr.write(`${e}\n`)};function Hr(e){return new O(`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 Ur(t,n,e(),process.cwd(),un());r!==0&&(process.exitCode=r)})}async function Ur(e,t,n,r,i,a=Vr){let o=Ke(n,r),s;if(e!==void 0){let t=Wr(e,i,o);if(t===null)return a.err(`Path is outside the content directory (${o}): ${e}`),1;s=t===``?void 0:t}let c=Bt(w(r));if(!c||c.port<=0)return a.err("OpenKnowledge server is not running — the links validator needs the live backlink index. Start it with `ok start` (or open OK Desktop) and re-run. For headless lint-only checks, use `ok lint`."),1;let l=s===void 0?``:`?path=${encodeURIComponent(s)}`,u;try{u=await fetch(`http://127.0.0.1:${c.port}/api/audit${l}`,{headers:ee({kind:`cli`,runtimeVersion:D})})}catch(e){return a.err(`Could not reach the OpenKnowledge server on port ${c.port}: ${String(e)}`),1}if(!u.ok){let e=await u.json().catch(()=>({}));return a.err(`Audit failed: ${e.title??e.error??e.message??`server responded with ${u.status}`}`),1}let d=he.safeParse(await u.json().catch(()=>null));if(!d.success){let e=d.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 f=d.data;return t.json===!0?a.out(JSON.stringify(f,null,2)):a.out(Br(Gr(f))),+(t.errorsOnly===!0?f.errorCount>0:f.errorCount+f.warningCount>0)}function Wr(e,t,n){let r=L(n,R(t,e));return r===``?``:r.startsWith(`..`)||ir(r)?null:r.split(or).join(`/`)}function Gr(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}}async function Kr(e,t,n,r){let i=qr(await Jr(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function qr(e){let t={};for(let n of e.split(`
|
|
4
4
|
`)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function Jr(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Yr(e,t){let n=new O(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let n=t?.();try{let t,r=await e({onKeychainRead:e=>{t=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&n?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await Kr(process.stdin,process.stdout,r,{log:n,getDiag:()=>t});await St(n),process.exit(i)}catch(e){n?.error({err:e},`[auth] git-credential get: unexpected error`),await St(n),process.exit(1)}}),n}function Xr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Zr(e,t,n){let r={baseUrl:Xr(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new Sn(`${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 Qr(e){let t=e.request||wn,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Zr(t,`POST /login/device/code`,n)}async function $r(e){let t=await Zr(e.request||wn,`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=ei(e,t.data.expires_in),n.refreshTokenExpiresAt=ei(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function ei(e,t){return new Date(e+t*1e3).toISOString()}async function ti(e,t){let n=ni(e,t.auth);if(n)return n;let{data:r}=await Qr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await ii(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function ni(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:!1}async function ri(e){await new Promise(t=>setTimeout(t,e*1e3))}async function ii(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await $r({...i,clientType:`oauth-app`}):await $r({...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 ri(r.interval),ii(e,t,n,r);if(a===`slow_down`)return await ri(r.interval+7),ii(e,t,n,r);throw i}}async function ai(e,t){return ti(e,{auth:t})}async function oi(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 ti(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var si=`0.0.0-development`;function ci(e){let t=e.request||wn.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${si} ${Cn()}`}}),{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(ai.bind(null,i),{hook:oi.bind(null,i)})}async function li(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=ci({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-CtDa6mtZ.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 ui(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}function W(e){let t=e.toLowerCase().replace(/:\d+$/,``);we.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function di(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function fi(e,t,n=li){let r=ui(),{host:i,json:a}=e;W(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?di(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?di(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function pi(e){return new O(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: workspace origin host)`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{let n=t.host??gt(process.cwd()),r=await e();await fi({...t,host:n},r)})}const mi={style:{maskedText:`[input is masked]`}};var hi=kn((e,t)=>{let{validate:n=()=>!0}=e,r=Hn(mi,e.theme),[i,a]=En(`idle`),[o,s]=En(),[c,l]=En(``),u=Fn({status:i,theme:r});jn(async(e,r)=>{if(i===`idle`)if(Ln(e)){let e=c;a(`loading`);let i=await n(e);i===!0?(l(e),a(`done`),t(e)):(r.write(c),s(i||`You must provide a valid value`),a(`idle`))}else l(r.line),s(void 0)});let d=r.style.message(e.message,i),f=``,p;e.mask?f=(typeof e.mask==`string`?e.mask:`*`).repeat(c.length):i!==`done`&&(p=`${r.style.help(r.style.maskedText)}${An}`),i===`done`&&(f=r.style.answer(f));let m=``;return o&&(m=r.style.error(o)),[[u,d,e.mask?f:p].join(` `),m]});function gi(e,t,n,r){if(typeof n!=`function`)throw Error(`method for before hook must be a function`);return r||={},Array.isArray(t)?t.reverse().reduce((t,n)=>gi.bind(null,e,n,t,r),n)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((e,t)=>t.hook.bind(null,e,r),n)():n(r))}function _i(e,t,n,r){let i=r;e.registry[n]||(e.registry[n]=[]),t===`before`&&(r=(e,t)=>Promise.resolve().then(i.bind(null,t)).then(e.bind(null,t))),t===`after`&&(r=(e,t)=>{let n;return Promise.resolve().then(e.bind(null,t)).then(e=>(n=e,i(n,t))).then(()=>n)}),t===`error`&&(r=(e,t)=>Promise.resolve().then(e.bind(null,t)).catch(e=>i(e,t))),e.registry[n].push({hook:r,orig:i})}function vi(e,t,n){if(!e.registry[t])return;let r=e.registry[t].map(e=>e.orig).indexOf(n);r!==-1&&e.registry[t].splice(r,1)}const yi=Function.bind,bi=yi.bind(yi);function xi(e,t,n){let r=bi(vi,null).apply(null,n?[t,n]:[t]);e.api={remove:r},e.remove=r,[`before`,`error`,`after`,`wrap`].forEach(r=>{let i=n?[t,r,n]:[t,r];e[r]=e.api[r]=bi(_i,null).apply(null,i)})}function Si(){let e=Symbol(`Singular`),t={registry:{}},n=gi.bind(null,t,e);return xi(n,t,e),n}function Ci(){let e={registry:{}},t=gi.bind(null,e);return xi(t,e),t}var wi={Singular:Si,Collection:Ci},Ti=`0.0.0-development`;function Ei(e){return`Request failed due to following response errors:
|
|
5
5
|
`+e.errors.map(e=>` - ${e.message}`).join(`
|
|
@@ -8,9 +8,9 @@ import{o as e}from"./chunk-DTipWd-i.mjs";import{At as t,E as n,Ft as r,Ht as i,M
|
|
|
8
8
|
`),n.includes(`file`)&&process.stderr.write(` cleared from ~/.ok/auth.yml
|
|
9
9
|
`)}function ba(){return new O(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: workspace origin host)`).action(async e=>{let t=e.host??gt(process.cwd());await ya({...e,host:t})})}async function xa(e,t,n=_n){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 Sa(e,t,n){return{type:`status`,host:e,backend:t,...n}}async function Ca(e,t){let{host:n,json:r}=e;W(n);let i=t.backend,a=await xa(n,t);a.tier===`none`&&(r?process.stdout.write(`${JSON.stringify(Sa(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 la({auth:a.token,...o?{baseUrl:o}:{}});try{let{data:e}=await s.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify(Sa(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=fa(e,n);r?process.stdout.write(`${JSON.stringify(Sa(n,i,{authenticated:!1,error:t.message}))}\n`):process.stderr.write(`✗ ${t.message}\n`),process.exit(1)}}function wa(e){return new O(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname (default: workspace origin host)`).option(`--json`,`Output JSON`,!1).action(async t=>{let n=t.host??gt(process.cwd());await Ca({...t,host:n},await e())})}function Ta(e){let t=new O(`auth`);t.description(`GitHub authentication management`);let n=e=>hn(void 0,e);return t.addCommand(pi(n)),t.addCommand(wa(n)),t.addCommand(va(n)),t.addCommand(ba()),t.addCommand(ha(n)),t.addCommand(Yr(n,e)),t}function Ea(e,t=Sr(),n=bn){try{t===`darwin`?n(`/usr/bin/open`,[`-R`,e]):n(t===`win32`?`explorer.exe`:`xdg-open`,[F(e)])}catch{}}function Da(){return new O(`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 on({level:`standard`,projectDir:process.cwd(),redact:!0,outputPath:Qt(),logger:Ff()});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&&Ea(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 Oa(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function ka(e){let t=e.inspect??(t=>t===`ui`?Xt(e.lockDir):Zt(e.lockDir,t)),n=e.unlink??(e=>U(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Oa(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function Aa(e){return new O(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),ka({lockDir:w(process.cwd())}).failed.length>0&&(process.exitCode=1)})}function ja(e){return`credential.helper=!${e.map(be).join(` `)} auth git-credential`}async function Ma(e,t,n={},r=_n){let i=[`credential.helper=`,ja(n.selfCliArgs??[`open-knowledge`])];if(!n.skipGhDetect){let t=r(e);if(t.available&&t.token)return{tier:`A`,gitConfig:i,relayToken:{token:t.token,host:e}}}let a=await t.get(e);return a==null?{tier:`none`,gitConfig:[]}:{tier:a.gitProtocol===`ssh`?`C`:`B`,gitConfig:i}}async function Na(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 Pa=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Fa(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 Pa)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function K(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function Ia(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 La(e,t=process.env){let n=Ia(t);return e.relayToken?(n.OK_GH_TOKEN=e.relayToken.token,n.OK_GH_TOKEN_HOST=e.relayToken.host):(delete n.OK_GH_TOKEN,delete n.OK_GH_TOKEN_HOST),n}function Ra(e=process.argv,t=process.execPath){let n=e[1];return n?[t,n]:[t]}function za(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const Ba=oe;async function Va(e){try{return await e.clone(za(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&Ba(t))return e.onFallback(e.branch),await e.clone(za(null)),{fellBack:!0};throw t}}function Ha(e,t){return{baseDir:e,config:t,unsafe:{allowUnsafeCredentialHelper:!0,allowUnsafePager:!0,allowUnsafeSshCommand:!0,allowUnsafeAskPass:!0,allowUnsafeEditor:!0}}}function Ua(e,t,n){return e===`https`&&t===`github.com`&&n}function Wa(e,t){let n=`${t.owner}/${t.name}`;return e===n||e===`${n}.git`?`https://${t.hostname}/${n}`:e}async function Ga(e,t,n,r=process.cwd()){let i=ln(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=Wa(e,i),o=t.dir?R(r,t.dir):R(r,i.name);if(z(o)&&gr(o).length>0)throw Error(`Target directory is not empty: ${o}`);ft();let s=vn(),c=i.protocol===`https`&&i.hostname===`github.com`?await Na(i.owner,i.name):!1,l=Ua(i.protocol,i.hostname,c)?{tier:`none`,gitConfig:[]}:await Ma(i.hostname,s,{selfCliArgs:Ra()}),u=La(l),d=Rt(Ha(r,l.gitConfig)).env(u),f=-1;d.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
10
10
|
`)){let n=Fa(e);n&&n.pct!==f&&(f=n.pct,K(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await Va({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:e=>d.clone(a,o,e),onFallback:e=>{K(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
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
11
|
+
`);try{let{runInit:e}=await import(`./init-C7HKweMR.mjs`),n=await e({cwd:o,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?K(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Ka(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function Ka(e){let t=On(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const qa=/^[A-Za-z0-9._/:@-]+$/;function Ja(e){return qa.test(e)?e:be(e)}function Ya(e,t){let n=typeof t==`string`&&t.length>0?` -b ${Ja(t)}`:``;return`ok clone ${Ja(e)}${n}`}function Xa(e){let t=x(e.error);if(t.kind!==`auth`)return null;if(te(t)){let t=Ya(e.url,e.branch);return[`✗ Couldn't clone ${e.url} — authentication is required.`,``,` To fix:`,` 1. Run: ok auth login`,` 2. Then re-run: ${t}`].join(`
|
|
12
12
|
`)}if(t.subclass===`403`){let t=typeof e.principal==`string`&&e.principal.length>0?` (signed in as @${e.principal} — may lack access)`:``;return`✗ Access denied when cloning ${e.url}${t}. Check that your account has access to the repository.`}return t.subclass===`ssh-auth`?`✗ Couldn't clone ${e.url} 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.`:["✗ 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: ok auth pat`,` 3. Then re-run: ${Ya(e.url,e.branch)}`].join(`
|
|
13
|
-
`)}function Za(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Xa({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Qa(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function $a(e){let t=x(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=ln(e.url);t&&(n=await(e.resolvePrincipal??(e=>Qa(vn(),e)))(t.hostname))}Za({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function eo(e){return new O(`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();try{let a=await Ga(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)K(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-
|
|
13
|
+
`)}function Za(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Xa({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Qa(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function $a(e){let t=x(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=ln(e.url);t&&(n=await(e.resolvePrincipal??(e=>Qa(vn(),e)))(t.hostname))}Za({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function eo(e){return new O(`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();try{let a=await Ga(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)K(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-De77XKSr.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){if(e instanceof At||e instanceof bt){r.json?K(!0,{type:`error`,message:e.message}):process.stderr.write(`${e.message}\n`),process.exitCode=78;return}await $a({error:e,url:t,branch:r.branch??null,json:r.json,emit:e=>K(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var to=_();const no=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],...f.map(e=>e.path)];function ro(e){return It({absPath:Lt(`project-local`,e),sideline:!1}).diagnostics}function io(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Gn;try{let{sources:n,diagnostics:i,sidelined:a}=r(e.cwd),o=(e.readProjectLocalFn??ro)(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(g(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 ao(e){let t=(0,to.parseDocument)(V(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of no)t.hasIn(e)&&n.push(e.join(`.`));return n}function oo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function so(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=oo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}function co(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 lo(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??E,s=co(r).map(t=>({scope:t,absPath:Lt(t,a,e.homedirOverride)})),c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!z(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ao(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:so(no.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:g(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 uo=`project | project-local | user | all`,fo=new Set(Object.keys({project:!0,"project-local":!0,user:!0,both:!0,all:!0}));function po(e){return e!==`config`}function mo(){let e=new O(`config`).description(`Inspect and maintain OpenKnowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{io({}).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: ${uo}`,`all`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=String(e.scope);if(!fo.has(t)){console.error(`Invalid --scope: ${t}. Expected: ${uo}`),process.exitCode=2;return}(await lo({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const ho=[` 1. ${P(`Customize`)} (sidebar) → ${P(`Skills`)}`,` 2. Click the ${P(`+`)} button`,` 3. Click ${P(`Create skill`)}`,` 4. Click ${P(`Upload skill`)}`,` 5. Pick ${P(`openknowledge.skill`)} from Downloads`],go=k(` Open the Claude Desktop App, then: ${P(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function _o(e){let t=[j(`Built ${e.outputPath}`),A(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(N(` Handoff failed: ${e.handoffError.message}`)),t.push(go),t.join(`
|
|
14
14
|
`)}function vo(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[k(`OpenKnowledge skill ${P(`v${t}`)} already delivered to Claude Desktop.`),A(` Recorded at ${n} in ~/.ok/skill-state.yml`),A(` Use ${P(`--force`)} to rebuild and re-open the install dialog.`)].join(`
|
|
15
15
|
`)}function yo(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[j(`Built ${e.outputPath}`),A(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),k(` Claude Desktop App opened. Now upload the file manually:`),...ho,A(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
|
|
16
16
|
`)}function bo(e){return`${M(`Error:`)} ${e.buildError??`unknown build failure`}`}async function xo(e={}){let t=await pt(e);return t.status===`failed`?{...t,message:bo(t),exitCode:1}:t.status===`skip-current`?{...t,message:vo(t),exitCode:0}:t.status===`installed`?{...t,message:yo(t),exitCode:0}:{...t,message:_o(t),exitCode:0}}function So(){return new O(`cowork`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. (Advanced/rarely needed — `ok 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 xo({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 Co(e,t){let n=Or({input:t??process.stdin,output:process.stderr});try{let t=(await n.question(e)).trim().toLowerCase();return t===`y`||t===`yes`}finally{n.close()}}function wo(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return Ut(t).join(qt({...e,platformName:t}),n)}function To(e={}){let t=e.platformName??process.platform,n=e.home??xr(),r=e.env??process.env,i=Ut(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`@inkeepopen-knowledge-desktop-updater`)}function Eo(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Do(e){let t=I(e,`state.json`);if(!z(t))return[];let n;try{n=JSON.parse(V(t,`utf-8`))}catch{return[]}return Eo(n)??[]}function Oo(e){let t=I(e,`state.json`);if(!z(t))return!1;try{return Eo(JSON.parse(V(t,`utf-8`)))!==null}catch{return!1}}function q(e,t){return e===t?`~`:e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function ko(e){return or===`/`?e:e.split(or).join(`/`)}function Ao(e,t,n=`This project`){let r=[];r.push({kind:`stop-server`,group:n,label:`Stop the project server (if running)`,lockDir:w(e)});let i=new Set;for(let a of Wt){let o=Kt[a];if(!o.projectConfigPath)continue;let s=o.projectConfigPath(e);i.add(ko(L(e,s))),r.push({kind:`mcp-entry`,group:n,label:`Remove OK's MCP entry from ${o.label} (${ko(L(e,s))})`,editorId:a,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 a=new Set([...Tn(e),...ae]);for(let t of a){let a=t.replace(/\/$/,``);i.has(a)||a!==`.claude/launch.json`&&r.push({kind:`remove-path`,group:n,label:`Remove ${t}`,path:I(e,a),containWithin:e})}try{r.push({kind:`remove-path`,group:n,label:`Remove the OK shadow repo (.git/ok/)`,path:Be(e)})}catch{}return r}function jo(e,t){return{scope:`deinit`,ops:Ao(e,t)}}function Mo(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 ${q(I(e,`..`,`..`),t)}`,lockDir:e});c.push({kind:`keychain-token`,group:`Credentials`,label:`Remove the GitHub credential (${r}) from the OS keychain + auth.yml`,host:r}),c.push({kind:`embeddings-key`,group:`Credentials`,label:`Remove all embeddings API keys (secrets.yml)`}),c.push(...Po(a,t));for(let e of Wt){let n=Kt[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} (${q(r,t)})`,editorId:e,scope:`user`,cwd:t,home:t,configPath:r})}for(let e of Yn(t))c.push({kind:`remove-path`,group:`Skill bundles`,label:`Remove ${q(e.path,t)}`,path:e.path});c.push(...Fo(t,n,e.env));for(let e of o)c.push(...Ao(e,t,`Project: ${rr(e)}`));return c.push({kind:`remove-path`,group:`Global directory`,label:s?`Remove ~/.ok (including user-authored skills)`:`Remove ~/.ok (keeping ~/.ok/skills)`,path:I(t,`.ok`),preserve:s?void 0:[`skills`]}),{scope:`uninstall`,ops:c}}function No(e){return[I(e,`.zshrc`),I(e,`.bash_profile`),I(e,`.config`,`fish`,`conf.d`,`open-knowledge.fish`)]}function Po(e,t){let n=[],r=new Set([...No(t),...e?.rcFiles??[]]);for(let e of r)z(e)&&n.push({kind:`shell-block`,group:`Shell PATH`,label:`Strip the OK block from ${q(e,t)}`,rcFile:e});for(let r of e?.extraSymlinks??[])n.push({kind:`extra-symlink`,group:`Shell PATH`,label:`Remove the ok symlink at ${q(r.path,t)}`,path:r.path,target:r.target});return n}function Fo(e,t,n){let r={home:e,platformName:t,env:n},i=wo(r),a=To(r),o=[{kind:`remove-path`,group:`Application data`,label:`Remove ${q(i,e)}`,path:i}];if(t===`darwin`){let t=wo({...r,productName:`Open Knowledge`});o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${q(t,e)} (only if it is OpenKnowledge's)`,path:t,requireOurState:!0})}return o.push({kind:`remove-path`,group:`Application data`,label:`Remove ${q(a,e)}`,path:a}),o}async function Io(e,t={}){let n=t.clearToken??xn,r=t.clearEmbeddingsKey??Dt,i=t.stopServer??(e=>{let t=cn({lockDir:e,log:()=>{},error:()=>{}});return{stopped:t.stopped.length,failed:t.failed.map(e=>({pid:e.target.pid,error:e.error}))}}),a=[];for(let t of e.ops)try{a.push(await Lo(t,{clearToken:n,clearEmbeddingsKey:r,stopServer:i}))}catch(e){a.push({op:t,status:`failed`,detail:e instanceof Error?e.message:String(e)})}return{results:a,removed:a.filter(e=>e.status===`removed`),failed:a.filter(e=>e.status===`failed`)}}async function Lo(e,t){switch(e.kind){case`stop-server`:{let{stopped:n,failed:r}=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(`; `)}); a process may still be using files that were removed`}:{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 "open-knowledge"`}:{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`:{if(!z(e.rcFile))return{op:e,status:`not-present`};let{text:t,changed:n,emptyAfter:r}=tn(V(e.rcFile,`utf-8`));return n?r?(yr(e.rcFile,{force:!0}),{op:e,status:`removed`,detail:`file removed (was OK-owned)`}):(Ft(e.rcFile,t,{mode:Vn(e.rcFile)}),{op:e,status:`removed`}):{op:e,status:`not-present`}}case`extra-symlink`:return an(e.path,e.target)?(U(e.path),{op:e,status:`removed`}):{op:e,status:`not-present`};case`mcp-entry`:{let t=en(Kt[e.editorId],e.cwd,e.home,e.configPath);switch(t.kind){case`removed`:return{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`:return{op:e,status:`skipped`,detail:`declined (${t.reason})`};default:throw Error(`unhandled mcp-remove outcome: ${t.kind}`)}}case`launch-entry`:{let t=Xn(e.projectRoot);switch(t.kind){case`removed`:return{op:e,status:`removed`};case`not-present`:return{op:e,status:`not-present`};case`declined`:return{op:e,status:`skipped`,detail:`declined (unparseable)`};default:throw Error(`unhandled launch-remove outcome: ${t.kind}`)}}case`git-exclude`:{if(zn(e.projectRoot).length===0)return{op:e,status:`not-present`};let t=Pn(e.projectRoot,Tn(e.projectRoot));return t.kind===`no-exclude`?t.reason===`inaccessible`?{op:e,status:`failed`,detail:`could not write .git/info/exclude (inaccessible)`}:{op:e,status:`not-present`,detail:t.reason}:{op:e,status:t.removed.length>0?`removed`:`not-present`}}case`remove-path`:return Ro(e)}}function Ro(e){if(e.requireOurState&&!Oo(e.path))return{op:e,status:`skipped`,detail:`not verified as OpenKnowledge — left untouched`};e.containWithin&&Gt(e.path,e.containWithin);let t;try{t=pr(e.path)}catch(e){if(e.code!==`ENOENT`)throw e}if(!t)return{op:e,status:`not-present`};if(t.isSymbolicLink())return U(e.path),{op:e,status:`removed`};if(e.preserve&&e.preserve.length>0){let t=new Set(e.preserve),n=!1;for(let r of gr(e.path))t.has(r)||(yr(I(e.path,r),{recursive:!0,force:!0}),n=!0);return{op:e,status:n?`removed`:`not-present`}}return yr(e.path,{recursive:!0,force:!0}),{op:e,status:`removed`}}function zo(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 Bo(e){if(e.ops.length===0)return A(`Nothing to remove.`);let t=[];for(let[n,r]of zo(e.ops)){t.length>0&&t.push(``),t.push(P(`${n}:`));for(let e of r)t.push(` ${N(`-`)} ${e.label}`)}return t.join(`
|
|
@@ -39,17 +39,17 @@ ws.addEventListener('error', () => process.exit(1));
|
|
|
39
39
|
setTimeout(() => process.exit(2), ${t+1e4});
|
|
40
40
|
`),r}async function bs(e,t,n,r,i){let a=ys(e,t,I(r,`cpu.cpuprofile`)),o=!1,s=tr(process.execPath,[a],T({stdio:`ignore`})),c=setInterval(()=>{let e=hs(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{yr(I(a,`..`),{recursive:!0,force:!0})}catch{}return o}function xs(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(`
|
|
41
41
|
`)}async function Ss(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??Et,s=t.inspect??Zt,c=t.resolveCommand??rt,l=t.resolveUsage??xt,u=t.collectLsofFn??gs,d=t.getEndpoints??vs,f=t.profiler??bs,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(J.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&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?I(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):I(process.cwd(),`ok-diagnose-${n}-${b}`);try{B(x,{recursive:!0})}catch(e){a(J.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(J.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{br(I(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 te=u(n);if(te&&S(`lsof.txt`,te),!i){let e=te?_s(te).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(J.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(J.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
|
|
42
|
-
`)}\n`);try{S(`stacks.txt`,xs(V(I(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.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: ${J.default.bold(x)}`)}async function Cs(e){let t=Or({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function ws(e){let t=mr(I(Cr(),`ok-bundle-process-`));return await Ss({pid:e,output:t}),t}function Ts(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 Es(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Ds(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 Os(e){let t=e.manifest.redaction.secretScrub;return t===void 0?J.default.yellow(`NOT scrubbed (--no-redact): tokens and keys ship verbatim`):`scrubbed known credential formats (${t.redactedLineCount} line(s) across ${t.redactions.length} file(s))`}function ks(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — what leaves this machine`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ts(r.totalBytes)} uncompressed`),e(` Document names: included in cleartext (${r.docNameCount} doc.name occurrence(s) in telemetry)`),e(` Content-dir path: ${Ds(t)}`),e(` Credentials: ${Os(t)}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function As(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Cs,i=t.runProcessDiagnose??ws,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=F(o);if(!z(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=I(e.contentDir,`.ok`,`local`,`diagnostics`);B(n,{recursive:!0}),o=I(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=e.redact!==!1,l=await nn({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:c,scrubSecrets:c,deps:t.collectDeps});try{return l.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),ks(n,l,o),e.yes!==!0&&!Es(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await $t({collected:l,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(l.cleanup(),s!==void 0)try{yr(s,{recursive:!0,force:!0})}catch{}}}function js(){let e=new O(`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(J.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(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Ss({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ms()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok 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(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-
|
|
42
|
+
`)}\n`);try{S(`stacks.txt`,xs(V(I(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.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: ${J.default.bold(x)}`)}async function Cs(e){let t=Or({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function ws(e){let t=mr(I(Cr(),`ok-bundle-process-`));return await Ss({pid:e,output:t}),t}function Ts(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 Es(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Ds(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 Os(e){let t=e.manifest.redaction.secretScrub;return t===void 0?J.default.yellow(`NOT scrubbed (--no-redact): tokens and keys ship verbatim`):`scrubbed known credential formats (${t.redactedLineCount} line(s) across ${t.redactions.length} file(s))`}function ks(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — what leaves this machine`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ts(r.totalBytes)} uncompressed`),e(` Document names: included in cleartext (${r.docNameCount} doc.name occurrence(s) in telemetry)`),e(` Content-dir path: ${Ds(t)}`),e(` Credentials: ${Os(t)}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function As(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Cs,i=t.runProcessDiagnose??ws,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=F(o);if(!z(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=I(e.contentDir,`.ok`,`local`,`diagnostics`);B(n,{recursive:!0}),o=I(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=e.redact!==!1,l=await nn({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:c,scrubSecrets:c,deps:t.collectDeps});try{return l.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),ks(n,l,o),e.yes!==!0&&!Es(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await $t({collected:l,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(l.cleanup(),s!==void 0)try{yr(s,{recursive:!0,force:!0})}catch{}}}function js(){let e=new O(`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(J.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(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Ss({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ms()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok 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(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-Osy-rk3T.mjs`),{resolveContentDir:r}=await import(`./src-BMc6VYxR.mjs`),i=process.cwd(),{config:a}=n(i);await As({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(J.default.red(t)),process.exit(1)}}),e}async function Ms(){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 hi({message:`Enter embeddings provider API key:`})).trim()}function Ns(e){return dt(e)}async function Ps(e,t){let n=await Ct(at(),e,t);return n.apiKey?{present:!0,notRequired:!1,source:n.source}:{present:!1,notRequired:n.keyless,source:null}}async function Fs(e){try{let t=Bt(w(e));if(!t||t.port<=0||!zt(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=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function Is(){return new O(`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 Ms();if(!t){process.stderr.write(`No key provided.
|
|
43
43
|
`),process.exitCode=1;return}let n=R(e.cwd??process.cwd()),{baseUrl:r}=Ns(n);try{await at().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 ~/.ok/secrets.yml, 0600, this machine only — never in the project).
|
|
44
44
|
Enable semantic search with \`ok embeddings enable\`, or in
|
|
45
45
|
OK Desktop → Settings → This project → Search.
|
|
46
46
|
`)})}function Ls(){return new O(`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=R(e.cwd??process.cwd()),{baseUrl:n}=Ns(t),r;try{r=await at().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 Rs(){return new O(`list`).description(`List every project + endpoint that has a stored embeddings key`).action(async()=>{let e=await at().listProjects();if(e.length===0){process.stderr.write(`No project embeddings keys stored.
|
|
47
47
|
`);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(`
|
|
48
|
-
`)}\n`)})}function zs(){return new O(`set-url`).description(`Set the embeddings API endpoint for this project (project-local)`).argument(`<url>`,`OpenAI-compatible base URL, e.g. https://api.openai.com/v1`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async(e,t)=>{let n=e.trim(),r=a(n);if(r!==null){process.stderr.write(r===`invalid-url`?`Not a valid URL: ${e}\n`:`Refusing an insecure endpoint: use https:// (http:// is allowed only for localhost). Got: ${e}\n`),process.exitCode=1;return}let i=R(t.cwd??process.cwd()),o=await E({cwd:i,scope:`project-local`,patch:{search:{semantic:{baseUrl:n}}}});if(!o.ok){process.stderr.write(`Failed to set the embeddings endpoint — ${
|
|
49
|
-
`)})}function Hs(){return new O(`clear-model`).description(`Reset the embeddings model to ${
|
|
48
|
+
`)}\n`)})}function zs(){return new O(`set-url`).description(`Set the embeddings API endpoint for this project (project-local)`).argument(`<url>`,`OpenAI-compatible base URL, e.g. https://api.openai.com/v1`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async(e,t)=>{let n=e.trim(),r=a(n);if(r!==null){process.stderr.write(r===`invalid-url`?`Not a valid URL: ${e}\n`:`Refusing an insecure endpoint: use https:// (http:// is allowed only for localhost). Got: ${e}\n`),process.exitCode=1;return}let i=R(t.cwd??process.cwd()),o=await E({cwd:i,scope:`project-local`,patch:{search:{semantic:{baseUrl:n}}}});if(!o.ok){process.stderr.write(`Failed to set the embeddings endpoint — ${g(o.error)}\n`),process.exitCode=1;return}process.stderr.write(`✓ Embeddings endpoint set to ${n} for ${i}\n`)})}function Bs(){return new O(`clear-url`).description(`Reset the embeddings API endpoint to the default OpenAI endpoint (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async e=>{let t=R(e.cwd??process.cwd()),n=await E({cwd:t,scope:`project-local`,patch:{search:{semantic:{baseUrl:c}}}});if(!n.ok){process.stderr.write(`Failed to reset the embeddings endpoint — ${g(n.error)}\n`),process.exitCode=1;return}process.stderr.write(`✓ Embeddings endpoint reset to ${c} for ${t}\n`)})}function Vs(){return new O(`set-model`).description(`Set the embeddings model for this project (project-local)`).argument(`<model>`,`Model id served by the configured endpoint, e.g. nomic-embed-text`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async(e,t)=>{let n=e.trim();if(!n){process.stderr.write("Model id cannot be empty. Use `clear-model` to reset the default.\n"),process.exitCode=1;return}let r=R(t.cwd??process.cwd()),i=await E({cwd:r,scope:`project-local`,patch:{search:{semantic:{model:n}}}});if(!i.ok){process.stderr.write(`Failed to set the embeddings model — ${g(i.error)}\n`),process.exitCode=1;return}process.stderr.write(`✓ Embeddings model set to ${n} for ${r}\n Changing the model re-embeds the corpus on the next search.
|
|
49
|
+
`)})}function Hs(){return new O(`clear-model`).description(`Reset the embeddings model to ${r} (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async e=>{let t=R(e.cwd??process.cwd()),n=await E({cwd:t,scope:`project-local`,patch:{search:{semantic:{model:r}}}});if(!n.ok){process.stderr.write(`Failed to reset the embeddings model — ${g(n.error)}\n`),process.exitCode=1;return}process.stderr.write(`✓ Embeddings model reset to ${r} for ${t}\n`)})}function Us(e,t){return new O(e).description(`Turn semantic search ${t?`on`:`off`} for this project (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async n=>{let r=R(n.cwd??process.cwd()),i=await E({cwd:r,scope:`project-local`,patch:{search:{semantic:{enabled:t}}}});if(!i.ok){process.stderr.write(`Failed to ${e} semantic search — ${g(i.error)}\n`),process.exitCode=1;return}if(process.stderr.write(`✓ Semantic search ${t?`enabled`:`disabled`} for ${r}\n`),t){let{present:e,notRequired:t}=await Ps(r,Ns(r).baseUrl);!e&&!t&&process.stderr.write(" Note: no API key set yet — run `ok embeddings set-key`. Until then, search stays lexical.\n")}})}function Ws(){return new O(`status`).description(`Show semantic-search capability: key presence, enabled, coverage, provider`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=R(e.cwd??process.cwd()),n=Ns(t),{present:r,notRequired:i,source:a}=await Ps(t,n.baseUrl),o=n.enabled&&(r||i),s=o?await Fs(t):null;if(e.json){process.stdout.write(`${JSON.stringify({project:t,key:{present:r,notRequired:i,source:a},project_config:{enabled:n.enabled,capable:o,coverage:s?{embedded:s.embedded,total:s.total}:null,provider:{baseUrl:n.baseUrl,model:n.model,dimensions:n.dimensions??null}}})}\n`);return}let c=r?`set for this endpoint — ${a===`env`?`environment (${ct})`:`~/.ok/secrets.yml`}`:i?`not required (localhost endpoint)`:`not set`,l=o?s?`${s.embedded} / ${s.total} pages embedded`:`server not running — start it to index (or it has not embedded yet)`:null,u=[`Semantic search`,` project: ${t}`,``,` This project:`,` enabled: ${n.enabled?`yes`:`no`}`,` API key: ${c}`,` capability: ${o?`AVAILABLE`:`unavailable (search stays lexical)`}`,...l?[` coverage: ${l}`]:[],` provider: ${n.baseUrl}`,` model: ${n.model}`,` dimensions: ${n.dimensions??`auto (detected from the endpoint)`}`],d=[];!r&&!i&&d.push(`Set a key: ok embeddings set-key (or export ${ct})`),n.enabled||d.push(`Enable it: ok embeddings enable (in this project folder)`),d.length>0&&u.push(``,...d.map(e=>` ${e}`)),process.stdout.write(`${u.join(`
|
|
50
50
|
`)}\n`)})}function Gs(){return new O(`embeddings`).description(`Manage the semantic-search embeddings provider key + status`).addCommand(Is()).addCommand(Ls()).addCommand(zs()).addCommand(Bs()).addCommand(Vs()).addCommand(Hs()).addCommand(Us(`enable`,!0)).addCommand(Us(`disable`,!1)).addCommand(Rs()).addCommand(Ws())}const Ks=I(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),qs=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Js(e,t,n){return e===`darwin`?[I(t,`Applications`,`OpenKnowledge.app`,Ks),I(`/Applications`,`OpenKnowledge.app`,Ks)].find(e=>n.existsSync(e))??null:null}function Ys(e,t,n){if(n!==`darwin`)return{proxy:!1,suppressedBy:`platform`};let r=e.OK_BUNDLE_PROXY?.toLowerCase();return r===`0`||r===`false`?{proxy:!1,suppressedBy:`env`}:t.includes(`--no-bundle-proxy`)?{proxy:!1,suppressedBy:`flag`}:typeof t[1]==`string`&&qs.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function Xs(e){e.stderr.write(`${JSON.stringify({event:`mcp-bundle-proxy`,mode:e.mode,bundlePath:e.bundlePath,reason:e.reason,hint:`Suppress with --no-bundle-proxy or OK_BUNDLE_PROXY=0.`})}\n`)}function Zs(e){Xs({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??tr,n=e.exitProcess??(e=>process.exit(e)),r=e.now??(()=>Date.now()),i=r(),a=e.startupFailureWindowMs??1e3;return new Promise((o,s)=>{let c=t(e.bundlePath,e.argv.filter(e=>e!==`--no-bundle-proxy`),{env:{...e.env,OK_BUNDLE_PROXY:`0`},stdio:`inherit`,windowsHide:!0}),l=e=>{c.kill(e)},u=()=>{process.off(`SIGTERM`,l),process.off(`SIGINT`,l)};process.on(`SIGTERM`,l),process.on(`SIGINT`,l),c.once(`error`,e=>{u(),s(e)}),c.once(`exit`,(e,t)=>{if(u(),t){s(Error(`bundle process exited by signal ${t}`));return}let o=e??0,c=r()-i;if(o!==0&&c<=a){s(Error(`bundle process exited during startup with code ${o}`));return}n(o)})})}function Qs(e){let t=e.scheduler??{setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e)},n=e.initialBackoffMs??1e3,r=e.maxBackoffMs??3e4,i=e.rng??Math.random,a=e.createWebSocket??(e=>new WebSocket(e)),o=e.logger??null,s=e.log,c=null,l=null,u=!1,d=n;function f(e,t,n){try{o?o[e](t,n):s?.(t)}catch{}}function p(){if(u)return;l!==null&&t.clearTimeout(l);let e=d;d=Math.min(d*2,r);let n=i(),a=Math.max(1,Math.floor(e*(1-n/2)));f(`debug`,`scheduling reconnect`,{backoffMs:a,ceilMs:e}),l=t.setTimeout(()=>{l=null,m().catch(e=>f(`warn`,`reconnect failed`,{error:String(e)}))},a)}async function m(){if(u)return;let t;try{t=await e.resolveWsUrl()}catch(e){f(`warn`,`resolveWsUrl threw`,{error:String(e)}),p();return}if(!t){p();return}let r=[];e.pid!==void 0&&r.push(`pid=${encodeURIComponent(String(e.pid))}`),e.connectionId&&r.push(`connectionId=${encodeURIComponent(e.connectionId)}`),e.connectionId&&e.displayName!==void 0&&e.clientName!==void 0&&e.colorSeed!==void 0&&(r.push(`displayName=${encodeURIComponent(e.displayName)}`),r.push(`clientName=${encodeURIComponent(e.clientName)}`),r.push(`colorSeed=${encodeURIComponent(e.colorSeed)}`));let i=r.length>0?`?${r.join(`&`)}`:``,o=`${t}/collab/keepalive${i}`;try{c=a(o)}catch(e){f(`warn`,`WebSocket constructor failed`,{url:o,error:String(e)}),c=null,p();return}c.addEventListener(`open`,()=>{f(`info`,`connected`,{url:t}),d=n}),c.addEventListener(`close`,()=>{u||(f(`info`,`disconnected`,{url:t}),c=null,p())}),c.addEventListener(`error`,()=>{f(`debug`,`websocket error observed`,{url:t,readyState:c?.readyState,reason:`error-event`})})}return queueMicrotask(()=>{m().catch(e=>f(`warn`,`initial connect failed`,{error:String(e)}))}),{close:()=>{if(!u&&(u=!0,l!==null&&(t.clearTimeout(l),l=null),c)){try{c.close()}catch{}c=null}},isConnected:()=>c!==null&&c.readyState===1}}var $s=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
51
51
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),ec(t)}clear(){this._buffer=void 0}};function ec(e){return ot.parse(JSON.parse(e))}function tc(e){return JSON.stringify(e)+`
|
|
52
|
-
`}var nc=class{constructor(e=sr.stdin,t=sr.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new $s,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=tc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function rc(e){if(e.platform!==`darwin`)return{kind:`unchanged`};let t;try{t=e.realpath(e.bundleAnchorPath)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}let n;try{n=e.statInode(t)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}return n===e.currentInode?{kind:`unchanged`}:{kind:`replaced`,currentInode:e.currentInode,onDiskInode:n}}function ic(e){let t=e.setInterval??setInterval,n=e.clearInterval??clearInterval,r=e.intervalMs??3e5,i=!0,a=!1,o=!1,s=t(()=>{if(!i)return;let t;try{t=e.detect()}catch(t){e.log(`bundle identity check threw unexpectedly (contract violation): ${t instanceof Error?t.message:String(t)}`);return}if(t.kind===`unreadable`){o||(o=!0,e.log(`bundle identity check unreadable${t.reason?`: ${t.reason}`:``} — will retry on next tick`));return}o&&(o=!1,e.log(`bundle identity check recovered from unreadable`)),t.kind!==`unchanged`&&(i=!1,e.onReplaced(t))},r);return typeof s.unref==`function`&&s.unref(),{stop:()=>{a||(a=!0,i=!1,n(s))}}}function ac(e,t){let n;try{n=t.realpathSync(e)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (realpath failed): ${e instanceof Error?e.message:String(e)}`);return}let r;try{r=t.statInoSync(n)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (stat failed): ${e instanceof Error?e.message:String(e)}`);return}return{resolvedPath:n,inode:r}}function oc(e){let t=e.scheduler??{setInterval:(e,t)=>globalThis.setInterval(e,t),clearInterval:e=>globalThis.clearInterval(e)},n=e.getPpid();if(n<=1)return{stop:()=>{}};let r=!1,i=t.setInterval(()=>{if(r)return;let a=e.getPpid();a!==n&&(r=!0,t.clearInterval(i),e.onHostGone(`host process exited (ppid ${n} -> ${a})`))},e.intervalMs??1e3);return i.unref?.(),{stop:()=>t.clearInterval(i)}}function sc(e){let t=t=>{try{e.log(t)}catch{}},n=e.transport.onclose;e.transport.onclose=()=>{t(`[mcp] stdio transport closed (internal shutdown)`),n?.()},e.stdin.once(`end`,()=>t(`[mcp] stdin EOF (host closed pipe)`)),e.stdin.once(`close`,()=>t(`[mcp] stdin closed`)),e.process.on(`exit`,e=>{t(`[mcp] exit code=${e}`)}),e.process.on(`uncaughtExceptionMonitor`,(e,n)=>{t(`[mcp] uncaughtException origin=${n}: ${e instanceof Error?e.stack??e.message:String(e)}`)})}function cc(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function lc(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...cc(t.headers),...cc(r.headers)}:t.headers}):e}let uc;uc=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function dc(e){return(await uc).getRandomValues(new Uint8Array(e))}async function fc(e){let t=``;for(;t.length<e;){let n=await dc(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function pc(e){return await fc(e)}async function mc(e){let t=await(await uc).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function hc(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await pc(e);return{code_verifier:t,code_challenge:await mc(t)}}const Y=s().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:kr.custom,message:`URL must be parseable`,fatal:!0}),v}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),gc=g({resource:r().url(),authorization_servers:y(Y).optional(),jwks_uri:r().url().optional(),scopes_supported:y(r()).optional(),bearer_methods_supported:y(r()).optional(),resource_signing_alg_values_supported:y(r()).optional(),resource_name:r().optional(),resource_documentation:r().optional(),resource_policy_uri:r().url().optional(),resource_tos_uri:r().url().optional(),tls_client_certificate_bound_access_tokens:c().optional(),authorization_details_types_supported:y(r()).optional(),dpop_signing_alg_values_supported:y(r()).optional(),dpop_bound_access_tokens_required:c().optional()}),_c=g({issuer:r(),authorization_endpoint:Y,token_endpoint:Y,registration_endpoint:Y.optional(),scopes_supported:y(r()).optional(),response_types_supported:y(r()),response_modes_supported:y(r()).optional(),grant_types_supported:y(r()).optional(),token_endpoint_auth_methods_supported:y(r()).optional(),token_endpoint_auth_signing_alg_values_supported:y(r()).optional(),service_documentation:Y.optional(),revocation_endpoint:Y.optional(),revocation_endpoint_auth_methods_supported:y(r()).optional(),revocation_endpoint_auth_signing_alg_values_supported:y(r()).optional(),introspection_endpoint:r().optional(),introspection_endpoint_auth_methods_supported:y(r()).optional(),introspection_endpoint_auth_signing_alg_values_supported:y(r()).optional(),code_challenge_methods_supported:y(r()).optional(),client_id_metadata_document_supported:c().optional()}),vc=h({...g({issuer:r(),authorization_endpoint:Y,token_endpoint:Y,userinfo_endpoint:Y.optional(),jwks_uri:Y,registration_endpoint:Y.optional(),scopes_supported:y(r()).optional(),response_types_supported:y(r()),response_modes_supported:y(r()).optional(),grant_types_supported:y(r()).optional(),acr_values_supported:y(r()).optional(),subject_types_supported:y(r()),id_token_signing_alg_values_supported:y(r()),id_token_encryption_alg_values_supported:y(r()).optional(),id_token_encryption_enc_values_supported:y(r()).optional(),userinfo_signing_alg_values_supported:y(r()).optional(),userinfo_encryption_alg_values_supported:y(r()).optional(),userinfo_encryption_enc_values_supported:y(r()).optional(),request_object_signing_alg_values_supported:y(r()).optional(),request_object_encryption_alg_values_supported:y(r()).optional(),request_object_encryption_enc_values_supported:y(r()).optional(),token_endpoint_auth_methods_supported:y(r()).optional(),token_endpoint_auth_signing_alg_values_supported:y(r()).optional(),display_values_supported:y(r()).optional(),claim_types_supported:y(r()).optional(),claims_supported:y(r()).optional(),service_documentation:r().optional(),claims_locales_supported:y(r()).optional(),ui_locales_supported:y(r()).optional(),claims_parameter_supported:c().optional(),request_parameter_supported:c().optional(),request_uri_parameter_supported:c().optional(),require_request_uri_registration:c().optional(),op_policy_uri:Y.optional(),op_tos_uri:Y.optional(),client_id_metadata_document_supported:c().optional()}).shape,..._c.pick({code_challenge_methods_supported:!0}).shape}),yc=h({access_token:r(),id_token:r().optional(),token_type:r(),expires_in:jr().optional(),scope:r().optional(),refresh_token:r().optional()}).strip(),bc=h({error:r(),error_description:r().optional(),error_uri:r().optional()}),xc=Y.optional().or(o(``).transform(()=>void 0)),Sc=h({redirect_uris:y(Y),token_endpoint_auth_method:r().optional(),grant_types:y(r()).optional(),response_types:y(r()).optional(),client_name:r().optional(),client_uri:Y.optional(),logo_uri:xc,scope:r().optional(),contacts:y(r()).optional(),tos_uri:xc,policy_uri:r().optional(),jwks_uri:Y.optional(),jwks:d().optional(),software_id:r().optional(),software_version:r().optional(),software_statement:r().optional()}).strip(),Cc=h({client_id:r(),client_secret:r().optional(),client_id_issued_at:t().optional(),client_secret_expires_at:t().optional()}).strip(),wc=Sc.merge(Cc);h({error:r(),error_description:r().optional()}).strip(),h({token:r(),token_type_hint:r().optional()}).strip();function Tc(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Ec({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var X=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Dc=class extends X{};Dc.errorCode=`invalid_request`;var Oc=class extends X{};Oc.errorCode=`invalid_client`;var kc=class extends X{};kc.errorCode=`invalid_grant`;var Ac=class extends X{};Ac.errorCode=`unauthorized_client`;var jc=class extends X{};jc.errorCode=`unsupported_grant_type`;var Mc=class extends X{};Mc.errorCode=`invalid_scope`;var Nc=class extends X{};Nc.errorCode=`access_denied`;var Pc=class extends X{};Pc.errorCode=`server_error`;var Fc=class extends X{};Fc.errorCode=`temporarily_unavailable`;var Ic=class extends X{};Ic.errorCode=`unsupported_response_type`;var Lc=class extends X{};Lc.errorCode=`unsupported_token_type`;var Rc=class extends X{};Rc.errorCode=`invalid_token`;var zc=class extends X{};zc.errorCode=`method_not_allowed`;var Bc=class extends X{};Bc.errorCode=`too_many_requests`;var Vc=class extends X{};Vc.errorCode=`invalid_client_metadata`;var Hc=class extends X{};Hc.errorCode=`insufficient_scope`;var Uc=class extends X{};Uc.errorCode=`invalid_target`;const Wc={[Dc.errorCode]:Dc,[Oc.errorCode]:Oc,[kc.errorCode]:kc,[Ac.errorCode]:Ac,[jc.errorCode]:jc,[Mc.errorCode]:Mc,[Nc.errorCode]:Nc,[Pc.errorCode]:Pc,[Fc.errorCode]:Fc,[Ic.errorCode]:Ic,[Lc.errorCode]:Lc,[Rc.errorCode]:Rc,[zc.errorCode]:zc,[Bc.errorCode]:Bc,[Vc.errorCode]:Vc,[Hc.errorCode]:Hc,[Uc.errorCode]:Uc};var Z=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Gc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Kc=`code`,qc=`S256`;function Jc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Gc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Yc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Xc(i,a,n);return;case`client_secret_post`:Zc(i,a,r);return;case`none`:Qc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Xc(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Zc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Qc(e,t){t.set(`client_id`,e)}async function $c(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=bc.parse(JSON.parse(n));return new(Wc[e]||Pc)(t||``,r)}catch(e){return new Pc(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function el(e,t){try{return await tl(e,t)}catch(n){if(n instanceof Oc||n instanceof Ac)return await e.invalidateCredentials?.(`all`),await tl(e,t);if(n instanceof kc)return await e.invalidateCredentials?.(`tokens`),await tl(e,t);throw n}}async function tl(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await pl(c,{fetchFn:a}),!s)try{s=await ol(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await ml(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await rl(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!nl(r))throw new Vc(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await bl(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await yl(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await vl(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof X)||e instanceof Pc))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await hl(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function nl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function rl(e,t,n){let r=Tc(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Ec({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function il(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=al(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=al(e,`scope`)||void 0,s=al(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function al(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function ol(e,t,n=fetch){let r=await dl(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return gc.parse(await r.json())}async function sl(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?sl(e,void 0,n):void 0;throw r}}function cl(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ll(e,t,n=fetch){return await sl(e,{"MCP-Protocol-Version":t},n)}function ul(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function dl(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=cl(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ll(o,a,n);return!r?.metadataUrl&&ul(s,i.pathname)&&(s=await ll(new URL(`/.well-known/${t}`,i),a,n)),s}function fl(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function pl(e,{fetchFn:t=fetch,protocolVersion:n=lt}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=fl(e);for(let{url:e,type:n}of i){let i=await sl(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?_c.parse(await i.json()):vc.parse(await i.json())}}}async function ml(e,t){let n,r;try{n=await ol(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await pl(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function hl(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Kc))throw Error(`Incompatible auth server: does not support response type ${Kc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qc))throw Error(`Incompatible auth server: does not support code challenge method ${qc}`)}else s=new URL(`/authorize`,e);let c=await hc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Kc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,qc),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function gl(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function _l(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Yc(Jc(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await $c(l);return yc.parse(await l.json())}async function vl(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await _l(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function yl(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=gl(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return _l(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function bl(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await $c(o);return wc.parse(await o.json())}var xl=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Sl(e){}function Cl(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Sl,onError:n=Sl,onRetry:r=Sl,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
52
|
+
`}var nc=class{constructor(e=sr.stdin,t=sr.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new $s,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=tc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function rc(e){if(e.platform!==`darwin`)return{kind:`unchanged`};let t;try{t=e.realpath(e.bundleAnchorPath)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}let n;try{n=e.statInode(t)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}return n===e.currentInode?{kind:`unchanged`}:{kind:`replaced`,currentInode:e.currentInode,onDiskInode:n}}function ic(e){let t=e.setInterval??setInterval,n=e.clearInterval??clearInterval,r=e.intervalMs??3e5,i=!0,a=!1,o=!1,s=t(()=>{if(!i)return;let t;try{t=e.detect()}catch(t){e.log(`bundle identity check threw unexpectedly (contract violation): ${t instanceof Error?t.message:String(t)}`);return}if(t.kind===`unreadable`){o||(o=!0,e.log(`bundle identity check unreadable${t.reason?`: ${t.reason}`:``} — will retry on next tick`));return}o&&(o=!1,e.log(`bundle identity check recovered from unreadable`)),t.kind!==`unchanged`&&(i=!1,e.onReplaced(t))},r);return typeof s.unref==`function`&&s.unref(),{stop:()=>{a||(a=!0,i=!1,n(s))}}}function ac(e,t){let n;try{n=t.realpathSync(e)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (realpath failed): ${e instanceof Error?e.message:String(e)}`);return}let r;try{r=t.statInoSync(n)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (stat failed): ${e instanceof Error?e.message:String(e)}`);return}return{resolvedPath:n,inode:r}}function oc(e){let t=e.scheduler??{setInterval:(e,t)=>globalThis.setInterval(e,t),clearInterval:e=>globalThis.clearInterval(e)},n=e.getPpid();if(n<=1)return{stop:()=>{}};let r=!1,i=t.setInterval(()=>{if(r)return;let a=e.getPpid();a!==n&&(r=!0,t.clearInterval(i),e.onHostGone(`host process exited (ppid ${n} -> ${a})`))},e.intervalMs??1e3);return i.unref?.(),{stop:()=>t.clearInterval(i)}}function sc(e){let t=t=>{try{e.log(t)}catch{}},n=e.transport.onclose;e.transport.onclose=()=>{t(`[mcp] stdio transport closed (internal shutdown)`),n?.()},e.stdin.once(`end`,()=>t(`[mcp] stdin EOF (host closed pipe)`)),e.stdin.once(`close`,()=>t(`[mcp] stdin closed`)),e.process.on(`exit`,e=>{t(`[mcp] exit code=${e}`)}),e.process.on(`uncaughtExceptionMonitor`,(e,n)=>{t(`[mcp] uncaughtException origin=${n}: ${e instanceof Error?e.stack??e.message:String(e)}`)})}function cc(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function lc(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...cc(t.headers),...cc(r.headers)}:t.headers}):e}let uc;uc=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function dc(e){return(await uc).getRandomValues(new Uint8Array(e))}async function fc(e){let t=``;for(;t.length<e;){let n=await dc(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function pc(e){return await fc(e)}async function mc(e){let t=await(await uc).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function hc(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await pc(e);return{code_verifier:t,code_challenge:await mc(t)}}const Y=y().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:kr.custom,message:`URL must be parseable`,fatal:!0}),h}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),gc=t({resource:i().url(),authorization_servers:s(Y).optional(),jwks_uri:i().url().optional(),scopes_supported:s(i()).optional(),bearer_methods_supported:s(i()).optional(),resource_signing_alg_values_supported:s(i()).optional(),resource_name:i().optional(),resource_documentation:i().optional(),resource_policy_uri:i().url().optional(),resource_tos_uri:i().url().optional(),tls_client_certificate_bound_access_tokens:n().optional(),authorization_details_types_supported:s(i()).optional(),dpop_signing_alg_values_supported:s(i()).optional(),dpop_bound_access_tokens_required:n().optional()}),_c=t({issuer:i(),authorization_endpoint:Y,token_endpoint:Y,registration_endpoint:Y.optional(),scopes_supported:s(i()).optional(),response_types_supported:s(i()),response_modes_supported:s(i()).optional(),grant_types_supported:s(i()).optional(),token_endpoint_auth_methods_supported:s(i()).optional(),token_endpoint_auth_signing_alg_values_supported:s(i()).optional(),service_documentation:Y.optional(),revocation_endpoint:Y.optional(),revocation_endpoint_auth_methods_supported:s(i()).optional(),revocation_endpoint_auth_signing_alg_values_supported:s(i()).optional(),introspection_endpoint:i().optional(),introspection_endpoint_auth_methods_supported:s(i()).optional(),introspection_endpoint_auth_signing_alg_values_supported:s(i()).optional(),code_challenge_methods_supported:s(i()).optional(),client_id_metadata_document_supported:n().optional()}),vc=o({...t({issuer:i(),authorization_endpoint:Y,token_endpoint:Y,userinfo_endpoint:Y.optional(),jwks_uri:Y,registration_endpoint:Y.optional(),scopes_supported:s(i()).optional(),response_types_supported:s(i()),response_modes_supported:s(i()).optional(),grant_types_supported:s(i()).optional(),acr_values_supported:s(i()).optional(),subject_types_supported:s(i()),id_token_signing_alg_values_supported:s(i()),id_token_encryption_alg_values_supported:s(i()).optional(),id_token_encryption_enc_values_supported:s(i()).optional(),userinfo_signing_alg_values_supported:s(i()).optional(),userinfo_encryption_alg_values_supported:s(i()).optional(),userinfo_encryption_enc_values_supported:s(i()).optional(),request_object_signing_alg_values_supported:s(i()).optional(),request_object_encryption_alg_values_supported:s(i()).optional(),request_object_encryption_enc_values_supported:s(i()).optional(),token_endpoint_auth_methods_supported:s(i()).optional(),token_endpoint_auth_signing_alg_values_supported:s(i()).optional(),display_values_supported:s(i()).optional(),claim_types_supported:s(i()).optional(),claims_supported:s(i()).optional(),service_documentation:i().optional(),claims_locales_supported:s(i()).optional(),ui_locales_supported:s(i()).optional(),claims_parameter_supported:n().optional(),request_parameter_supported:n().optional(),request_uri_parameter_supported:n().optional(),require_request_uri_registration:n().optional(),op_policy_uri:Y.optional(),op_tos_uri:Y.optional(),client_id_metadata_document_supported:n().optional()}).shape,..._c.pick({code_challenge_methods_supported:!0}).shape}),yc=o({access_token:i(),id_token:i().optional(),token_type:i(),expires_in:jr().optional(),scope:i().optional(),refresh_token:i().optional()}).strip(),bc=o({error:i(),error_description:i().optional(),error_uri:i().optional()}),xc=Y.optional().or(m(``).transform(()=>void 0)),Sc=o({redirect_uris:s(Y),token_endpoint_auth_method:i().optional(),grant_types:s(i()).optional(),response_types:s(i()).optional(),client_name:i().optional(),client_uri:Y.optional(),logo_uri:xc,scope:i().optional(),contacts:s(i()).optional(),tos_uri:xc,policy_uri:i().optional(),jwks_uri:Y.optional(),jwks:v().optional(),software_id:i().optional(),software_version:i().optional(),software_statement:i().optional()}).strip(),Cc=o({client_id:i(),client_secret:i().optional(),client_id_issued_at:p().optional(),client_secret_expires_at:p().optional()}).strip(),wc=Sc.merge(Cc);o({error:i(),error_description:i().optional()}).strip(),o({token:i(),token_type_hint:i().optional()}).strip();function Tc(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Ec({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var X=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Dc=class extends X{};Dc.errorCode=`invalid_request`;var Oc=class extends X{};Oc.errorCode=`invalid_client`;var kc=class extends X{};kc.errorCode=`invalid_grant`;var Ac=class extends X{};Ac.errorCode=`unauthorized_client`;var jc=class extends X{};jc.errorCode=`unsupported_grant_type`;var Mc=class extends X{};Mc.errorCode=`invalid_scope`;var Nc=class extends X{};Nc.errorCode=`access_denied`;var Pc=class extends X{};Pc.errorCode=`server_error`;var Fc=class extends X{};Fc.errorCode=`temporarily_unavailable`;var Ic=class extends X{};Ic.errorCode=`unsupported_response_type`;var Lc=class extends X{};Lc.errorCode=`unsupported_token_type`;var Rc=class extends X{};Rc.errorCode=`invalid_token`;var zc=class extends X{};zc.errorCode=`method_not_allowed`;var Bc=class extends X{};Bc.errorCode=`too_many_requests`;var Vc=class extends X{};Vc.errorCode=`invalid_client_metadata`;var Hc=class extends X{};Hc.errorCode=`insufficient_scope`;var Uc=class extends X{};Uc.errorCode=`invalid_target`;const Wc={[Dc.errorCode]:Dc,[Oc.errorCode]:Oc,[kc.errorCode]:kc,[Ac.errorCode]:Ac,[jc.errorCode]:jc,[Mc.errorCode]:Mc,[Nc.errorCode]:Nc,[Pc.errorCode]:Pc,[Fc.errorCode]:Fc,[Ic.errorCode]:Ic,[Lc.errorCode]:Lc,[Rc.errorCode]:Rc,[zc.errorCode]:zc,[Bc.errorCode]:Bc,[Vc.errorCode]:Vc,[Hc.errorCode]:Hc,[Uc.errorCode]:Uc};var Z=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Gc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Kc=`code`,qc=`S256`;function Jc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Gc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Yc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Xc(i,a,n);return;case`client_secret_post`:Zc(i,a,r);return;case`none`:Qc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Xc(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Zc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Qc(e,t){t.set(`client_id`,e)}async function $c(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=bc.parse(JSON.parse(n));return new(Wc[e]||Pc)(t||``,r)}catch(e){return new Pc(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function el(e,t){try{return await tl(e,t)}catch(n){if(n instanceof Oc||n instanceof Ac)return await e.invalidateCredentials?.(`all`),await tl(e,t);if(n instanceof kc)return await e.invalidateCredentials?.(`tokens`),await tl(e,t);throw n}}async function tl(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await pl(c,{fetchFn:a}),!s)try{s=await ol(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await ml(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await rl(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!nl(r))throw new Vc(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await bl(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await yl(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await vl(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof X)||e instanceof Pc))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await hl(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function nl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function rl(e,t,n){let r=Tc(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Ec({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function il(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=al(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=al(e,`scope`)||void 0,s=al(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function al(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function ol(e,t,n=fetch){let r=await dl(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return gc.parse(await r.json())}async function sl(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?sl(e,void 0,n):void 0;throw r}}function cl(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ll(e,t,n=fetch){return await sl(e,{"MCP-Protocol-Version":t},n)}function ul(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function dl(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=cl(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ll(o,a,n);return!r?.metadataUrl&&ul(s,i.pathname)&&(s=await ll(new URL(`/.well-known/${t}`,i),a,n)),s}function fl(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function pl(e,{fetchFn:t=fetch,protocolVersion:n=lt}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=fl(e);for(let{url:e,type:n}of i){let i=await sl(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?_c.parse(await i.json()):vc.parse(await i.json())}}}async function ml(e,t){let n,r;try{n=await ol(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await pl(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function hl(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Kc))throw Error(`Incompatible auth server: does not support response type ${Kc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qc))throw Error(`Incompatible auth server: does not support code challenge method ${qc}`)}else s=new URL(`/authorize`,e);let c=await hc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Kc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,qc),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function gl(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function _l(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Yc(Jc(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await $c(l);return yc.parse(await l.json())}async function vl(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await _l(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function yl(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=gl(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return _l(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function bl(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await $c(o);return wc.parse(await o.json())}var xl=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Sl(e){}function Cl(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Sl,onError:n=Sl,onRetry:r=Sl,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
53
53
|
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new xl(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
54
54
|
`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
|
|
55
55
|
`,n);continue}let i=e.charCodeAt(n);if(wl(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
|
|
@@ -59,7 +59,7 @@ ${a}`,d++}else Tl(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e
|
|
|
59
59
|
`,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(wl(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
|
|
60
60
|
${i}`,d++;return}if(Tl(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){i&&i(e.slice(t,n).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}
|
|
61
61
|
${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new xl(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new xl(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}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 wl(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 Tl(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 El=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=Cl({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 Dl={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Ol=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},kl=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=lc(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Dl}async _authThenStart(){if(!this._authProvider)throw new Z(`No auth provider`);let e;try{e=await el(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 Z;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=cc(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 Ol(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 El({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=ot.parse(JSON.parse(e.data));ut(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 Z(`No auth provider`);if(await el(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z(`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:vt(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 Ol(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=il(o);if(this._resourceMetadataUrl=t,this._scope=n,await el(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=il(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Ol(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await el(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Z;return this.send(e)}}throw new Ol(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),wt(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=>ot.parse(e)):[ot.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Ol(-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 Ol(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 Al(e){return ar.join(ar.dirname(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const jl=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function Ml(e){if(e.platform!==`darwin`||!jl.test(e.execPath))return null;let t=Al(e.execPath);return e.exists(t)?t:null}function Nl(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??z,a=r[1];return a?{command:Ml({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 Pl(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 Fl(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Il(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Ll(e,t){return`http://${Il(e)}:${t}/mcp`}function Rl(e){return`${e}/mcp`}function zl(e){return e.replace(/^http/,`ws`)}function Bl(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Vl(e,t){if(e&&e.draining!==!0&&t(e.pid))return Vt(e,{fallbackHost:`127.0.0.1`})??void 0}function Hl(e){return z(e)?V(e,`utf-8`).trim():``}function Ul(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Wl(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Gl(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 Kl(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function ql(e){let t=e.readLock??(()=>Bt(e.lockDir)),n=e.isAlive??zt,r=e.sleep??(e=>Er(e)),i=e.spawn??tr,a=e.readErrorLog??Hl,o=e.openErrorLog??(e=>hr(e,`w`)),s=e.closeFd??dr,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 Ll(_e,t)}let u=t(),d=Vl(u,n);if(d!==void 0)return Rl(d);if(e.envAutoStart===`0`)throw new tt(`OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);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=Vl(t(),n);if(o!==void 0)return Rl(o)}z(e.lockDir)||B(e.lockDir,{recursive:!0});let f=I(e.lockDir,Se),p=o(f),m,h,g=Nl();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}`)}await r(l);let e=Vl(t(),n);if(e!==void 0)return Rl(e)}if(h){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}throw Error(Ul(c,a(f)))}function Jl(e,t){if(e.portOverride!==void 0)return Bl(t);let n=e.readLock??(()=>Bt(e.lockDir)),r=e.isAlive??zt,i=Vl(n(),r);if(i!==void 0)return zl(i)}async function Yl(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new nc(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new kl(new URL(e),{fetch:Pl(r),requestInit:{headers:{...ee({kind:`mcp`,runtimeVersion:D}),...t.connectionId===void 0?{}:{[mt]: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=Wl(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(Kl(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=Gl(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 Xl(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Yl,r=await ql(e),i=e.createConnectionId?.()??Tr(),a=!1,o=(e.startKeepalive??Qs)({connectionId:i,pid:process.pid,resolveWsUrl:async()=>Jl(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 Zl=/^mcp\.\d{4}-\d{2}-\d{2}\.log$/;function Ql(){return I(xr(),`.ok`,`logs`)}function $l(e,t=()=>new Date){try{let n=t().getTime(),r=gr(e).filter(e=>Zl.test(e)).flatMap(t=>{try{let n=H(I(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{U(I(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{U(I(e,t.name)),a-=t.size}catch{}}}catch{}}function eu(e={}){let t=e.logsDir??Ql(),n=e.now??(()=>new Date),r=e.pruneDelayMs??5e3;r<=0?$l(t,n):setTimeout(()=>$l(t,n),r).unref?.();let i=0,a=!1;return{write(e){if(!(i>=5))try{a||=(B(t,{recursive:!0}),!0);let r=n().toISOString();ur(I(t,`mcp.${r.slice(0,10)}.log`),`${r} ${e}`),i=0}catch{a=!1,i++}}}}const tu=cr(import.meta.url),nu=Dr(Qn);async function ru(e){try{let{stdout:t}=await nu(`git`,[`-C`,e,`worktree`,`list`,`--porcelain`],T({timeout:2e3}));return t.split(`
|
|
62
|
-
`).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function iu(e){let t=R(e);for(;;){if(Ae(t))return t;let n=F(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 \`${
|
|
62
|
+
`).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function iu(e){let t=R(e);for(;;){if(Ae(t))return t;let n=F(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 \`${d}\`).`);t=n}}function au(e){try{let t=new URL(e);return t.protocol===`file:`?cr(t):void 0}catch{return}}async function ou(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=au(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function su(e,t,n,r=iu){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 cu(e){let t=eu(),n={write:e=>(t.write(e),process.stderr.write(e))},r=e.spawnTimeoutMs??Fl(process.env.OK_MCP_SPAWN_TIMEOUT_MS),i=e.envAutoStart??process.env.OK_MCP_AUTOSTART,a=Kn({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),o=new jt({name:Ce,version:D});Ot(o);let s=Tr(),c={current:{connectionId:s,displayName:s,colorSeed:s}},l=new Map,u=e=>{if(l.has(e))return;let t=Pt(e),r=c.current,i=Qs({connectionId:s,pid:process.pid,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Jl({lockDir:t,contentDir:e},``),log:t=>n.write(`[mcp] keepalive[${e}]: ${t}\n`)});l.set(e,i)},d=()=>ou({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 ru(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 su(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 su(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 ql({lockDir:Pt(n),contentDir:Ke(o,n),envAutoStart:i,...r===void 0?{}:{timeoutMs:r}});return u(n),s.replace(/\/mcp$/,``)};o.server.oninitialized=()=>{let e=o.server.getClientVersion(),t=Re(e?.name,s);c.current={connectionId:s,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},Fe(o,{serverUrl:g,resolveCwd:h,config:a,identityRef:c,isHostedAgent:ue(process.env)}),_t(o);let _=new nc,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)
|
|
63
63
|
`);let S=!1,C=()=>{S||(S=!0,setTimeout(()=>{n.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
64
64
|
`),process.exit(1)},5e3).unref(),x().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,C),process.once(`SIGTERM`,C),process.stdin.on(`end`,()=>{n.write(`[mcp] stdin end — host disconnected, shutting down
|
|
65
65
|
`),C()}),process.stdin.on(`error`,e=>{n.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),C()}),b=oc({getPpid:()=>process.ppid,onHostGone:e=>{n.write(`[mcp] ${e} — shutting down\n`),C()}}),sc({log:e=>n.write(`${e}\n`),transport:_,process,stdin:process.stdin}),process.platform===`darwin`){let e=ac(tu,{realpathSync:_r,statInoSync:e=>H(e).ino,log:e=>n.write(`${e}\n`)});if(e!==void 0){n.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${D}\n`);let{resolvedPath:t,inode:r}=e;y=ic({detect:()=>rc({bundleAnchorPath:tu,currentInode:r,platform:process.platform,realpath:_r,statInode:e=>H(e).ino}),onReplaced:e=>{n.write(`[mcp] bundle replaced anchor=${t} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${D} — exiting for host respawn\n`),C()},log:e=>n.write(`[mcp] ${e}\n`)})}}return{close:x}}function lu(e){return new O(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the Desktop app bundle (macOS-only proxy; no-op elsewhere; equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=Fl(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Xl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Ys(process.env,i,process.platform);if(a.proxy){let e=Js(process.platform,xr(),{existsSync:z});if(e===null)Xs({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed OpenKnowledge.app bundle found`});else try{await Zs({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Xs({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Xs({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await cu({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}const uu=/<aside>\s*([\s\S]*?)\s*<\/aside>/g,du=/^(?:\p{Extended_Pictographic}️?\s*)+/u;function fu(e){return e.replace(uu,(e,t)=>{let n=t.replace(/\r\n/g,`
|
|
@@ -74,7 +74,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
74
74
|
`).replace(/\n+$/,``);return e.endsWith(`
|
|
75
75
|
`)?`${c}\n`:c}function Ku(e){return e.replace(/\r\n|\r|\n/g,`<br>`).replace(/\|/g,`\\|`)}function qu(e){return/\s/.test(e)?`<${e}>`:e}function Ju(e,t={}){let{header:n,rows:r}=_u(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(Ku).join(` | `)} |`,`| ${n.map(()=>`---`).join(` | `)} |`,...r.map(e=>`| ${n.map((n,r)=>{let i=e[r]??``,a=Ku(i);if(r===o&&t.linkForTitle&&i.trim()!==``){let e=t.linkForTitle(i);if(e)return`[${a}](${qu(e)})`}return a}).join(` | `)} |`)].join(`
|
|
76
76
|
`),columns:i,wide:i>a}}function Yu(e,t){let n=e.match(/^#\s+(.+)$/m);return n?n[1].trim():t}function Xu(e,t){return`# ${e}\n\n${t}\n`}const Zu=[`links`,`frontmatter`,`callouts`,`images`,`tables`],Qu=/\.mdx?$/i;function $u(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 ed(e,t={}){let n=t.selected??new Set(Zu),r=Ru(e);if(!r&&!t.force)return{changes:[],assets:[],deletions:[],report:$u(!1)};let i=$u(r),a=Fu(e),o=Eu(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(!Qu.test(e)||s&&l.has(e))continue;let r;try{r=V(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=gu(a,rr(e),{strip:t.stripBase64});a=r.markdown;for(let t of r.assets)d.push({path:I(F(e),t.filename),bytes:t.bytes});i.assetsExtracted+=r.assets.length,o(`images`,n)}if(n.has(`callouts`)){let e=a;a=fu(a),o(`callouts`,e)}if(n.has(`frontmatter`)){let t=c.get(e);if(t){let e=a;a=Gu(a,t.propertyKeys),o(`frontmatter`,e)}}if(n.has(`links`)){let e=a;a=Pu(a,{redirectCsv:s}),o(`links`,e)}a!==r&&u.push({path:e,content:a})}if(s)for(let e of o){let r=Ju(e.csvText,{linkForTitle:t=>{let n=Cu(e.folderIndex,t);return n.ambiguous&&(i.ambiguousTitleLinks+=1),n.path?L(F(e.stubTargetPath),n.path):null}});if(r.columns===0)continue;let a=e.stubPath??e.stubTargetPath,o=null;if(e.stubPath)try{o=V(e.stubPath,`utf8`)}catch{i.unreadable.push(e.stubPath);continue}let c=Xu(o===null?e.fallbackTitle:Yu(o,e.fallbackTitle),r.table);n.has(`links`)&&(c=Pu(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 td(e){for(let t of e.assets)B(F(t.path),{recursive:!0}),br(t.path,t.bytes);for(let t of e.changes)B(F(t.path),{recursive:!0}),br(t.path,t.content,`utf8`);for(let t of e.deletions)try{U(t)}catch(e){if(e.code!==`ENOENT`)throw e}}const nd={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`},rd=[`images`,`callouts`,`frontmatter`,`tables`,`links`];function id(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 rd)n.push(` ${nd[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(`
|
|
77
|
-
`)}function ad(e,t){return JSON.stringify({applied:t.applied,...e},null,2)}function od(e){let t=new Set(Zu);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: ${Zu.join(`, `)}`);return e})}function sd(e,t){let n=new Set(Zu);if(e&&(n=new Set(od(e))),t)for(let e of od(t))n.delete(e);return n}function cd(){let e=new O(`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=R(e??process.cwd()),r;try{r=sd(t.only,t.skip)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let i=ed(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{td(i)}catch(e){console.error(`Failed to apply changes: ${e instanceof Error?e.message:String(e)}`),process.exitCode=4;return}console.log(t.json?ad(a,{applied:t.apply??!1}):id(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 ld(e,t){return t===`darwin`?{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 ud(e,t={}){let n=ld(e,t.platform??process.platform);return mn(n.command,n.args,{spawn:t.spawn,env:t.env,timeoutMs:t.timeoutMs})}function dd(e,t,n=process.platform){let r=ld(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 fd(e=()=>gn(yn())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>Te({lockDir:w(e)}).baseUrl,classifyName:(e,t)=>{let n=I(e,t);try{return H(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:ud,log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function pd(e){return e.startsWith(`/`)||e.includes(`\\`)||e.split(`/`).includes(`..`)}function md(e){return e.error("No OpenKnowledge desktop app found and no UI is running. Install it from https://openknowledge.ai/download, or run `ok start` to serve the editor, then retry."),1}async function hd(e,t,n){let r=await n.openTarget(e);return r.ok?(n.log(t),0):(n.error(`Could not open ${e}: ${dd(r.reason,e)}.`),1)}async function gd(e,t,n){let r=R(t.project??process.cwd()),i=e.replace(/\/+$/,``);if(!i)return n.error("Nothing to open: pass a doc, folder, or skill name (e.g. `ok open specs/foo/SPEC`)."),1;if(pd(i))return n.error(`Invalid name "${i}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(t.skill===!0){let e=t.scope??`project`;if(!ce.includes(e))return n.error(`Invalid --scope "${t.scope}": expected one of ${ce.join(`, `)}.`),1;if(n.detectBundlePath())return hd(`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(`__skill__/${e}/${i}`)}`,`Opening skill ${i} (${e}) in the OpenKnowledge desktop app.`,n);let a=n.resolveBaseUrl(r);if(a){let t=`${a}/#/${Ge(e,i)}`;return hd(t,`Opening skill ${i} (${e}) in your browser: ${t}`,n)}return md(n)}let a=/\/+$/.test(e)||n.classifyName(r,i)===`folder`,o=n.detectBundlePath();if(a){if(o)return hd(`openknowledge://open?project=${encodeURIComponent(r)}&folder=${encodeURIComponent(i)}`,`Opening folder ${i} in the OpenKnowledge desktop app.`,n);let e=n.resolveBaseUrl(r);if(e){let t=`${e}/#/${Qe(i)}`;return hd(t,`Opening folder ${i} in your browser: ${t}`,n)}return md(n)}if(o)return hd(`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(i)}`,`Opening ${i} in the OpenKnowledge desktop app.`,n);let s=n.resolveBaseUrl(r);if(s){let e=`${s}/#/${Xe(i)}`;return hd(e,`Opening ${i} in your browser: ${e}`,n)}return md(n)}function _d(){return new O(`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: ${ce.join(` | `)}`,`project`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action(async(e,t)=>{process.exitCode=await gd(e,t,fd())})}function vd(e){return new O(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-
|
|
77
|
+
`)}function ad(e,t){return JSON.stringify({applied:t.applied,...e},null,2)}function od(e){let t=new Set(Zu);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: ${Zu.join(`, `)}`);return e})}function sd(e,t){let n=new Set(Zu);if(e&&(n=new Set(od(e))),t)for(let e of od(t))n.delete(e);return n}function cd(){let e=new O(`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=R(e??process.cwd()),r;try{r=sd(t.only,t.skip)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let i=ed(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{td(i)}catch(e){console.error(`Failed to apply changes: ${e instanceof Error?e.message:String(e)}`),process.exitCode=4;return}console.log(t.json?ad(a,{applied:t.apply??!1}):id(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 ld(e,t){return t===`darwin`?{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 ud(e,t={}){let n=ld(e,t.platform??process.platform);return mn(n.command,n.args,{spawn:t.spawn,env:t.env,timeoutMs:t.timeoutMs})}function dd(e,t,n=process.platform){let r=ld(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 fd(e=()=>gn(yn())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>Te({lockDir:w(e)}).baseUrl,classifyName:(e,t)=>{let n=I(e,t);try{return H(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:ud,log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function pd(e){return e.startsWith(`/`)||e.includes(`\\`)||e.split(`/`).includes(`..`)}function md(e){return e.error("No OpenKnowledge desktop app found and no UI is running. Install it from https://openknowledge.ai/download, or run `ok start` to serve the editor, then retry."),1}async function hd(e,t,n){let r=await n.openTarget(e);return r.ok?(n.log(t),0):(n.error(`Could not open ${e}: ${dd(r.reason,e)}.`),1)}async function gd(e,t,n){let r=R(t.project??process.cwd()),i=e.replace(/\/+$/,``);if(!i)return n.error("Nothing to open: pass a doc, folder, or skill name (e.g. `ok open specs/foo/SPEC`)."),1;if(pd(i))return n.error(`Invalid name "${i}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(t.skill===!0){let e=t.scope??`project`;if(!ce.includes(e))return n.error(`Invalid --scope "${t.scope}": expected one of ${ce.join(`, `)}.`),1;if(n.detectBundlePath())return hd(`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(`__skill__/${e}/${i}`)}`,`Opening skill ${i} (${e}) in the OpenKnowledge desktop app.`,n);let a=n.resolveBaseUrl(r);if(a){let t=`${a}/#/${Ge(e,i)}`;return hd(t,`Opening skill ${i} (${e}) in your browser: ${t}`,n)}return md(n)}let a=/\/+$/.test(e)||n.classifyName(r,i)===`folder`,o=n.detectBundlePath();if(a){if(o)return hd(`openknowledge://open?project=${encodeURIComponent(r)}&folder=${encodeURIComponent(i)}`,`Opening folder ${i} in the OpenKnowledge desktop app.`,n);let e=n.resolveBaseUrl(r);if(e){let t=`${e}/#/${Qe(i)}`;return hd(t,`Opening folder ${i} in your browser: ${t}`,n)}return md(n)}if(o)return hd(`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(i)}`,`Opening ${i} in the OpenKnowledge desktop app.`,n);let s=n.resolveBaseUrl(r);if(s){let e=`${s}/#/${Xe(i)}`;return hd(e,`Opening ${i} in your browser: ${e}`,n)}return md(n)}function _d(){return new O(`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: ${ce.join(` | `)}`,`project`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action(async(e,t)=>{process.exitCode=await gd(e,t,fd())})}function vd(e){return new O(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DAuizf4r.mjs`),r=e(),i=process.cwd(),a=Ke(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 yd(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function bd(e,t,n=process.cwd()){let r=e.op??`sync`,i=Bt(w(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...ee({kind:`cli`,runtimeVersion:D})},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}`)}yd(e.json,{type:`triggered`,op:r,port:i.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 a=Rt({baseDir:n});if(r===`sync`||r===`pull`){yd(e.json,{type:`step`,step:`pull`});let t=await a.pull();yd(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(yd(e.json,{type:`step`,step:`push`}),await a.push(),yd(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
78
78
|
`)),yd(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function xd(e){return new O(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await bd({json:t.json,op:`sync`},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(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Sd(e){return new O(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await bd({json:t.json,op:`pull`},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(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Cd(e){return new O(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await bd({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)}})}function wd(e,t){if(e.packSkillHomeRefusal===void 0)return``;if(e.packSkillHomeRefusal===`home-escapes-project`)return`\n${N(`!`)} The ${t} skills were not installed: this project's skill folder is a symlink pointing outside the project, and Open Knowledge will not write through it. Replace it with a real directory inside the project, then run \`ok seed\` again.`;let n=[...new Set([le,...ie.map(e=>ge[e])].filter(e=>e!==null).map(re))].map(e=>`${e}/`);return`\n${N(`!`)} The ${t} skills were not installed: this project has no agent folder for them. Open Knowledge only writes skills into a folder that already exists (${n.join(`, `)}) and never creates one for you. Create the folder your agent uses, then run \`ok seed\` again to install them.`}function Td(e){return typeof e==`string`&&Me.includes(e)}async function Ed(e={}){let t=R(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!Je[n])return{status:`failed`,message:`${M(`Error:`)} Unknown pack "${n}". Available: ${Me.join(`, `)}`,exitCode:1};let r;try{r=await je({projectDir:t,rootDir:e.root,packId:n,skipPrerequisite:e.dryRun===!0})}catch(e){return e instanceof Ze?{status:`prerequisite-missing`,message:`${M(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${M(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(!ne(r)){let e=Je[n].name,t=(r.packSkills??[]).filter(e=>e.conflict).map(e=>`\n${N(`!`)} Skill "${e.name}" is your own — the pack's version is not installed. Rename yours to install the pack's version.`).join(``),i=wd(r,e);return{status:`no-op`,message:`${j(`Your ${e} pack is already seeded.`)}${i}${t}${i===``?`\n${A(`Nothing to do.`)}`:``}`,plan:r,exitCode:0}}if(e.dryRun){let e=We(Je[n]);return{status:`dry-run`,message:`${P(`Reference this pack for inspiration (dry-run — no changes made):`)}\n\n${e}\n\n${P(`Plan:`)}\n\n${Od(r,t)}`,plan:r,exitCode:0}}if(!e.yes&&!await kd(`${P(`Plan:`)}\n\n${Od(r,t)}\n\n${P(`Apply?`)} ${A(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:A(`Cancelled.`),plan:r,exitCode:0};let i=await Pe(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${M(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${N(`Applied`)} ${i.applied} entries, ${N(String(i.errors.length))} error(s):`,...e].join(`
|
|
79
79
|
`),plan:r,exitCode:1}}let a=Je[n].name,o=i.packSkillsInstalled.length>0?`\n${A(`Installed the ${a} skills for: ${i.packSkillsInstalled.join(`, `)}`)}`:``,s=i.pluginsEnabled.length>0?`\n${A(`Enabled plugin(s) included with this pack: ${i.pluginsEnabled.join(`, `)} — turn off any time in Settings.`)}`:``,c=(i.packSkillConflicts??[]).map(e=>e.hosts===void 0||e.hosts.length===0?`\n${N(`!`)} Skill "${e.name}" was not installed — you already have your own skill with that name. Rename yours if you want the pack's version.`:`\n${N(`!`)} Skill "${e.name}" was not installed for ${e.hosts.join(`, `)} — you already have your own skill with that name there. Rename yours if you want the pack's version.`).join(``);return{status:`applied`,message:`${j(`✓ Seeded ${a}`)} ${A(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}${s}${wd(r,a)}${c}`,plan:r,exitCode:0}}function Dd(){let e=[P(`Available packs:`)];for(let t of Me){let n=Je[t];e.push(` ${j(t)} ${A(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
|
80
80
|
`)}function Od(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(P(`Folders to create:`));for(let e of r)n.push(` ${j(`+`)} ${k(L(t,R(t,e.path))||e.path)}${A(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(P(`Files to create:`));for(let e of i)n.push(` ${j(`+`)} ${k(L(t,R(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(A(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${A(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(N(`Warnings:`));for(let t of e.warnings)n.push(` ${N(`!`)} ${t}`)}let a=(e.packSkills??[]).filter(e=>e.conflict);if(a.length>0){n.length>0&&n.push(``),n.push(N(`Name collisions:`));for(let e of a)n.push(` ${N(`!`)} Skill "${e.name}" is your own — the pack's version will not be installed. Rename yours to install the pack's version.`)}return n.join(`
|
|
@@ -83,7 +83,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
83
83
|
`);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 Nd(e){return new O(`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 Md(t,await e())})}async function Pd(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 Fd(e,t){let{host:n,json:r}=e;W(n);let i=await ga(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 Pd(new la({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 Id(e){return new O(`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 Fd(t,await e())})}function Ld(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(`
|
|
84
84
|
`)??``}\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 Rd(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 zd(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 Bd(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function Vd(e){return Rt(Ha(e,[])).env(Ia())}function Hd(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const Ud={ensureOkScaffold:e=>{et(e)},gitFactory:Vd};async function Wd(e){let t={...Ud,...e.deps},n=R(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await Bd(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:Ld(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!z(I(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await Rd({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(Ld(t)===`name-conflict`){let t=await zd(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:Ld(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=Hd(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.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/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function Gd(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 Kd(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;if(W(n),Ee(s)){process.stderr.write(`${new it(R(s)).message}\n`),process.exitCode=64;return}let l=await ga(n,t);if(l==null){Gd(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new la({auth:l,...u?{baseUrl:u}:{}});try{er(`git config user.email`,T({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`}Gd(c,await Wd({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function qd(e){return new O(`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'
|
|
85
85
|
`),process.exit(1)),await Kd(t,await e())})}function Jd(){let e=new O(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let t=()=>hn();return e.addCommand(Id(t)),e.addCommand(Nd(t)),e.addCommand(qd(t)),e}function Yd(){return new O(`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=R(e.project??process.cwd()),n=Mn(t),r=Pn(t,Tn(t));if(r.kind===`no-exclude`){Xd(e.json,t,r.reason);return}let i=Mn(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${k(`Sharing mode is already`)} ${P(`shared`)} ${k(`— nothing to do.`)}\n`);return}process.stderr.write(`${j(`✓`)} ${P(`Sharing mode set to`)} ${j(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${P(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function Xd(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(`${N({"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 Zd(){return new O(`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=R(e.project??process.cwd()),n=Mn(t),r=Nn(t),i=[...zn(t)],a=Rn(t,Tn(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,skillsShared:r,excluded:i,trackedUpstream:a};process.stdout.write(`${JSON.stringify(e)}\n`);return}let o=[];if(o.push(`OpenKnowledge sharing mode: ${Qd(n)}`),r&&o.push(` ${P(`.ok/skills`)} is committable (carved out); the rest of .ok/ stays local.`),o.push(``),o.push(`Excluded from git via ${P(`.git/info/exclude`)}:`),i.length===0)o.push(` (none)`);else for(let e of i)o.push(` ${e}`);if(o.push(``),o.push(`Other OK paths exist but are tracked upstream:`),a.length===0)o.push(` (none)`);else for(let e of a)o.push(` ${e}`);o.push(``),o.push(`Toggle with: ${k(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),r&&o.push(` (that shares the whole project; to undo only the skills carve-out, use the desktop app: Settings > Sync & sharing)`),process.stdout.write(`${o.join(`
|
|
86
|
-
`)}\n`)})}function Qd(e){switch(e){case`shared`:return j(`shared`);case`local-only`:return j(`local-only`);case`no-git`:return N(`no-git (not a git repository)`)}}function $d(){return new O(`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=R(e.project??process.cwd()),n=On(t,Tn(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){ef(e.json,t,n.reason);return}let r=Mn(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${P(`Sharing mode is already`)} ${j(`local-only`)} ${P(`— nothing to do.`)}\n`);return}process.stderr.write(`${j(`✓`)} ${P(`Sharing mode set to`)} ${j(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${P(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function ef(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(`${N({"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 tf(){let e=new O(`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(Yd()),e.addCommand($d()),e.addCommand(Zd()),e}const nf=new Set([`--cwd`,`--log-level`]);function rf(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){nf.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function af(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 of(e){return/\.(md|mdx)$/i.test(e)}function sf(e,t){if(of(t))return!0;try{return H(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 cf(e=()=>gn(yn())){return{prepare:nt,detectBundlePath:()=>e().bundlePath??null,openTarget:ud,runProjectOpen:(e,t)=>gd(e,{project:t},fd()),runBrowserOpen:e=>uf(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function lf(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof yt||e instanceof kt||e instanceof Tt)return t.error(e.message),1;throw e}if(n.mode===`project`)return await t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`,r=await t.openTarget(e);return r.ok?(t.log(`Opening ${n.singleDocRelPath} in the OpenKnowledge desktop app.`),0):(t.error(`Could not open the OpenKnowledge desktop app: ${dd(r.reason,e)}.`),1)}return await t.runBrowserOpen(n),0}async function uf(e){let{createEphemeralProjectDir:t}=await import(`./src-
|
|
86
|
+
`)}\n`)})}function Qd(e){switch(e){case`shared`:return j(`shared`);case`local-only`:return j(`local-only`);case`no-git`:return N(`no-git (not a git repository)`)}}function $d(){return new O(`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=R(e.project??process.cwd()),n=On(t,Tn(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){ef(e.json,t,n.reason);return}let r=Mn(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${P(`Sharing mode is already`)} ${j(`local-only`)} ${P(`— nothing to do.`)}\n`);return}process.stderr.write(`${j(`✓`)} ${P(`Sharing mode set to`)} ${j(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${P(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function ef(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(`${N({"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 tf(){let e=new O(`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(Yd()),e.addCommand($d()),e.addCommand(Zd()),e}const nf=new Set([`--cwd`,`--log-level`]);function rf(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){nf.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function af(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 of(e){return/\.(md|mdx)$/i.test(e)}function sf(e,t){if(of(t))return!0;try{return H(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 cf(e=()=>gn(yn())){return{prepare:nt,detectBundlePath:()=>e().bundlePath??null,openTarget:ud,runProjectOpen:(e,t)=>gd(e,{project:t},fd()),runBrowserOpen:e=>uf(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function lf(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof yt||e instanceof kt||e instanceof Tt)return t.error(e.message),1;throw e}if(n.mode===`project`)return await t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`,r=await t.openTarget(e);return r.ok?(t.log(`Opening ${n.singleDocRelPath} in the OpenKnowledge desktop app.`),0):(t.error(`Could not open the OpenKnowledge desktop app: ${dd(r.reason,e)}.`),1)}return await t.runBrowserOpen(n),0}async function uf(e){let{createEphemeralProjectDir:t}=await import(`./src-BMc6VYxR.mjs`),{loadConfig:n}=await import(`./src-C49kugTg.mjs`),{bootStartServer:r,resolveBundledReactShellDir:i,resolveHost:a}=await import(`./start-De77XKSr.mjs`),{openBrowser:o}=await import(`./open-browser-xN9OlX1t.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()=>{if(!l){l=!0;try{await u?.destroy()}catch{}try{await wr(c,{recursive:!0,force:!0})}catch{}}},f=()=>{d().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}/#/${Xe(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.
|
|
87
87
|
`),o(h)),await new Promise(()=>{})}function df(){let e=new O(`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=R(process.cwd()),n=De(He(t)?.rootPath??t),r=Nt({projectDir:n}),i={...r,skills:r.skills.filter(e=>me(e.provenance,n))};if(e.json){process.stdout.write(`${JSON.stringify(i,null,2)}\n`);return}if(i.skills.length===0){process.stdout.write(`${A(`No installed skills found across any agent.`)}\n`);return}process.stdout.write(`${P(`${i.skills.length} installed skill(s):`)}\n`);for(let e of i.skills){let t=e.provenance.version?A(` v${e.provenance.version}`):``,n=[e.inert.commands&&`commands`,e.inert.hooks&&`hooks`,e.inert.mcp&&`mcp`].filter(Boolean),r=n.length>0?A(` [${n.join(`, `)}]`):``;process.stdout.write(` ${j(e.name)}${t} ${A(e.sourceHarnesses.join(`, `))}${r}\n`)}process.stdout.write(`\n${P(`${i.packs.length} pack(s):`)}\n`);for(let e of i.packs)process.stdout.write(` ${k(e.name)} ${A(`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=Zt(w(process.cwd()),`server`);if(n.status!==`alive`){process.stderr.write(`${M(`Error:`)} no running Open Knowledge server for this project. Start it with ${P(`ok start`)} and retry.\n`),process.exitCode=1;return}let r;try{r=await fetch(`http://127.0.0.1:${n.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(`${M(`Error:`)} could not reach the server: ${t}\n`),process.exitCode=1;return}let i=await r.json().catch(()=>({}));if(!r.ok){let e=i.detail??i.title??`HTTP ${r.status}`;process.stderr.write(`${M(`Import failed:`)} ${e}\n`),process.exitCode=1;return}let a=i.name;if(i.alreadyImported){process.stdout.write(`${k(`Already imported:`)} ${P(a)} (identical content).\n`);return}let o=i.provenance??{},s=i.collisionRenamedFrom;process.stdout.write(`${j(`Imported`)} ${P(a)}${s?A(` (renamed from ${s} — name was taken)`):``} from ${A(o.source??e)}${o.publisher?A(` · ${o.publisher}`):``}.\n${A(`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 i.warnings??[])process.stdout.write(` ${A(`! ${e}`)}\n`)}),e}function ff(e){return{server:pf(`server`,e),ui:e.status===`alive`&&Ht(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 pf(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};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`:return{name:e,state:`dead-pid`,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 mf(e){return`${hf(e.server)}\n${hf(e.ui)}`}function hf(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``: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 \`ok 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 gf(e){let t=e.inspect??(()=>Zt(e.lockDir,`server`)),n=e.log??(e=>console.log(e)),r=ff(t());return e.json?n(JSON.stringify(r,null,2)):n(mf(r)),r}function _f(e){return new O(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),gf({lockDir:w(process.cwd()),json:t.json===!0})})}function vf(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 yf(e,t){let n=Or({input:e.input,output:e.output});try{return(await n.question(t)).trim()}finally{n.close()}}async function bf(e={}){let t={input:e.input??process.stdin,output:e.output??process.stderr};t.output.write(A(`
|
|
88
88
|
What you share is sent to the OpenKnowledge team.
|
|
89
89
|
`));let n=await In({message:`Before you go, mind sharing why? (optional)`,default:null,pageSize:pe.length+1,choices:[...pe.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 yf(t,A(`Anything else we should know? (optional) `)),i=await yf(t,A(`Email, if we may follow up (optional) `));return{reason:n,note:r||void 0,email:i||void 0}}async function xf(e){if(!vf(e))return`not-prompted`;let t;try{t=await(e.collect??(()=>bf(e)))()}catch{return`failed`}return C(t)?((e.output??process.stderr).write(`\n${P(`Thank you. We read every response.`)}\n\n`),(await(e.submit??se)({...t,source:`cli_uninstall`,appVersion:e.appVersion,platform:e.platform})).ok?`submitted`:`undelivered`):`skipped`}function Sf(e,t,n=Cf,r=z,i={}){let a=[],o=i.platform??process.platform,s=i.env??process.env;if(o===`darwin`)for(let t of[`/Applications/OpenKnowledge.app`,I(e,`Applications`,`OpenKnowledge.app`)])r(t)&&a.push({method:`app`,label:`OK Desktop (${t})`,instruction:`Move ${t} to the Trash (or: rm -rf "${t}")`});else if(o===`win32`){let e=s.LOCALAPPDATA;if(e)for(let t of[`@inkeepopen-knowledge-desktop`,`OpenKnowledge`]){let n=I(e,`Programs`,t,`OpenKnowledge.exe`);if(r(n)){a.push({method:`app`,label:`OK Desktop (${n})`,instruction:`Uninstall from Windows Settings → Apps → Installed apps → OpenKnowledge`});break}}}else o===`linux`&&r(`/opt/OpenKnowledge/openknowledge`)&&a.push({method:`app`,label:`OK Desktop (/opt/OpenKnowledge)`,instruction:`Remove with your package manager: sudo apt remove openknowledge (Debian/Ubuntu) or sudo dnf remove OpenKnowledge (Fedora/RHEL)`});return n([`ls`,`-g`,`--depth=0`,`@inkeep/open-knowledge`])?.includes(`@inkeep/open-knowledge@`)&&a.push({method:`npm-global`,label:`npm global install`,instruction:`npm uninstall -g @inkeep/open-knowledge`}),t&&/[/\\]_npx[/\\]/.test(t)&&a.push({method:`npx`,label:`npx (ephemeral)`,instruction:`Nothing to uninstall — npx runs from a temporary cache. (Optional: npm cache clean --force)`}),a}function Cf(e){try{return $n(`npm`,e,T({encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}))}catch{return null}}const wf=`━`.repeat(64);function Tf(e,t=process.platform){let n=[N(wf),P(` One more step — remove the OpenKnowledge app itself`),A(` (OpenKnowledge can't delete its own running binary — do this by hand.)`),``];if(e.length===0){let e=t===`win32`?`uninstall from Settings → Apps → Installed apps → OpenKnowledge`:t===`linux`?`remove the openknowledge package with your package manager (apt / dnf)`:`move /Applications/OpenKnowledge.app to the Trash`;n.push(A(` Install method not detected. If you installed it, remove it via:`)),n.push(` ${k(`OK Desktop`)} — ${e}`),n.push(` ${k(`npm global`)} — npm uninstall -g @inkeep/open-knowledge`),n.push(` ${k(`npx`)} — nothing to remove (runs from a temporary cache)`)}else for(let t of e)n.push(` ${k(t.label)}`),n.push(` ${t.instruction}`);return n.push(N(wf)),n.join(`
|
|
@@ -93,7 +93,7 @@ What you share is sent to the OpenKnowledge team.
|
|
|
93
93
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:e.map(e=>({name:`${e.path}${e.current?` (current)`:``}${e.running?` (running — will be stopped)`:``}`,value:e.path,checked:!1}))})}const Af=A(`The openknowledge:// URL scheme deregisters itself once the app is removed — no action needed.`);async function jf(e={}){let t=e.home??xr(),n=e.platform??process.platform,r=e.env??process.env,i=R(e.cwd??process.cwd()),a=e.host??`github.com`,o=e.purgeContent??!1,s=e.deps?.discoverLockDirs??Et,c=e.deps?.resolveRecentProjects??Of,l=e.deps?.detectInstallMethods??Sf,u=await s(),d=Mo({home:t,platform:n,env:r,host:a,lockDirs:u,marker:Yt(t),recentDeinitProjectRoots:await c({home:t,platform:n,env:r,cwd:i,lockDirs:u,yes:e.yes,allProjects:e.allProjects,dryRun:e.dryRun,isTTY:e.isTTY}),purgeContent:o}),f=A("Individual projects are only removed when you select them (or pass --all-projects). To remove OpenKnowledge from one project, run `ok deinit` inside it."),p=()=>Tf(l(t,e.argv1??process.argv[1],void 0,void 0,{platform:n,env:r}),n);if(e.dryRun)return{status:`dry-run`,message:e.json?JSON.stringify(Ho(d),null,2):[P(`Would remove (dry-run — no changes made):`),``,Bo(d),``,f,``,p()].join(`
|
|
94
94
|
`),exitCode:0};if(e.json&&!e.yes)return{status:`failed`,message:`${M(`Error:`)} --json requires --yes (or --dry-run) so there is no interactive prompt.`,exitCode:1};if(!e.yes){if(!(e.isTTY??process.stdout.isTTY))return{status:`cancelled`,message:`${M(`Aborted:`)} refusing to uninstall non-interactively without --yes.`,exitCode:1};if(process.stderr.write(`${P(`This will remove OpenKnowledge from your machine:`)}\n\n${Bo(d)}\n\n${N(`This cannot be undone.`)}\n\n`),!await Co(`${P(`Remove all of the above?`)} ${A(`[y/N] `)}`,e.confirmStream))return{status:`cancelled`,message:A(`Cancelled. Nothing was removed.`),exitCode:0}}let m=await Io(d,e.deps?.runRemovalDeps),h=m.failed.length===0?async()=>{await xf({stdinIsTTY:e.isStdinTTY,stdoutIsTTY:e.isTTY,yes:e.yes,json:e.json,appVersion:Un,platform:n,...e.deps?.feedback})}:void 0,g=[e.json?JSON.stringify(Uo(`uninstall`,m),null,2):Vo(m)];return e.json||(g.push(``,f,Af),m.failed.length===0&&g.push(``,j(`OpenKnowledge's files have been removed from this machine.`)),g.push(``,p())),{status:m.failed.length>0?`failed`:`done`,message:g.join(`
|
|
95
95
|
`),exitCode:+(m.failed.length>0),runFeedbackAfterReport:h}}function Mf(){return new O(`uninstall`).description(`Remove OpenKnowledge from your machine — credentials, PATH entries, editor MCP configs, skill bundles, app data, and ~/.ok. Keeps your markdown content and your authored skills (~/.ok/skills) unless --purge-content. Detects the app install and prints how to remove it; never self-deletes.`).option(`-y, --yes`,`Skip the confirmation prompt (removes the global footprint only; add --all-projects to also deinit projects)`).option(`--dry-run`,`Print the removal plan and exit without changing anything`).option(`--json`,`Emit a machine-readable plan/outcome (requires --yes or --dry-run)`).option(`--purge-content`,`Also remove user-authored content (~/.ok/skills)`).option(`--all-projects`,`Also deinit every recent/running project (by default no project is removed — you pick them interactively)`).action(async e=>{let t=await jf({yes:e.yes,dryRun:e.dryRun,json:e.json,purgeContent:e.purgeContent,allProjects:e.allProjects});process.stdout.write(`${t.message}\n`),await t.runFeedbackAfterReport?.(),t.exitCode!==0&&(process.exitCode=t.exitCode)})}function Nf(e){return[e,`Copyright (C) 2026 Inkeep, Inc.`,`License GPL-3.0-or-later: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.`,`This is free software: you are free to change and redistribute it.`,`There is NO WARRANTY, to the extent permitted by law.`].join(`
|
|
96
|
-
`)}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR),Mt();const Q=new O;let $,Pf;function Ff(){return Pf}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Nf(Un)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=Jt(n,process.cwd());r!==null&&(dn(process.cwd()),process.chdir(r),console.error(`[ok] Using OpenKnowledge project at ${r}`));let i;try{let e=Gn(r??t);if(i=e.config,po(n))for(let t of e.diagnostics)t.code===`REMOVED_KEY`&&console.error(`[ok] ${
|
|
96
|
+
`)}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR),Mt();const Q=new O;let $,Pf;function Ff(){return Pf}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Nf(Un)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=Jt(n,process.cwd());r!==null&&(dn(process.cwd()),process.chdir(r),console.error(`[ok] Using OpenKnowledge project at ${r}`));let i;try{let e=Gn(r??t);if(i=e.config,po(n))for(let t of e.diagnostics)t.code===`REMOVED_KEY`&&console.error(`[ok] ${g(t)}`);for(let t of e.ignoredCommittedKeys)console.error(`[ok] ${fe(t)}`)}catch(e){if(n===`uninstall`||n===`deinit`)console.error(`[ok] project config could not be loaded; ${n} will use defaults: ${e instanceof Error?e.message:String(e)}`),i=$e.parse({});else throw e}$=i;let a=e.args?.[0]??e.name()??`cli`;Pf=st({name:`cli`,project:i.project?.name??void 0}),Pf.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{let e=gn(yn());if(e.available){pn({spawn:tr},e);return}await qn($,{})});const If=Jn(()=>$);Q.addCommand(If);const Lf=lu(()=>$);Q.addCommand(Lf),Q.addCommand(Bn()),Q.addCommand(Ad()),Q.addCommand(cd()),Q.addCommand(So(),{hidden:!0}),Q.addCommand(Zn()),Q.addCommand(df());const Rf=vd(()=>$);Q.addCommand(Rf),Q.addCommand(Ir(()=>$)),Q.addCommand(Hr(()=>$));const zf=new O(`ui`).description("Removed: the editor UI is served by `ok start`").allowUnknownOption().allowExcessArguments().argument(`[args...]`).action(()=>{console.error("`ok ui` was removed — the editor UI is served by the project server. Run `ok start` instead."),process.exit(1)});Q.addCommand(zf,{hidden:!0}),Q.addCommand(_d()),Q.addCommand(rn(()=>$)),Q.addCommand(Aa(()=>$)),Q.addCommand(_f(()=>$)),Q.addCommand(Go()),Q.addCommand(Mf()),Q.addCommand(sn()),Q.addCommand(js()),Q.addCommand(Da()),Q.addCommand(mo()),Q.addCommand(Ta(Ff)),Q.addCommand(Gs()),Q.addCommand(eo(()=>$)),Q.addCommand(xd(()=>$)),Q.addCommand(Cd(()=>$)),Q.addCommand(Sd(()=>$)),Q.addCommand(Jd()),Q.addCommand(tf()),Q.addHelpText(`after`,`
|
|
97
97
|
Examples:
|
|
98
98
|
ok Launch the desktop app (or start a local server if it isn't installed)
|
|
99
99
|
ok notes.md Open a single markdown file in the editor
|