@inkeep/open-knowledge 0.0.0-dev-20260423193928 → 0.0.0-dev-20260423224129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cli.mjs +8 -8
  2. package/dist/constants-p2mrQUZK.mjs +2 -0
  3. package/dist/index.d.mts +171 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/init-DJzYkC45.mjs +1 -0
  6. package/dist/{init-Cr5zNjLr.mjs → init-DsaVseaZ.mjs} +2 -2
  7. package/dist/init-P1I9tsCc.mjs +1 -0
  8. package/dist/init-RBK7HHVy.mjs +5 -0
  9. package/dist/loader-DzbVFAz5.mjs +1 -0
  10. package/dist/{loader-BjvYg6bR.mjs → loader-lj28Sw6t.mjs} +2 -2
  11. package/dist/paths-CJMOZlvG.mjs +1 -0
  12. package/dist/{paths-Dcbxj9qp.mjs → paths-DreD7ab4.mjs} +2 -2
  13. package/dist/{preview-B7p7jyyl.mjs → preview-B55OlWJc.mjs} +2 -2
  14. package/dist/preview-CfQP5PHw.mjs +1 -0
  15. package/dist/public/assets/{GraphPanel-D2JBM6nD.js → GraphPanel-nbYklZ9C.js} +2 -2
  16. package/dist/public/assets/McpConsentDialogBody-BTLTOjWM.js +1 -0
  17. package/dist/public/assets/SourceEditor-CEqBKP5f.js +3 -0
  18. package/dist/public/assets/button-BuHZQnlF.js +1 -0
  19. package/dist/public/assets/clipboard-ZQ-AEssh.js +36 -0
  20. package/dist/public/assets/dialog-C2kd-BJI.js +45 -0
  21. package/dist/public/assets/{dist-B2YW_ZWG.js → dist-1RA1Ivz5.js} +1 -1
  22. package/dist/public/assets/{dist-k7VFO_3K.js → dist-B90Tbt-G.js} +1 -1
  23. package/dist/public/assets/{dist-CQbn9Fxc.js → dist-BJa-wTjR.js} +1 -1
  24. package/dist/public/assets/{dist-X189qk_S.js → dist-CsuK1sJe.js} +1 -1
  25. package/dist/public/assets/{dist-Dm75HY2n.js → dist-D96Jocj9.js} +1 -1
  26. package/dist/public/assets/{dist-Bx72hMUu.js → dist-DQmXHI9Z.js} +1 -1
  27. package/dist/public/assets/{dist-DVEMi7bH.js → dist-yRCb9u34.js} +1 -1
  28. package/dist/public/assets/index-CGTgnYOo.css +1 -0
  29. package/dist/public/assets/index-DUIfxmm6.js +21 -0
  30. package/dist/public/assets/panel-CnHxXki4.js +240 -0
  31. package/dist/public/assets/toggle-group-BNTPJpXY.js +1 -0
  32. package/dist/public/index.html +11 -9
  33. package/dist/server-lock-BI-SqMWk.mjs +2 -0
  34. package/dist/server-lock-zOHsiWX-.mjs +1 -0
  35. package/dist/src-BFFb00v4.mjs +1 -0
  36. package/dist/src-DHnGx64r.mjs +1 -0
  37. package/dist/{src-skP-DoiW.mjs → src-rqPIkHTi.mjs} +3 -3
  38. package/dist/start-B6-KWyei.mjs +1 -0
  39. package/dist/{start-zmc8Anu_.mjs → start-BufFj0pL.mjs} +2 -2
  40. package/package.json +1 -1
  41. package/dist/constants-oa8rklCf.mjs +0 -2
  42. package/dist/init-1srg7AC9.mjs +0 -5
  43. package/dist/init-B7uATxQD.mjs +0 -1
  44. package/dist/init-DSYBjbGB.mjs +0 -1
  45. package/dist/loader-CVOTHZaY.mjs +0 -1
  46. package/dist/paths-5vJ24bHl.mjs +0 -1
  47. package/dist/preview-CFVO89Px.mjs +0 -1
  48. package/dist/public/assets/SourceEditor-BKyWQ7mW.js +0 -3
  49. package/dist/public/assets/clipboard-CdKkyvy1.js +0 -80
  50. package/dist/public/assets/index-Bfb7OhfE.js +0 -21
  51. package/dist/public/assets/index-DHlHPMwL.css +0 -1
  52. package/dist/public/assets/panel-DTlG8EiB.js +0 -240
  53. package/dist/public/assets/toggle-group-BFNw1DkB.js +0 -1
  54. package/dist/server-lock-B4frNnOB.mjs +0 -2
  55. package/dist/server-lock-CPmOhzSz.mjs +0 -1
  56. package/dist/src-CQRey-Fm.mjs +0 -1
  57. package/dist/src-DB3pnkMU.mjs +0 -1
  58. package/dist/start-CsGsfw3C.mjs +0 -1
  59. /package/dist/public/assets/{go-IODVg4Ok.js → go-C_J4XPHz.js} +0 -0
  60. /package/dist/public/assets/{shell-COsTRxlr.js → shell-Cp2AENBi.js} +0 -0
  61. /package/dist/public/assets/{w3c-keyname-DLDSJn4E.js → w3c-keyname-DGDXsZN5.js} +0 -0
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t}from"./constants-oa8rklCf.mjs";import{O as n,c as r,k as i}from"./src-CQw-HNNM.mjs";import{n as a,t as o}from"./paths-Dcbxj9qp.mjs";import{ct as s,lt as c,ot as l,p as u,st as d,tt as f}from"./src-skP-DoiW.mjs";import{c as p,f as m,r as h}from"./server-lock-B4frNnOB.mjs";import{i as g}from"./init-Cr5zNjLr.mjs";import{t as _}from"./is-object-DaHwJLOe.mjs";import{r as v}from"./init-1srg7AC9.mjs";import{i as y,n as ee,t as b}from"./loader-BjvYg6bR.mjs";import{o as x,s as S}from"./start-zmc8Anu_.mjs";import"./src-CQRey-Fm.mjs";import{Command as C}from"commander";import{appendFileSync as w,closeSync as T,existsSync as E,mkdirSync as D,openSync as te,readFileSync as O,readdirSync as ne,realpathSync as re,statSync as ie,unlinkSync as ae,writeFileSync as oe}from"node:fs";import{homedir as se,hostname as ce}from"node:os";import{basename as le,dirname as ue,isAbsolute as de,join as fe,relative as pe,resolve as k}from"node:path";import{parse as me,stringify as he}from"yaml";import{createOAuthDeviceAuth as ge}from"@octokit/auth-oauth-device";import _e from"@inquirer/password";import{Octokit as ve}from"@octokit/rest";import{fileURLToPath as ye}from"node:url";import{randomUUID as be}from"node:crypto";import{execFileSync as xe,spawn as Se}from"node:child_process";import Ce from"simple-git";import{readFile as we,readdir as Te,stat as Ee}from"node:fs/promises";import{createServer as De,request as Oe}from"node:http";import ke from"picomatch";import{z as A}from"zod";import{McpServer as Ae}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as je}from"@modelcontextprotocol/sdk/server/stdio.js";import{RootsListChangedNotificationSchema as Me}from"@modelcontextprotocol/sdk/types.js";import{AsyncLocalStorage as Ne}from"node:async_hooks";import{Bash as Pe,ReadWriteFs as Fe}from"just-bash";import Ie from"shell-quote";const Le=`open-knowledge`;var Re=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Le,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Le,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Le,e).deletePassword()}catch{}}},ze=class{backend=`file`;authFile;constructor(e){this.authFile=e??fe(se(),`.open-knowledge`,`auth.yml`)}read(){if(!E(this.authFile))return{};try{return me(O(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=ue(this.authFile);E(t)||D(t,{recursive:!0,mode:448}),oe(this.authFile,he(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Be(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Le,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{a as e,i as t}from"./constants-p2mrQUZK.mjs";import{O as n,c as r,k as i}from"./src-CQw-HNNM.mjs";import{n as a,t as o}from"./paths-DreD7ab4.mjs";import{ct as s,lt as c,m as l,nt as u,st as d,ut as f}from"./src-rqPIkHTi.mjs";import{c as p,f as m,r as h}from"./server-lock-BI-SqMWk.mjs";import{i as g}from"./init-DsaVseaZ.mjs";import{t as _}from"./is-object-DaHwJLOe.mjs";import{r as v}from"./init-RBK7HHVy.mjs";import{i as y,n as ee,t as b}from"./loader-lj28Sw6t.mjs";import{o as x,s as S}from"./start-BufFj0pL.mjs";import"./src-BFFb00v4.mjs";import{Command as C}from"commander";import{appendFileSync as w,closeSync as T,existsSync as E,mkdirSync as D,openSync as te,readFileSync as O,readdirSync as ne,realpathSync as re,statSync as ie,unlinkSync as ae,writeFileSync as oe}from"node:fs";import{homedir as se,hostname as ce}from"node:os";import{basename as le,dirname as ue,isAbsolute as de,join as fe,relative as pe,resolve as k}from"node:path";import{parse as me,stringify as he}from"yaml";import{createOAuthDeviceAuth as ge}from"@octokit/auth-oauth-device";import _e from"@inquirer/password";import{Octokit as ve}from"@octokit/rest";import{fileURLToPath as ye}from"node:url";import{randomUUID as be}from"node:crypto";import{execFileSync as xe,spawn as Se}from"node:child_process";import Ce from"simple-git";import{readFile as we,readdir as Te,stat as Ee}from"node:fs/promises";import{createServer as De,request as Oe}from"node:http";import ke from"picomatch";import{z as A}from"zod";import{McpServer as Ae}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as je}from"@modelcontextprotocol/sdk/server/stdio.js";import{RootsListChangedNotificationSchema as Me}from"@modelcontextprotocol/sdk/types.js";import{AsyncLocalStorage as Ne}from"node:async_hooks";import{Bash as Pe,ReadWriteFs as Fe}from"just-bash";import Ie from"shell-quote";const Le=`open-knowledge`;var Re=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Le,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Le,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Le,e).deletePassword()}catch{}}},ze=class{backend=`file`;authFile;constructor(e){this.authFile=e??fe(se(),`.open-knowledge`,`auth.yml`)}read(){if(!E(this.authFile))return{};try{return me(O(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=ue(this.authFile);E(t)||D(t,{recursive:!0,mode:448}),oe(this.authFile,he(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Be(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Le,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new Re}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new ze(e)}}async function Ve(e,t,n){let r=He(await Ue(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function He(e){let t={};for(let n of e.split(`
5
5
  `)){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 Ue(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 We(e){let t=new C(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Ve(process.stdin,process.stdout,t);process.exit(n)}),t}async function Ge(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=ge({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(`@octokit/request`)).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 Ke(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const qe=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Je(e){let t=e.toLowerCase().replace(/:\d+$/,``);qe.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 Ye(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Xe(e,t,n,r=Ge){let i=Ke(n),{host:a,json:o}=e;Je(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?Ye(!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`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?Ye(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Ze(e,t){return new C(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await Xe(n,await t(),e())})}async function Qe(e,t,n){let{host:r,json:i}=e;Je(r);let a=await(n??(()=>_e({message:`Enter PAT:`})))();a||(process.stderr.write(`No token provided
@@ -7,7 +7,7 @@ import{a as e,i as t}from"./constants-oa8rklCf.mjs";import{O as n,c as r,k as i}
7
7
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function $e(e){return new C(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Qe(t,await e())})}async function et(e,t){let{host:n,json:r}=e;Je(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new ve({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function tt(e){return new C(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await et(t,await e())})}async function nt(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function rt(e){return new C(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await nt(t,await e())})}async function it(e,t){let{host:n,json:r}=e;Je(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new ve({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
8
8
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function at(e){return new C(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await it(t,await e())})}function ot(e){let t=new C(`auth`);t.description(`GitHub authentication management`);let n=()=>Be(),r=e??(()=>({}));return t.addCommand(Ze(r,n)),t.addCommand(at(n)),t.addCommand(tt(n)),t.addCommand(rt(n)),t.addCommand($e(n)),t.addCommand(We(n)),t}function st(e,t,n={}){let r=p(e,t);if(!E(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(O(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??ce();return a.hostname===o?(n.isAlive??m)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function ct(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 lt(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.unlink??(e=>ae(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=ct(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 ut(e){return new C(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{lt({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function dt(){try{let e=xe(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function ft(e,t,n={},r=dt){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function pt(e){return e.replace(/:\d+$/,``)}function mt(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:pt(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:pt(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:pt(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const ht=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function gt(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 ht)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function _t(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function vt(e,t,n,r=process.cwd()){let i=mt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?k(r,t.dir):k(r,i.name);if(E(a)&&ne(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Be(),s=await ft(i.hostname,o,{}),c=Ce({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;if(c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
9
9
  `)){let n=gt(e);n&&n.pct!==l&&(l=n.pct,_t(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning… ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
10
- `),!E(k(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-DSYBjbGB.mjs`),import(`./init-B7uATxQD.mjs`)]);await e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function yt(e){return new C(`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).action(async(t,n,r)=>{let i=e();try{let a=await vt(t,{json:r.json,dir:n},i);if(r.json)_t(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CsGsfw3C.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?_t(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const bt=new Ne;var xt=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??be().slice(0,12),this.corrId=be().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{w(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function St(e=`mcp`){return new xt(e)}function Ct(e,t){return bt.run(e,t)}function wt(){return bt.getStore()}const Tt=new Set([`find`,`markdown`,`replace`]),Et=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],Dt=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ot(e){return j(e)&&`requestId`in e}function kt(e,t){if(Tt.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
10
+ `),!E(k(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-P1I9tsCc.mjs`),import(`./init-DJzYkC45.mjs`)]);await e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function yt(e){return new C(`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).action(async(t,n,r)=>{let i=e();try{let a=await vt(t,{json:r.json,dir:n},i);if(r.json)_t(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-B6-KWyei.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?_t(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const bt=new Ne;var xt=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??be().slice(0,12),this.corrId=be().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{w(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function St(e=`mcp`){return new xt(e)}function Ct(e,t){return bt.run(e,t)}function wt(){return bt.getStore()}const Tt=new Set([`find`,`markdown`,`replace`]),Et=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],Dt=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ot(e){return j(e)&&`requestId`in e}function kt(e,t){if(Tt.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
11
11
  `).length};let n=e===`command`?240:120;return t.length<=n?t:{type:`string`,length:t.length,preview:`${t.slice(0,n)}...`}}function At(e,t){if(t===null)return null;if(typeof t==`string`)return kt(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(j(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function jt(e,t){return j(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,At(e,t)])):At(e,t)}function Mt(e){let t={structuredKeys:Object.keys(e).sort()};for(let n of Dt)n in e&&(t[n]=e[n]);for(let n of Et){let r=e[n];Array.isArray(r)&&(t[`${n}Count`]=r.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),j(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),j(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function Nt(e){if(!j(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>j(t)&&typeof t.text==`string`?e+t.text.length:e,0)),j(e.structuredContent)&&Object.assign(t,Mt(e.structuredContent)),t}function Pt(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{},...e.label?{label:e.label}:{}}}function Ft(e){let t=e.at(-1);return Ot(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function It(e,t,n){let r=n.logger;return r?async(...i)=>{let a=r.child(),o=Date.now(),{toolArgs:s,extra:c}=Ft(i);a.info(`tool start`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},...c?.sessionId?{transportSessionId:c.sessionId}:{},...n.identityRef?.current?{agent:Pt(n.identityRef.current)}:{},...s===void 0?{}:{args:jt(e,s)}});try{let n=await Ct(a,async()=>await t(...i));return a.info(`tool finish`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o,result:Nt(n)}),n}catch(t){throw a.error(`tool error`,t,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o}),t}}:t}function Lt(e,t){if(!t.logger)return e;let n=e.tool.bind(e),r=Object.create(e);return r.tool=((...e)=>{let r=String(e[0]),i=e.at(-1);if(typeof i!=`function`)return n(...e);let a=[...e];return a[a.length-1]=It(r,i,t),n(...a)}),r}const M="Absolute host path to resolve the request against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.",Rt=A.string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function N(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function P(e,t,n){return{content:[{type:`text`,text:e}],structuredContent:t,...n?{isError:!0}:{}}}const F="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.";async function zt(e,t){return typeof e==`function`?await e(t):e}async function Bt(e,t){return typeof e==`function`?await e(t):e}async function I(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await Bt(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function L(e,t,n,r){let i=await I(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await zt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function z(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function B(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function Vt(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
12
12
 
13
13
  Topic: ${e}
@@ -151,15 +151,15 @@ superseded_by: <path-to-new-canonical-article>.md
151
151
  - **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
152
152
 
153
153
  Full convention: read \`${n}/AGENTS.md\`.`}const Ht=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
154
- `);function Ut(e,t){e.tool(`consolidate`,Ht,{topic:A.string().describe(`The topic to consolidate into a canonical article`),cwd:A.string().optional().describe(M)},async e=>{let n=await I(t.resolveCwd,t.config,e.cwd);return n.ok?P(Vt(e.topic,n.config.content.dir),{previewUrl:null}):N(`Error: ${n.error}`,!0)})}function Wt(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Gt(e){return e.endsWith(`/`)?e.slice(0,-1):e}function Kt(e){try{return new URL(e),!0}catch{return!1}}async function V(e,t,n){let r=n??await t.resolveCwd(),i=await Bt(t.config,r),s=o(i,r);return U(e,{config:i,lockDir:a(s),contentDir:s})}function qt(e){try{let t=f(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function H(e,t){let n=t??await e.resolveCwd(),r=await Bt(e.config,n),i=o(r,n),s={config:r,lockDir:a(i),contentDir:i};return{resolve:e=>U(e,s),ui:qt(s)}}function Jt(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function U(e,t){let n=`/#/${Wt(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=re(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&Kt(r))return{url:`${Gt(r)}${n}`,source:`env`};try{let e=f(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&Kt(i)?{url:`${Gt(i)}${n}`,source:`config`}:null}const Yt=["**IMPORTANT: Before calling this tool, you MUST first call `get_preview_url` and navigate to the returned URL in your preview browser. If `get_preview_url` returns null, start the server first (`open-knowledge start` or `preview_start`), then call `get_preview_url` again. Do NOT call this tool without the preview open. NEVER manually construct the URL.**",``,`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
154
+ `);function Ut(e,t){e.tool(`consolidate`,Ht,{topic:A.string().describe(`The topic to consolidate into a canonical article`),cwd:A.string().optional().describe(M)},async e=>{let n=await I(t.resolveCwd,t.config,e.cwd);return n.ok?P(Vt(e.topic,n.config.content.dir),{previewUrl:null}):N(`Error: ${n.error}`,!0)})}function Wt(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Gt(e){return e.endsWith(`/`)?e.slice(0,-1):e}function Kt(e){try{return new URL(e),!0}catch{return!1}}async function V(e,t,n){let r=n??await t.resolveCwd(),i=await Bt(t.config,r),s=o(i,r);return U(e,{config:i,lockDir:a(s),contentDir:s})}function qt(e){try{let t=u(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function H(e,t){let n=t??await e.resolveCwd(),r=await Bt(e.config,n),i=o(r,n),s={config:r,lockDir:a(i),contentDir:i};return{resolve:e=>U(e,s),ui:qt(s)}}function Jt(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function U(e,t){let n=`/#/${Wt(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=re(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&Kt(r))return{url:`${Gt(r)}${n}`,source:`env`};try{let e=u(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&Kt(i)?{url:`${Gt(i)}${n}`,source:`config`}:null}const Yt=["**IMPORTANT: Before calling this tool, you MUST first call `get_preview_url` and navigate to the returned URL in your preview browser. If `get_preview_url` returns null, start the server first (`open-knowledge start` or `preview_start`), then call `get_preview_url` again. Do NOT call this tool without the preview open. NEVER manually construct the URL.**",``,`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
155
155
  `);function Xt(e,t){e.tool(`edit_document`,Yt,{docName:A.string().describe(`Document name to edit`),find:A.string().describe(`Text to find (exact match)`),replace:A.string().describe(`Replacement text`),offset:A.number().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:Rt,cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:s}=n;if(!s)return N(F,!0);let c=R(e.docName);if(!c.ok)return N(c.error,!0);let l=t.identityRef?.current,u=await B(s,`/api/agent-patch`,{docName:c.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...l?{agentId:l.connectionId,agentName:l.displayName,clientName:l.clientInfo?.name,colorSeed:l.colorSeed}:{}});if(!u.ok)return N(`Error: ${u.error}`,!0);let d=a(o(i,r)),f=U(c.docName,{config:i,lockDir:d}),p=(typeof u.subscriberCount==`number`?u.subscriberCount:void 0)===0,m=u.summary&&typeof u.summary==`object`?u.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];f&&g.push(`Preview: ${f.url}`),p&&g.push(f?`Warning: no preview is currently attached to "${c.docName}". Open ${f.url} to watch future edits live.`:`Warning: no preview is currently attached to "${c.docName}".`),h&&g.push(h);let _=g.join(`
156
156
  `);if(!f&&!p&&!m)return N(_);let v={};return f&&(v.previewUrl=f.url,v.previewUrlSource=f.source),p&&(v.warning={message:`No preview attached to ${c.docName}.`,previewUrl:f?.url??null}),m&&(v.summary=m),P(_,v)})}const Zt=new Set([`cat`,`ls`,`grep`,`find`]),Qt=/\b[\w./-]+\.(md|mdx)\b/g;function W(e){return/\.(md|mdx)$/.test(e)}function G(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function K(e){return e.args.slice(1)}function q(e){return e.filter(e=>!e.startsWith(`-`))}function $t(e){return q(K(e)).filter(W)}function en(e,t){let n=q(K(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?G(r):``,a=[];i&&a.push(i);for(let t of e.split(`
157
157
  `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!W(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function tn(e){let t=[];for(let n of e.split(`
158
158
  `)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=G(n.slice(0,e));W(r)&&t.push(r)}return t}function nn(e){let t=[];for(let n of e.split(`
159
159
  `)){let e=G(n);e&&W(e)&&t.push(e)}return t}function rn(e){return q(K(e)).filter(W)}function an(e){return q(K(e)).length>0}function on(e){let t=[],n=e.matchAll(Qt);for(let e of n)t.push(G(e[0]));return t}function sn(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(Zt.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&an(r)){n=r;break}}let r;if(!n)r=on(e);else{switch(n.command){case`cat`:r=$t(n);break;case`ls`:r=en(e,n);break;case`grep`:r=tn(e);break;case`find`:r=nn(e);break;case`head`:case`tail`:r=rn(n);break;default:r=on(e)}r.length===0&&(r=on(e))}let i=new Set,a=[];for(let e of r){let t=G(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}function J(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const cn=16*1024*1024;var ln=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function un(e){if(!de(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Pe({cwd:`/`,fs:new Fe({root:k(e),allowSymlinks:!1})})}async function dn(e,t){let n=await e.exec(t);if(n.stdout.length>cn)throw new ln(cn,n.stdout.length,{stdout:n.stdout.slice(0,cn),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function fn(e){return e.startsWith(`**/`)?e.slice(3):e}async function pn(e,t,n={}){let r=un(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${J(fn(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${J(fn(e))}`),i.push(`--exclude-dir=${J(fn(e))}`);let a=n.paths?.length?n.paths.map(J):[`.`],o=`grep ${i.join(` `)} ${J(e)} ${a.join(` `)}`,s;try{s=await dn(r,o)}catch(e){if(e instanceof ln)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
160
160
  `)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const mn=new Set([`.git`,n,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function hn(e){let t=k(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await Te(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&mn.has(s.name))continue;let o=k(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await Ee(o);n.set(pe(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function gn(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}const _n=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,n,`.claude`];function vn(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const yn=[{command:`grep`,applies:e=>e.slice(1).some(vn),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function bn(e){return e.map(e=>{let t=yn.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(_n),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function xn(e){return e.map(e=>e.args.map(J).join(` `)).join(` | `)}const Sn=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),Cn=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),wn=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),Tn=new Set([`-o`,`--output-file`,`--output`]),En=[`-o=`,`--output-file=`,`--output=`],Dn=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),On=/[`]|\$\(|\$\{|\$'/;function kn(e){return typeof e==`object`&&!!e&&`op`in e}function An(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return Cn.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:wn.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function jn(e){let t=[];for(let n of e){if(typeof n==`string`){if(On.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!kn(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:An(n)}}return{args:t}}function Mn(e){if(!Sn.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(Tn.has(t)||En.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&Dn.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function Nn(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=Ie.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(kn(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=jn(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=Mn(n);if(r)return{error:r};a.push(n)}return{stages:a}}const Pn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Fn(e,t){let n=e.match(Pn);if(!n)return null;try{let e=me(n[1]);if(_(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}const In=new WeakMap;function Ln(e){let t=In.get(e);if(t)return t;let n=e.map(e=>ke(e.match,{dot:!0}));return In.set(e,n),n}function Rn(e,t){if(e.length===0)return{};let n=Ln(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function zn(e){try{return ie(k(e,`.git`)).isDirectory()}catch{return!1}}function Bn(e){return Ce({baseDir:k(e),timeout:{block:5e3}})}async function Vn(e,t,n=5){if(!zn(e))return{commits:[],source:`git-absent`};let r=Bn(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
161
- `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const Hn=5e3;async function Un(e){try{let t=(await Ce({baseDir:e,timeout:{block:Hn}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Wn(e,t){return Ce({baseDir:t,timeout:{block:Hn}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Gn(e,t){let n=d(t);return e.startsWith(n)?e.slice(n.length):e}async function Kn(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=Gn(t,r),l=s(o),u=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,s=``,d=``]=t.split(`\0`),f=n.trim();f.length===40&&u.push({hash:f,date:i,writerName:a,message:s,contributors:c(d),writerId:o,isAgent:l.isAgent,writerClassification:l.classification,branch:r})}return u}async function qn(e,t,n=5){let r=l(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await Un(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Wn(r,k(e)),o=``;try{o=await a.raw(`for-each-ref`,d(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
162
- `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>Kn(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const Jn=1e3,Yn=new Set([`.git`,n,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Xn=/\.(md|mdx)$/i,Zn=A.object({title:A.string().optional(),description:A.string().optional(),tags:A.array(A.string()).default([])});function Qn(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function $n(e){try{let t=Fn(await we(e,`utf-8`),Zn);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function er(e,t){if(!e)return null;let n=await z(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function tr(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await z(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function nr(e,t){if(!e)return null;let n=await z(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function rr(e,t,n){let r=t??[],i=r.length===0?{}:Rn(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function ir(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=k(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=$n(i);if(!o){let e=rr(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,er(t.serverUrl,Qn(r)).catch(()=>null),nr(t.serverUrl,Qn(r)).catch(()=>null),qn(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),Vn(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=rr(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function ar(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=Jn){n.truncated=!0;break}let a;try{a=await Te(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=Jn){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Yn.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Xn.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Ee(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:pe(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function or(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await ar(k(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await $n(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??le(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=Rn(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const sr=50*1024,cr=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,lr=[`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
161
+ `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const Hn=5e3;async function Un(e){try{let t=(await Ce({baseDir:e,timeout:{block:Hn}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Wn(e,t){return Ce({baseDir:t,timeout:{block:Hn}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Gn(e,t){let n=s(t);return e.startsWith(n)?e.slice(n.length):e}async function Kn(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=Gn(t,r),s=c(o),l=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,c=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&l.push({hash:d,date:i,writerName:a,message:c,contributors:f(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return l}async function qn(e,t,n=5){let r=d(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await Un(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Wn(r,k(e)),o=``;try{o=await a.raw(`for-each-ref`,s(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let c=o.split(`
162
+ `).map(e=>e.trim()).filter(Boolean);return c.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(c.map(e=>Kn(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const Jn=1e3,Yn=new Set([`.git`,n,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Xn=/\.(md|mdx)$/i,Zn=A.object({title:A.string().optional(),description:A.string().optional(),tags:A.array(A.string()).default([])});function Qn(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function $n(e){try{let t=Fn(await we(e,`utf-8`),Zn);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function er(e,t){if(!e)return null;let n=await z(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function tr(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await z(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function nr(e,t){if(!e)return null;let n=await z(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function rr(e,t,n){let r=t??[],i=r.length===0?{}:Rn(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function ir(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=k(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=$n(i);if(!o){let e=rr(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,er(t.serverUrl,Qn(r)).catch(()=>null),nr(t.serverUrl,Qn(r)).catch(()=>null),qn(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),Vn(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=rr(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function ar(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=Jn){n.truncated=!0;break}let a;try{a=await Te(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=Jn){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Yn.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Xn.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Ee(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:pe(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function or(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await ar(k(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await $n(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??le(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=Rn(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const sr=50*1024,cr=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,lr=[`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
163
163
  `);function ur(e){let t=e.split(`
164
164
  `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=sr)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>sr)break;a++}let o=t.slice(0,a).join(`
165
165
  `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function dr(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||cr.test(e)&&t.push(e);return t}function fr(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function pr(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=fr(n.args),i=t.split(`
@@ -172,7 +172,7 @@ Full convention: read \`${n}/AGENTS.md\`.`}const Ht=[`Promote research into a ca
172
172
  `);function Ar(e,t){e.tool(`get_history`,kr,{docName:A.string().describe(`Document name to query history for`),branch:A.string().optional().describe(`Branch name (default: current branch)`),limit:A.number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:A.number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:A.enum([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:A.string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:A.string().optional().describe(`Exclude entries by this author name or email`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=R(e.docName);if(!a.ok)return N(a.error,!0);let o=new URLSearchParams;o.set(`docName`,a.docName),e.branch&&o.set(`branch`,e.branch),e.limit!=null&&o.set(`limit`,String(e.limit)),e.offset!=null&&o.set(`offset`,String(e.offset)),e.type&&o.set(`type`,e.type),e.author&&o.set(`author`,e.author),e.excludeAuthor&&o.set(`excludeAuthor`,e.excludeAuthor);let s=await z(i,`/api/history?${o.toString()}`);if(!s.ok)return N(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=await V(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return P(JSON.stringify(l,null,2),{...l,previewUrl:u?.url??null,...u?{previewUrlSource:u.source}:{}})})}const jr=[`[Requires: Hocuspocus server] Find the most-linked pages in the knowledge graph.`,`Returns hub pages ordered by inbound link count as JSON.`,``,`**Parameters:**`,"- `limit` (optional) — Maximum number of hubs to return (default 20)"].join(`
173
173
  `);function Mr(e,t){e.tool(`get_hubs`,jr,{limit:A.number().int().positive().optional().describe(`Maximum number of hubs to return`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=await z(i,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!a.ok)return N(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await H(t,r),d=(c.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,hubs:d,ui:u,cwd:r};return P(JSON.stringify(f,null,2),f)})}const Nr=[`[Requires: Hocuspocus server] Find disconnected pages in the knowledge graph.`,`Returns orphaned pages as JSON.`,``,`**Parameters:**`,"- `mode` (optional) — Orphan lens: `incoming`, `outgoing`, or `both` (default `both`)"].join(`
174
174
  `);function Pr(e,t){e.tool(`get_orphans`,Nr,{mode:A.enum(i).optional().describe(`Filter which type of graph disconnection to surface`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=await z(i,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!a.ok)return N(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await H(t,r),d=(c.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,orphans:d,ui:u,cwd:r};return P(JSON.stringify(f,null,2),f)})}const Fr=["Return a browser URL for the given wiki docName. Agents should call this IMMEDIATELY BEFORE `write_document` / `edit_document` so they can navigate the preview browser to the doc first and watch the CRDT edit land live.",``,`**Parameters:**`,"- `docName` — Wiki doc name, typically without extension.",``,"Returns `{ previewUrl, previewUrlSource }` (source: `env` / `lock` / `config`). When no source is configured, returns `{ previewUrl: null }` and the agent may proceed without navigation."].join(`
175
- `);async function Ir(e,t){let n=R(e.docName);if(!n.ok)return{ok:!1,error:n.error};let r=n.docName,i=await I(t.resolveCwd,t.config,e.cwd);if(!i.ok)return i;let{cwd:s,config:c}=i,l=o(c,s),d;try{d=u({projectDir:s,contentDir:l,includePatterns:c.content.include,excludePatterns:c.content.exclude})}catch(e){return{ok:!1,error:`Cannot evaluate content filter: ${e instanceof Error?e.message:String(e)}`}}if(![`${r}.md`,`${r}.mdx`].some(e=>!d.isExcluded(e)))return{ok:!1,error:`Error: docName "${r}" is not inside content.include globs (${c.content.include.join(`, `)}). This tool only returns URLs for docs that match those globs.`};let f=U(r,{config:c,lockDir:a(l),contentDir:l});return f?{ok:!0,result:{previewUrl:f.url,previewUrlSource:f.source},text:`Preview URL for "${r}" (source: ${f.source}):\n${f.url}`}:{ok:!0,result:{previewUrl:null},text:`No preview URL resolvable for "${r}". The server is likely not running yet. Start it with \`open-knowledge start\` (or \`preview_start\`), then **call \`get_preview_url\` again** — the server writes a lock file that this tool reads to resolve the URL. NEVER guess or manually construct the preview URL. Alternatively, set \`OPEN_KNOWLEDGE_PREVIEW_BASE_URL\` or add \`preview.baseUrl\` to .open-knowledge/config.yml.`}}function Lr(e,t){e.tool(`get_preview_url`,Fr,{docName:A.string().min(1),cwd:A.string().optional().describe(M)},async e=>{let n=await Ir(e,t);return n.ok?P(n.text,n.result):N(n.error,!0)})}function Rr(e,t){return`Capture this external source into the project knowledge base as raw reference material. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
175
+ `);async function Ir(e,t){let n=R(e.docName);if(!n.ok)return{ok:!1,error:n.error};let r=n.docName,i=await I(t.resolveCwd,t.config,e.cwd);if(!i.ok)return i;let{cwd:s,config:c}=i,u=o(c,s),d;try{d=l({projectDir:s,contentDir:u,includePatterns:c.content.include,excludePatterns:c.content.exclude})}catch(e){return{ok:!1,error:`Cannot evaluate content filter: ${e instanceof Error?e.message:String(e)}`}}if(![`${r}.md`,`${r}.mdx`].some(e=>!d.isExcluded(e)))return{ok:!1,error:`Error: docName "${r}" is not inside content.include globs (${c.content.include.join(`, `)}). This tool only returns URLs for docs that match those globs.`};let f=U(r,{config:c,lockDir:a(u),contentDir:u});return f?{ok:!0,result:{previewUrl:f.url,previewUrlSource:f.source},text:`Preview URL for "${r}" (source: ${f.source}):\n${f.url}`}:{ok:!0,result:{previewUrl:null},text:`No preview URL resolvable for "${r}". The server is likely not running yet. Start it with \`open-knowledge start\` (or \`preview_start\`), then **call \`get_preview_url\` again** — the server writes a lock file that this tool reads to resolve the URL. NEVER guess or manually construct the preview URL. Alternatively, set \`OPEN_KNOWLEDGE_PREVIEW_BASE_URL\` or add \`preview.baseUrl\` to .open-knowledge/config.yml.`}}function Lr(e,t){e.tool(`get_preview_url`,Fr,{docName:A.string().min(1),cwd:A.string().optional().describe(M)},async e=>{let n=await Ir(e,t);return n.ok?P(n.text,n.result):N(n.error,!0)})}function Rr(e,t){return`Capture this external source into the project knowledge base as raw reference material. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
176
176
 
177
177
  Source: ${e}
178
178
 
@@ -593,6 +593,6 @@ Folder metadata lives in \`config.yml\`, **not** in content files — this is in
593
593
  ${Object.entries(xi).map(([e,t])=>`### \`${e}\`\n${t}`).join(`
594
594
 
595
595
  `)}
596
- `}async function Oi(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function ki(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=St(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await Oi(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Ae({name:t,version:e},{instructions:Di(o,{dynamicConfig:typeof a==`function`&&!s})}),l=Ti({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=Ei({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Me,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=be(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},Si(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new je;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-UJIeMtkM.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function Ai(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function ji(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Mi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??Se,a=e.readErrorLog??(e=>E(e)?O(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>te(e,`w`)),s=e.closeFd??(e=>T(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=ji({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};E(e.lockDir)||D(e.lockDir,{recursive:!0});let d=fe(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=S();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),ee=(c/1e3).toFixed(c%1e3==0?0:2),b=p?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${ee}s.${x}${y?` stderr:\n${y}`:``}`)}function Ni(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Mi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function Pi(e){return new C(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=b({startupCwd:r,startupConfig:n}),a=Ai(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Ni({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await ki({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fi(e){return new C(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CFVO89Px.mjs`),r=e(),i=process.cwd(),a=o(r,i),s;try{s=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(s,i)}\n`),s.totalCount===0&&s.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ii(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(a(o(t,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`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}Z(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 s=Ce({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await s.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await s.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
597
- `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Li(e){return new C(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Ri(e){return new C(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 zi(e){return new C(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Bi(e,t){return{server:Vi(`server`,e),ui:Vi(`ui`,t)}}function Vi(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 Hi(e){return`${Ui(e.server)}\n${Ui(e.ui)}`}function Ui(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\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Wi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Hi(r)),r}function Gi(e){return new C(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{Wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ki(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function qi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ki(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Ji(e){return new C(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{qi({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Yi=1e4,Xi=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Zi(e){let t=e.upstreamTimeoutMs??Yi,n=De((n,r)=>{$i(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function Qi(e,t,n){$i(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Yi)}function $i(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Xi)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Oe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Xi)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function ea(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ta(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:i}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-DB3pnkMU.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-5vJ24bHl.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[i(m,`public`),i(m,`../../app/dist`),i(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Qi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):na(t)});return}if(g){g(e,t);return}na(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(ee);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let C=S;v=C,c(p,C);let w=e.scheduler??r,T=e.safetyNetMs??432e5,E=null,D=!1,te=!1,O=()=>{D||(D=!0,E!==null&&(w.clearTimeout(E),E=null))},ne=()=>{if(O(),!te){te=!0;try{s(p)}catch{}}},re=()=>{D||T<=0||(E!==null&&(w.clearTimeout(E),E=null),E=w.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}ne()},T))},ie=()=>{D||T<=0||re()};return y=ie,re(),{httpServers:x,port:C,release:ne,detachSafetyNet:O,nudgeSafetyNet:ie}}function na(e){e.writeHead(404),e.end(`Not found`)}function ra(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function ia(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-DB3pnkMU.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Zi({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function aa(e){return new C(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-xJqYhQcY.mjs`),{UiLockCollisionError:r}=await import(`./src-DB3pnkMU.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-5vJ24bHl.mjs`),o=e(),s=t.host,c;try{c=ra(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ta({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};ea(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await ia({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}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);const Q=new C;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ee(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const oa=x(()=>$);Q.addCommand(oa,{isDefault:!0});const sa=Pi(()=>$);Q.addCommand(sa),Q.addCommand(v());const ca=Fi(()=>$);Q.addCommand(ca);const la=aa(()=>$);Q.addCommand(la),Q.addCommand(Ji(()=>$)),Q.addCommand(ut(()=>$)),Q.addCommand(Gi(()=>$)),Q.addCommand(ot(()=>$)),Q.addCommand(yt(()=>$)),Q.addCommand(Li(()=>$)),Q.addCommand(zi(()=>$)),Q.addCommand(Ri(()=>$)),await Q.parseAsync();export{};
596
+ `}async function Oi(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function ki(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=St(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await Oi(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Ae({name:t,version:e},{instructions:Di(o,{dynamicConfig:typeof a==`function`&&!s})}),l=Ti({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=Ei({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Me,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=be(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},Si(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new je;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-UJIeMtkM.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function Ai(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function ji(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Mi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??Se,a=e.readErrorLog??(e=>E(e)?O(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>te(e,`w`)),s=e.closeFd??(e=>T(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=ji({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};E(e.lockDir)||D(e.lockDir,{recursive:!0});let d=fe(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=S();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),ee=(c/1e3).toFixed(c%1e3==0?0:2),b=p?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${ee}s.${x}${y?` stderr:\n${y}`:``}`)}function Ni(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Mi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function Pi(e){return new C(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=b({startupCwd:r,startupConfig:n}),a=Ai(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Ni({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await ki({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fi(e){return new C(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CfQP5PHw.mjs`),r=e(),i=process.cwd(),a=o(r,i),s;try{s=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(s,i)}\n`),s.totalCount===0&&s.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ii(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(a(o(t,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`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}Z(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 s=Ce({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await s.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await s.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
597
+ `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Li(e){return new C(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Ri(e){return new C(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 zi(e){return new C(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Bi(e,t){return{server:Vi(`server`,e),ui:Vi(`ui`,t)}}function Vi(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 Hi(e){return`${Ui(e.server)}\n${Ui(e.ui)}`}function Ui(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\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Wi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Hi(r)),r}function Gi(e){return new C(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{Wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ki(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function qi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ki(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Ji(e){return new C(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{qi({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Yi=1e4,Xi=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Zi(e){let t=e.upstreamTimeoutMs??Yi,n=De((n,r)=>{$i(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function Qi(e,t,n){$i(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Yi)}function $i(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Xi)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Oe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Xi)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function ea(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ta(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:i}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-DHnGx64r.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-CJMOZlvG.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[i(m,`public`),i(m,`../../app/dist`),i(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Qi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):na(t)});return}if(g){g(e,t);return}na(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(ee);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let C=S;v=C,c(p,C);let w=e.scheduler??r,T=e.safetyNetMs??432e5,E=null,D=!1,te=!1,O=()=>{D||(D=!0,E!==null&&(w.clearTimeout(E),E=null))},ne=()=>{if(O(),!te){te=!0;try{s(p)}catch{}}},re=()=>{D||T<=0||(E!==null&&(w.clearTimeout(E),E=null),E=w.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}ne()},T))},ie=()=>{D||T<=0||re()};return y=ie,re(),{httpServers:x,port:C,release:ne,detachSafetyNet:O,nudgeSafetyNet:ie}}function na(e){e.writeHead(404),e.end(`Not found`)}function ra(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function ia(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-DHnGx64r.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Zi({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function aa(e){return new C(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-xJqYhQcY.mjs`),{UiLockCollisionError:r}=await import(`./src-DHnGx64r.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-CJMOZlvG.mjs`),o=e(),s=t.host,c;try{c=ra(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ta({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};ea(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await ia({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}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);const Q=new C;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ee(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const oa=x(()=>$);Q.addCommand(oa,{isDefault:!0});const sa=Pi(()=>$);Q.addCommand(sa),Q.addCommand(v());const ca=Fi(()=>$);Q.addCommand(ca);const la=aa(()=>$);Q.addCommand(la),Q.addCommand(Ji(()=>$)),Q.addCommand(ut(()=>$)),Q.addCommand(Gi(()=>$)),Q.addCommand(ot(()=>$)),Q.addCommand(yt(()=>$)),Q.addCommand(Li(()=>$)),Q.addCommand(zi(()=>$)),Q.addCommand(Ri(()=>$)),await Q.parseAsync();export{};
598
598
  //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./src-CQw-HNNM.mjs";var e=`0.0.0-dev-20260423224129`;const t=`AGENTS.md`,n=`config.yml`,r=`cache`,i=e,a=`open-knowledge`;export{i as a,a as i,r as n,n as r,t};
2
+ //# sourceMappingURL=constants-p2mrQUZK.mjs.map
package/dist/index.d.mts CHANGED
@@ -1,5 +1,175 @@
1
+ import { Command } from "commander";
1
2
  import { z } from "zod";
2
3
 
4
+ //#region src/commands/editors.d.ts
5
+ type EditorId = 'claude' | 'claude-desktop' | 'cursor' | 'vscode' | 'windsurf' | 'codex';
6
+ declare const ALL_EDITOR_IDS: EditorId[];
7
+ type McpInstallMode = 'published' | 'dev';
8
+ interface McpInstallOptions {
9
+ mode?: McpInstallMode;
10
+ cliEntryPath?: string;
11
+ /**
12
+ * Absolute path to a CLI binary that spawns the Open Knowledge MCP server
13
+ * directly (e.g. the Electron-bundled `ok.sh` wrapper, or the `/usr/local/bin/ok`
14
+ * symlink when M6a is installed). When set, the managed entry is
15
+ * `{ command: cliPath, args: ['mcp'] }` — bypasses `npx` entirely.
16
+ *
17
+ * Highest-precedence branch of `buildManagedServerEntry`: takes effect even
18
+ * when `mode === 'dev'` is also set. Intended for Electron main's first-launch
19
+ * MCP wiring (M6b / D-M6-R9); the CLI `ok init` path never sets this.
20
+ */
21
+ cliPath?: string;
22
+ /**
23
+ * Skip `writeEditorMcpConfig`'s `isEditorTargetAvailable` check. Default
24
+ * `ok init` behavior (main branch PR #282) rejects writes for editors
25
+ * whose config dir doesn't exist — reasonable when the default editor list
26
+ * is being fanned out without user intent. M6b's consent dialog shows
27
+ * every editor with a checkbox and the user explicitly toggles; their
28
+ * click IS the consent, so the availability check would silently drop
29
+ * the selection. `writeUserMcpConfigs` (the M6b entry point) sets this
30
+ * to `true`; terminal-invoked `ok init` never sets it.
31
+ */
32
+ skipAvailabilityCheck?: boolean;
33
+ }
34
+ interface EditorMcpTarget {
35
+ id: EditorId;
36
+ /** Human-friendly name for CLI output. */
37
+ label: string;
38
+ /** Resolve the absolute path to the MCP config file. */
39
+ configPath: (cwd: string, home?: string) => string;
40
+ /** On-disk config format for this editor. */
41
+ format: 'json' | 'toml';
42
+ /** Top-level key that holds the server map. */
43
+ topLevelKey: 'mcpServers' | 'servers' | 'mcp_servers';
44
+ /** Config key used for this project's MCP server entry. */
45
+ serverName: (cwd: string) => string;
46
+ /** Build the server entry object for this editor. */
47
+ buildEntry: (cwd: string, options?: McpInstallOptions) => Record<string, unknown>;
48
+ /** True when the managed MCP fields already match the target entry. */
49
+ isCompatible: (existing: Record<string, unknown>, cwd: string, options?: McpInstallOptions) => boolean;
50
+ /** Merge only the managed MCP fields into an existing entry. */
51
+ mergeManagedFields: (existing: Record<string, unknown>, cwd: string, options?: McpInstallOptions) => Record<string, unknown>;
52
+ /** Whether the config is project-local or user-global. */
53
+ scope: 'project' | 'global';
54
+ /** Filesystem path whose existence implies the editor is installed. */
55
+ detectPath?: (cwd: string, home?: string) => string;
56
+ /** Legacy project-local MCP config path from pre-global installs, if any. */
57
+ legacyProjectConfigPath?: (cwd: string) => string;
58
+ /**
59
+ * Project-local agent instruction file to inject the Open Knowledge section
60
+ * into, if any. Claude reads CLAUDE.md; every other editor picks up the
61
+ * tool-agnostic root AGENTS.md which `open-knowledge init` always writes.
62
+ * Only declared for editors that can't read AGENTS.md directly.
63
+ */
64
+ instructionsPath?: (cwd: string) => string;
65
+ }
66
+ declare const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget>;
67
+ //#endregion
68
+ //#region src/commands/init.d.ts
69
+ interface EditorMcpResult {
70
+ editorId: EditorId;
71
+ label: string;
72
+ action: 'written' | 'overwritten' | 'skipped-missing' | 'skipped-flag' | 'failed';
73
+ configPath: string;
74
+ serverName: string;
75
+ error?: string;
76
+ }
77
+ /**
78
+ * Per-editor MCP config writer. Exported (US-006) so `@inkeep/open-knowledge`
79
+ * consumers — specifically Electron main's M6b first-launch consent flow via
80
+ * `writeUserMcpConfigs` — can invoke the same write logic that the terminal-
81
+ * origin `ok init` command uses. The `installOptions.skipAvailabilityCheck`
82
+ * flag distinguishes the two call sites: `ok init` enforces
83
+ * `isEditorTargetAvailable` so users don't get empty config dirs for editors
84
+ * they haven't installed; the M6b consent flow bypasses the check because
85
+ * the user explicitly toggled the editor checkbox in the dialog.
86
+ */
87
+ declare function writeEditorMcpConfig(target: EditorMcpTarget, cwd: string, installOptions: McpInstallOptions, home?: string): EditorMcpResult;
88
+ interface UserMcpConfigsOptions {
89
+ /**
90
+ * Editors whose MCP config to write. Caller (mcp-wiring.ts confirmHandler)
91
+ * is responsible for filtering out editors whose existing entry is a
92
+ * customized shape that should be preserved — those are classified via
93
+ * `readExistingMcpEntry` + `computeForce` and excluded from this array
94
+ * BEFORE the call. This function unconditionally overwrites every editor
95
+ * it receives (aligning with main's `writeEditorMcpConfig` always-rewrite
96
+ * semantic from PR #282 / "installs stay aligned with current defaults").
97
+ */
98
+ editors: EditorId[];
99
+ /**
100
+ * Absolute path to the MCP-spawning CLI binary. Written into every editor's
101
+ * entry as `{ command: cliPath, args: ['mcp'] }`. When unset, falls back to
102
+ * the canonical `{command:'npx', args:['@inkeep/open-knowledge','mcp']}` shape.
103
+ */
104
+ cliPath?: string;
105
+ /** Override `$HOME` for resolving user-scoped config paths (test hook). */
106
+ home?: string;
107
+ }
108
+ /**
109
+ * Write MCP config entries for a set of editors without any of `runInit`'s
110
+ * project-scoped side effects.
111
+ *
112
+ * Specifically does NOT run:
113
+ * - `ensureProjectGit` — would `git init` wherever `cwd` is (packaged Electron
114
+ * apps have `process.cwd() === '/'` by default)
115
+ * - `initContent` — scaffolds `.open-knowledge/` in a project
116
+ * - `scaffoldLaunchJson` — writes `.claude/launch.json`
117
+ * - `upsertRootInstructions` — mutates `AGENTS.md` / `CLAUDE.md`
118
+ * - `collectLegacyProjectConfig` — scans for `.mcp.json` / `.cursor/mcp.json`
119
+ *
120
+ * Per D-M6-R8, this is the entry point Electron main's first-launch MCP
121
+ * consent flow calls after the user clicks Add. The terminal-invoked `ok init`
122
+ * path still uses `runInit` and never sets `cliPath`, so backward compatibility
123
+ * of the `{command:'npx',...}` shape is preserved.
124
+ *
125
+ * Bypasses `isEditorTargetAvailable` via `skipAvailabilityCheck: true` — the
126
+ * user explicitly toggled the editor checkbox; their click IS the consent,
127
+ * so skip-on-missing would silently drop their selection.
128
+ */
129
+ declare function writeUserMcpConfigs(opts: UserMcpConfigsOptions): Promise<EditorMcpResult[]>;
130
+ /**
131
+ * Read a single editor's existing MCP server entry for use with
132
+ * `computeForce`-style classification (M6b). Reads the user-scoped config
133
+ * (format-aware — JSON or TOML), looks up `config[topLevelKey][serverName]`,
134
+ * and returns it as a plain object. Returns `null` when the config file is
135
+ * absent, unreadable, unparseable, or has no entry for this editor's
136
+ * server name.
137
+ *
138
+ * **Never-throws contract (load-bearing — Pass 0 Major #13):** the M6b
139
+ * first-launch consent flow MUST be able to classify every selected editor
140
+ * without aborting on one malformed config. A corrupt user config (e.g.,
141
+ * stale `~/.codex/config.toml` from a half-completed third-party edit) on
142
+ * ANY selected editor would otherwise crash `confirmHandler`, leave the
143
+ * marker absent, and create an infinite dialog re-fire loop on the user's
144
+ * machine. Every reachable failure path here returns `null`:
145
+ * - configPath() throws → null (platform-mismatched target, e.g.
146
+ * Claude Desktop on Linux)
147
+ * - readJson/readToml throws → null (unparseable config)
148
+ * - top-level mcpServers/servers/mcp_servers key absent → null
149
+ * - top-level key value not a plain object → null (e.g., array)
150
+ * - server entry value not a plain object → null (e.g., bare string)
151
+ *
152
+ * Note: `null` deliberately conflates "absent" with "malformed" — both mean
153
+ * "no compatible existing entry to merge into" from `computeForce`'s
154
+ * perspective. The downstream `writeEditorMcpConfig` re-reads via the same
155
+ * format-aware parser and would itself throw on truly corrupt files; that
156
+ * write-side error path is what surfaces the corruption to the user via
157
+ * the `mcp-wiring-write-failed` event in `mcp-wiring.ts` (Pass 0 Critical
158
+ * #1's toast contract).
159
+ */
160
+ declare function readExistingMcpEntry(target: EditorMcpTarget, cwd: string, home?: string): Record<string, unknown> | null;
161
+ /**
162
+ * Detect every editor whose global config surface already exists. Each target
163
+ * can override the probe path when the config file itself is a poor signal
164
+ * (for example Claude Code writes `~/.claude.json`, but installation is better
165
+ * inferred from the presence of `~/.claude/`).
166
+ *
167
+ * Used by `runInit()` and the CLI to install to every editor that already has
168
+ * a config root on disk without creating new user-home directories for tools
169
+ * the user does not have.
170
+ */
171
+ declare function detectInstalledEditors(cwd: string, home?: string): EditorId[];
172
+ //#endregion
3
173
  //#region src/config/schema.d.ts
4
174
  declare const ConfigSchema: z.ZodObject<{
5
175
  content: z.ZodDefault<z.ZodObject<{
@@ -82,5 +252,5 @@ interface AgentIdentity {
82
252
  colorSeed: string;
83
253
  }
84
254
  //#endregion
85
- export { type AgentIdentity, type Config, ConfigSchema, type LoadConfigResult, loadConfig };
255
+ export { ALL_EDITOR_IDS, type AgentIdentity, type Config, ConfigSchema, EDITOR_TARGETS, type EditorId, type EditorMcpResult, type EditorMcpTarget, type LoadConfigResult, type McpInstallOptions, type UserMcpConfigsOptions, detectInstalledEditors, loadConfig, readExistingMcpEntry, writeEditorMcpConfig, writeUserMcpConfigs };
86
256
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{n as e,r as t}from"./loader-BjvYg6bR.mjs";import"./src-CQRey-Fm.mjs";export{t as ConfigSchema,e as loadConfig};
1
+ import{c as e,i as t,l as n,o as r,s as i,t as a}from"./init-RBK7HHVy.mjs";import{n as o,r as s}from"./loader-lj28Sw6t.mjs";import"./src-BFFb00v4.mjs";export{e as ALL_EDITOR_IDS,s as ConfigSchema,n as EDITOR_TARGETS,a as detectInstalledEditors,o as loadConfig,t as readExistingMcpEntry,r as writeEditorMcpConfig,i as writeUserMcpConfigs};
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-DsaVseaZ.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
@@ -1,4 +1,4 @@
1
- import{n as e,r as t,t as n}from"./constants-oa8rklCf.mjs";import{O as r}from"./src-CQw-HNNM.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${r}/ — Open Knowledge config
1
+ import{n as e,r as t,t as n}from"./constants-p2mrQUZK.mjs";import{O as r}from"./src-CQw-HNNM.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${r}/ — Open Knowledge config
2
2
 
3
3
  This directory holds Open Knowledge's configuration for this project. It's **not** where content lives — content lives wherever \`content.dir\` + \`content.include\` in \`config.yml\` point. The default is the repo root with \`**/*.md\`, so any markdown file in the project is fair game. Inspect \`config.yml\` for the actual setting.
4
4
 
@@ -227,4 +227,4 @@ ${f}`;function v(e,t,r){let a=[n,...r??[]],u=new Set,d=[];for(let n of a){let r=
227
227
 
228
228
  `)?`
229
229
  `:``}${n}`,`utf-8`),`appended`)}const x=[{name:n,content:m},{name:`.gitignore`,content:`${e}/\nserver.lock\nui.lock\nsync-state.json\n`},{name:t,content:h}];function S(t){let n=u(t,r),i=[],o=[];a(n,{recursive:!0}),a(l(n,e),{recursive:!0});for(let e of x)y(l(n,e.name),e.content)?i.push(e.name):o.push(e.name);return{created:i,skipped:o}}export{b as a,g as i,d as n,S as o,f as r,v as s,_ as t};
230
- //# sourceMappingURL=init-Cr5zNjLr.mjs.map
230
+ //# sourceMappingURL=init-DsaVseaZ.mjs.map
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-RBK7HHVy.mjs";export{o as detectInstalledEditors,n as formatInitResult,i as initCommand,t as readExistingMcpEntry,e as runInit,r as writeEditorMcpConfig,a as writeUserMcpConfigs};
@@ -0,0 +1,5 @@
1
+ import{i as e}from"./constants-p2mrQUZK.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{n,t as r}from"./src-rqPIkHTi.mjs";import{o as i,s as a}from"./init-DsaVseaZ.mjs";import{t as o}from"./preview-B55OlWJc.mjs";import{t as s}from"./is-object-DaHwJLOe.mjs";import{Command as c}from"commander";import{existsSync as l,mkdirSync as u,readFileSync as d,writeFileSync as f}from"node:fs";import{homedir as p}from"node:os";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as x,win32 as S}from"node:path";import{parse as C,stringify as w}from"smol-toml";const T=[`claude`,`claude-desktop`,`cursor`,`vscode`,`windsurf`,`codex`],ee=[`@inkeep/open-knowledge`,`mcp`],te={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function E(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=b(e);if(m(t)===`cli.mjs`&&m(h(t))===`dist`)return t;let n=t.split(x),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return _(i.length===0?x:i.join(x),`packages`,`cli`,`dist`,`cli.mjs`)}function D(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[E(e.cliEntryPath),`mcp`],env:{...te}}:{command:`npx`,args:[...ee]}}function O(e){return e===`win32`?S:v}function k(e={}){let t=e.platformName??process.platform,n=e.home??p(),r=e.env??process.env,i=O(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function A(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.claude.json`)}function j(e={}){let t=e.platformName??process.platform,n=e.home??p(),r=e.env??process.env;if(t===`darwin`)return v.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??S.join(n,`AppData`,`Roaming`);return S.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function M(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.cursor`,`mcp.json`)}function N(e={}){return O(e.platformName??process.platform).join(k(e),`Code`,`User`,`mcp.json`)}function P(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.codeium`,`windsurf`,`mcp_config.json`)}function F(e={}){let t=e.platformName??process.platform,n=e.home??p();return(e.env??process.env).CODEX_HOME??O(t).join(n,`.codex`)}function I(e={}){return O(e.platformName??process.platform).join(F(e),`config.toml`)}function L(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>L(e,t[n]));if(s(e)&&s(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>L(e[n],t[n]))}return!1}function R(e,t){return Object.entries(t).every(([t,n])=>L(e[t],n))}function z(e,t){return{...e,...t}}function B(e){return{...e,isCompatible(t,n,r){return R(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return z(t,e.buildEntry(n,r))}}}const V={claude:B({id:`claude`,label:`Claude Code`,configPath:(e,t)=>A({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>_(t??p(),`.claude`),legacyProjectConfigPath:e=>_(e,`.mcp.json`),instructionsPath:e=>_(e,`CLAUDE.md`)}),"claude-desktop":B({id:`claude-desktop`,label:`Claude Desktop`,configPath:(e,t)=>j({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(j({home:t}))}),cursor:B({id:`cursor`,label:`Cursor`,configPath:(e,t)=>M({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(M({home:t})),legacyProjectConfigPath:e=>_(e,`.cursor`,`mcp.json`)}),vscode:B({id:`vscode`,label:`VS Code`,configPath:(e,t)=>N({home:t}),format:`json`,topLevelKey:`servers`,serverName:()=>e,buildEntry:(e,t)=>({type:`stdio`,...D(t)}),scope:`global`,detectPath:(e,t)=>h(N({home:t})),legacyProjectConfigPath:e=>_(e,`.vscode`,`mcp.json`)}),windsurf:B({id:`windsurf`,label:`Windsurf`,configPath:(e,t)=>P({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(P({home:t}))}),codex:B({id:`codex`,label:`Codex`,configPath:(e,t)=>I({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(I({home:t})),legacyProjectConfigPath:e=>_(e,`.codex`,`config.toml`)})};function H(e){let t=e.filter(e=>!(e in V));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${T.join(`, `)}`);return e.map(e=>V[e])}function U(e){if(!l(e))return{};let t=d(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(s(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function W(e){if(!l(e))return{};let t=d(e,`utf-8`).trim();if(t===``)return{};try{let n=C(t);if(s(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function G(e,t){u(h(e),{recursive:!0}),f(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function K(e,t){u(h(e),{recursive:!0});let n=w(t);f(e,n.endsWith(`
2
+ `)?n:`${n}\n`,`utf-8`)}const q=`0.0.1`,J=`open-knowledge-ui`;function ne(e,t={}){let n=_(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:J,runtimeExecutable:`node`,runtimeArgs:[E(t.cliEntryPath),`ui`],port:3e3}:{name:J,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!l(n))return u(h(n),{recursive:!0}),f(n,`${JSON.stringify({version:q,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let e=d(n,`utf-8`).trim(),t=e?JSON.parse(e):{};if(!s(t))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let i=Array.isArray(t.configurations)?t.configurations:[],a=i.findIndex(e=>s(e)&&e.name===J);a>=0?i[a]=r:i.push(r);let o={...t,version:t.version??q,configurations:i};return f(n,`${JSON.stringify(o,null,2)}\n`,`utf-8`),{action:a>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Y(e,t,n){try{return l(e.detectPath?.(t,n)??h(e.configPath(t,n)))}catch{return!1}}function X(e,t,n,r){let i=e.serverName(t),a;try{a=e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:i,error:t instanceof Error?t.message:String(t)}}if(!n.skipAvailabilityCheck&&!Y(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:a,serverName:i};let o;try{o=e.format===`toml`?W(a):U(a)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}let s=o[e.topLevelKey]??{},c=s[i],l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}let u={...o,[e.topLevelKey]:{...s,[i]:l}};try{e.format===`toml`?K(a,u):G(a,u)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:c===void 0?`written`:`overwritten`,configPath:a,serverName:i}}function re(e,t){let n=e.legacyProjectConfigPath?.(t);if(!(!n||!l(n)))return{editorId:e.id,label:e.label,path:n}}async function ie(e){let t=H(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>X(t,``,n,e.home))}function ae(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?W(r):U(r)}catch{return null}let a=i[e.topLevelKey];if(!s(a))return null;let o=a[e.serverName(t)];return s(o)?o:null}async function Z(e={}){let t=b(e.cwd??process.cwd()),r={mode:e.devMcp?`dev`:`published`,cliEntryPath:e.cliEntryPath},o=await n(t),s;try{s=i(t)}catch(n){let r=V.claude.configPath(t,e.home);return{contentCreated:[],contentSkipped:[],editors:[],legacyProjectConfigs:[],rootInstructions:[],didGitInit:o.didInit,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let c=H(e.editors??$(t,e.home)),l=c.filter(n=>Y(n,t,e.home)),u=[];for(let n of c){if(e.mcp===!1){let r=``;try{r=n.configPath(t,e.home)}catch{}u.push({editorId:n.id,label:n.label,action:`skipped-flag`,configPath:r,serverName:n.serverName(t)});continue}u.push(X(n,t,r,e.home))}let d=e.mcp===!1?[]:l.map(e=>re(e,t)).filter(e=>e!==void 0),f=l.some(e=>e.id===`claude`)&&e.mcp!==!1?ne(t,r):void 0,p=l.map(e=>e.instructionsPath?.(t)).filter(e=>e!==void 0).map(e=>g(e)?y(t,e):e),m=e.rootInstructions===!1?[]:a(t,!0,p),h=e.mcp===!1?`skipped-flag`:`skipped-missing`,_=u.find(e=>e.editorId===`claude`)??u[0]??{action:h,configPath:V.claude.configPath(t,e.home)};return{contentCreated:s.created,contentSkipped:s.skipped,editors:u,legacyProjectConfigs:d,rootInstructions:m,launchJson:f,didGitInit:o.didInit,mcpAction:_.action,mcpPath:_.configPath,mcpError:`error`in _?_.error:void 0}}function Q(e,n){let r=[],i=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),a=e.editors.some(e=>e.action===`failed`),s=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),c=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),l=e=>{let t=e.configPath.startsWith(n)?y(n,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${t} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${t} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${t} FAILED: ${e.error}`}};e.didGitInit&&r.push(`Initialized git repo at ${n}/.git/ (default branch: main)`);let u=_(n,t);if(e.contentCreated.length>0?(r.push(`Content scaffolded at ${u}/`),r.push(` Created: ${e.contentCreated.join(`, `)}`)):r.push(`Content already present at ${u}/`),e.contentSkipped.length>0&&r.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),r.push(``),e.mcpError&&e.editors.length===0)r.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)r.push(`MCP server configuration:`),r.push(e.mcpAction===`skipped-flag`?` MCP config not written — use without --no-mcp to configure editors`:` No supported editor config directories detected; skipped MCP registration`);else if(s)r.push(`MCP config not written — use without --no-mcp to configure editors`);else if(c)r.push(`MCP server configuration:`),r.push(` No supported editor config directories detected; skipped MCP registration`);else{r.push(`MCP server configuration:`);for(let t of e.editors){let i=t.configPath.startsWith(n)?y(n,t.configPath):t.configPath.replace(/^\/Users\/[^/]+/,`~`),a=t.serverName===`open-knowledge`?``:` (${t.serverName})`,o=` `.repeat(Math.max(1,14-t.label.length)),s=t.editorId===`claude-desktop`&&(t.action===`written`||t.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(t.action){case`written`:r.push(` ${t.label}${o}${i} registered${a}${s}`);break;case`overwritten`:r.push(` ${t.label}${o}${i} updated${a}${s}`);break;case`skipped-missing`:r.push(` ${t.label}${o}${i} config root missing; skipped`);break;case`failed`:r.push(` ${t.label}${o}${i} FAILED: ${t.error}`);break;case`skipped-flag`:break}t.editorId===`claude`&&e.launchJson&&r.push(l(e.launchJson))}}if(a&&(r.push(``),r.push(`For failed editors, add the MCP server entry manually. See:`),r.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){r.push(``),r.push(`Legacy project MCP configs detected:`);for(let t of e.legacyProjectConfigs)r.push(` ${t.label} ${y(n,t.path)}`);r.push(` These project-local files may override the new global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.rootInstructions.length>0){let t=e.rootInstructions.filter(e=>e.action!==`skipped-symlink`);if(t.length>0){r.push(``),r.push(`Root instructions:`);for(let e of t){let t=e.path.startsWith(n)?y(n,e.path):e.path,i=` `.repeat(Math.max(1,14-e.file.length));switch(e.action){case`created`:r.push(` ${e.file}${i}${t} created`);break;case`appended`:r.push(` ${e.file}${i}${t} appended Open Knowledge section`);break;case`replaced`:r.push(` ${e.file}${i}${t} replaced Open Knowledge section`);break;case`skipped-existing`:r.push(` ${e.file}${i}${t} already has Open Knowledge section`);break}}}}if(e.preview?(r.push(``),r.push(o(e.preview,n))):e.previewWarning&&(r.push(``),r.push(`Content preview unavailable: ${e.previewWarning}`)),i){let t=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.label);r.push(``),r.push(`Next steps:`),r.push(` 1. Open your editor (${t.join(` / `)})`),r.push(` 2. Approve the MCP server when prompted`),r.push(` 3. The knowledge base is ready — use the three workflow tools:`),r.push(` - mcp__open-knowledge__init-content — bootstrap articles from the codebase`),r.push(` - mcp__open-knowledge__ingest — capture an external source`),r.push(` - mcp__open-knowledge__research — gather sources and write findings`)}return r.join(`
3
+ `)}function $(e,t){let n=[];for(let r of T)Y(V[r],e,t)&&n.push(r);return n}function oe(){return new c(`init`).description(`Scaffold ${t}/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the ${t}/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).action(async e=>{let t=process.cwd(),n;try{n=await Z({cwd:t,mcp:e.mcp,devMcp:e.devMcp})}catch(e){if(e instanceof r){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
4
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-CfQP5PHw.mjs`),{loadConfig:r}=await import(`./loader-DzbVFAz5.mjs`),{resolveContentDir:i}=await import(`./paths-CJMOZlvG.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o,include:a.content.include,exclude:a.content.exclude})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Q(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Z as a,T as c,ae as i,V as l,Q as n,X as o,oe as r,ie as s,$ as t};
5
+ //# sourceMappingURL=init-RBK7HHVy.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-lj28Sw6t.mjs";export{e as loadConfig};
@@ -1,3 +1,3 @@
1
- import{r as e}from"./constants-oa8rklCf.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{t as n}from"./is-object-DaHwJLOe.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{realpath as c}from"node:fs/promises";import{z as l}from"zod";async function u(e){let t=o(e);try{return await c(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const d=l.object({title:l.string().optional(),description:l.string().optional(),tags:l.array(l.string()).optional()}).strict(),f=l.object({match:l.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:d}).strict(),p=l.object({content:l.object({dir:l.string().default(`.`),include:l.array(l.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:l.array(l.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:l.object({oauthAppClientId:l.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:l.object({enabled:l.boolean().optional(),pushIntervalSeconds:l.number().int().min(1).default(60),pullIntervalSeconds:l.number().int().min(1).default(30),autoCommit:l.boolean().default(!0),autoPush:l.boolean().default(!0),autoPull:l.boolean().default(!0),commitMessage:l.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:l.object({port:l.number().int().min(0).max(65535).default(0),host:l.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:l.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:l.object({debounceMs:l.number().int().min(0).default(2e3),maxDebounceMs:l.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:l.object({baseUrl:l.url().optional()}).default({}),folders:l.array(f).default([]),mcp:l.object({autoStart:l.boolean().default(!0),tools:l.object({read_document:l.object({historyDepth:l.number().int().min(0).default(5)}).default({historyDepth:5}),search:l.object({maxResults:l.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function m(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=m(a,o):o!==void 0&&(r[i]=o)}return r}function h(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function g(n){let r=n??process.cwd(),i=[],s=o(a(),t,e),c={},l=h(s);l&&(c=m(c,l),i.push(s));let u=o(r,t,e),d=h(u);d&&(c=m(c,d),i.push(u));let f=p.safeParse(c);if(!f.success){let e=f.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
1
+ import{r as e}from"./constants-p2mrQUZK.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{t as n}from"./is-object-DaHwJLOe.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{realpath as c}from"node:fs/promises";import{z as l}from"zod";async function u(e){let t=o(e);try{return await c(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const d=l.object({title:l.string().optional(),description:l.string().optional(),tags:l.array(l.string()).optional()}).strict(),f=l.object({match:l.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:d}).strict(),p=l.object({content:l.object({dir:l.string().default(`.`),include:l.array(l.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:l.array(l.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:l.object({oauthAppClientId:l.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:l.object({enabled:l.boolean().optional(),pushIntervalSeconds:l.number().int().min(1).default(60),pullIntervalSeconds:l.number().int().min(1).default(30),autoCommit:l.boolean().default(!0),autoPush:l.boolean().default(!0),autoPull:l.boolean().default(!0),commitMessage:l.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:l.object({port:l.number().int().min(0).max(65535).default(0),host:l.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:l.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:l.object({debounceMs:l.number().int().min(0).default(2e3),maxDebounceMs:l.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:l.object({baseUrl:l.url().optional()}).default({}),folders:l.array(f).default([]),mcp:l.object({autoStart:l.boolean().default(!0),tools:l.object({read_document:l.object({historyDepth:l.number().int().min(0).default(5)}).default({historyDepth:5}),search:l.object({maxResults:l.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function m(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=m(a,o):o!==void 0&&(r[i]=o)}return r}function h(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function g(n){let r=n??process.cwd(),i=[],s=o(a(),t,e),c={},l=h(s);l&&(c=m(c,l),i.push(s));let u=o(r,t,e),d=h(u);d&&(c=m(c,d),i.push(u));let f=p.safeParse(c);if(!f.success){let e=f.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
2
2
  `)}`)}return{config:f.data,sources:i}}function _(e,t=process.env){let n=e;return t.PORT&&(n={...n,server:{...n.server,port:Number(t.PORT)}}),t.HOST&&(n={...n,server:{...n.server,host:t.HOST}}),n}function v(e){let t=e.env??process.env,n=e.cacheMs??1e3,r=e.loadConfigFn??g,i=new Map,a=new Map,o=u(e.startupCwd);return async s=>{let c=await u(s??e.startupCwd),l=Date.now(),d=i.get(c);if(d&&d.expiresAt>l)return d.config;let f=a.get(c);if(f)return await f;let p=(async()=>{if(c===await o){let r=_(e.startupConfig,t);return i.set(c,{config:r,expiresAt:Date.now()+n}),r}let a=_(r(c).config,t);return i.set(c,{config:a,expiresAt:Date.now()+n}),a})();a.set(c,p);try{return await p}finally{a.delete(c)}}}export{u as i,g as n,p as r,v as t};
3
- //# sourceMappingURL=loader-BjvYg6bR.mjs.map
3
+ //# sourceMappingURL=loader-lj28Sw6t.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./paths-DreD7ab4.mjs";export{t as resolveContentDir,e as resolveLockDir};
@@ -1,2 +1,2 @@
1
- import"./constants-oa8rklCf.mjs";import{O as e}from"./src-CQw-HNNM.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
- //# sourceMappingURL=paths-Dcbxj9qp.mjs.map
1
+ import"./constants-p2mrQUZK.mjs";import{O as e}from"./src-CQw-HNNM.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
+ //# sourceMappingURL=paths-DreD7ab4.mjs.map