@inkeep/open-knowledge 0.20.0-beta.7 → 0.20.0-beta.9

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 (42) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +9 -9
  4. package/dist/constants-nTyY9ahE.mjs +2 -0
  5. package/dist/{dist-C7UX8Qzt.mjs → dist-Bf8Vy08L.mjs} +1 -1
  6. package/dist/{dist-BD4HwRwv.mjs → dist-ctsYjUwZ.mjs} +2 -2
  7. package/dist/index.mjs +1 -1
  8. package/dist/init-B55_K_T8.mjs +1 -0
  9. package/dist/{init-tXC9WSsK.mjs → init-DZYYr4Qo.mjs} +4 -4
  10. package/dist/loader-DD-AnN5t.mjs +1 -0
  11. package/dist/{loader-Djfd-Wlm.mjs → loader-DJ2_1TJm.mjs} +2 -2
  12. package/dist/preview-BEK2Jwjs.mjs +1 -0
  13. package/dist/{preview-C6hRCpi4.mjs → preview-DZhqYol8.mjs} +2 -2
  14. package/dist/public/assets/{ActivityModeContent-Bw1oRtQH.js → ActivityModeContent-DGw5iUid.js} +1 -1
  15. package/dist/public/assets/{DocumentContext-o-LUu0wz.js → DocumentContext-CmO1rPM6.js} +2 -2
  16. package/dist/public/assets/{ManagedArtifactProperties-D-xwymUR.js → ManagedArtifactProperties-Cr8eMUCF.js} +1 -1
  17. package/dist/public/assets/{PropertyPanel-CeeQNbcR.js → PropertyPanel-ze_4e3n_.js} +1 -1
  18. package/dist/public/assets/{SettingsDialogBody-wC0Rm8N5.js → SettingsDialogBody-hP9Vzn5G.js} +2 -2
  19. package/dist/public/assets/{SourceEditor-4ljQqBHw.js → SourceEditor-4T4loRia.js} +2 -2
  20. package/dist/public/assets/{config-validation-events-mtT7Nmop.js → config-validation-events-CA8jFSci.js} +4 -4
  21. package/dist/public/assets/index-BHFFl2Q_.css +1 -0
  22. package/dist/public/assets/index-DNKaMY7F.js +2004 -0
  23. package/dist/public/assets/{selection-context-CFA_dZau.js → selection-context-kDVHDAV2.js} +1 -1
  24. package/dist/public/assets/{typing-burst-detector-BfS-xBMY.js → typing-burst-detector-zGrvqSf8.js} +2 -2
  25. package/dist/public/index.html +7 -7
  26. package/dist/{repair-launch-json-TUK_SdBP.mjs → repair-launch-json-CW3DFdqJ.mjs} +2 -2
  27. package/dist/{repair-mcp-configs-AXgjVWOZ.mjs → repair-mcp-configs-DE4EVC8e.mjs} +2 -2
  28. package/dist/repair-skills-DIh6L29_.mjs +1 -0
  29. package/dist/{repair-skills-DSxz7qY4.mjs → repair-skills-DmGQPZy4.mjs} +2 -2
  30. package/dist/{src-CjUcbTUv.mjs → src-3-Gxdiww.mjs} +2 -2
  31. package/dist/{start-D6KVRcwv.mjs → start-79nR1Eky.mjs} +2 -2
  32. package/dist/start-DGfnJdwS.mjs +1 -0
  33. package/dist/{write-project-skill-CHLl9ySs.mjs → write-project-skill-BU5uV78y.mjs} +2 -2
  34. package/package.json +1 -1
  35. package/dist/constants-C1DCSZPa.mjs +0 -2
  36. package/dist/init-DaBG9Vt5.mjs +0 -1
  37. package/dist/loader-CpxBkx-l.mjs +0 -1
  38. package/dist/preview-DmtYPtUD.mjs +0 -1
  39. package/dist/public/assets/index-BZo7KSQC.js +0 -2004
  40. package/dist/public/assets/index-xDiw2wLq.css +0 -1
  41. package/dist/repair-skills-CLwWZbvZ.mjs +0 -1
  42. package/dist/start-DYwAiJfq.mjs +0 -1
@@ -3,7 +3,7 @@ name: open-knowledge-discovery
3
3
  description: "Read when the user asks what OpenKnowledge is, wants to install it on a repository, wants to share an OpenKnowledge project with collaborators, or asks how `ok init` / `ok cowork` / OK Desktop set up a project. Do NOT load to perform OpenKnowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs. If the user appears to be editing markdown inside a `.ok/` project and this is the only OK skill loaded, advise them to re-run `ok init` to install the project-local skill."
4
4
  compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
5
5
  metadata:
6
- version: "0.20.0-beta.7"
6
+ version: "0.20.0-beta.9"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "Authoritative agent-runtime contract for working inside an OpenKnowledge project — a markdown-CRDT knowledge base exposed over MCP. Use whenever reading, listing, searching, or editing any `.md` or `.mdx` file in the project, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, and the rest). Installed by `ok init`, so its presence means this is an OpenKnowledge project and it governs every markdown file here. Covers the read/write tool surface, grounding and linking rules, folder/template conventions, the live browser preview, and the rule that OK's MCP tools — never native file tools — handle in-scope markdown."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.20.0-beta.7"
6
+ version: "0.20.0-beta.9"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{$a as n,Bi as r,Ha as i,La as a,Li as o,Mo as s,No as c,Pn as l,Ra as u,Ya as d,ao as f,co as p,eo as m,f as h,fo as g,ga as _,ho as v,n as y,on as ee,oo as b,s as x,si as te,so as S,to as C,ui as ne,vo as re}from"./server-lock-CN2YHwpP-COM23IWb.mjs";import{a as ie,n as ae,r as oe,t as se}from"./gh-detect-BDIdc7oG.mjs";import{i as ce}from"./git-handle-DY9lXoT3-Cmzgvwd8.mjs";import{$ as le,An as ue,Cn as de,D as fe,Dn as pe,Dr as me,Ft as he,Gt as ge,Hn as _e,Kn as ve,Kt as ye,L as be,Mr as xe,O as Se,Or as Ce,Qr as w,Ur as we,Wt as Te,Yr as Ee,Zi as De,Zt as Oe,_t as ke,aa as Ae,ar as je,at as Me,b as Ne,bt as Pe,c as Fe,da as Ie,en as Le,et as Re,fa as ze,ga as Be,hn as Ve,ia as He,la as Ue,ln as We,ma as Ge,mi as Ke,mn as qe,na as Je,oa as Ye,or as Xe,ot as Ze,pa as Qe,ra as $e,rt as et,st as tt,ta as nt,ti as rt,wt as it,x as at,zn as ot}from"./dist-BD4HwRwv.mjs";import{t as st}from"./yazl-Docqgl6q.mjs";import{n as ct,r as lt,t as T}from"./dist-bundle-D75dREX-.mjs";import{A as ut,C as dt,D as ft,E as pt,F as mt,I as ht,L as gt,M as _t,N as vt,O as yt,P as bt,S as xt,T as St,b as Ct,j as wt,k as Tt,u as Et,v as Dt,w as Ot}from"./init-tXC9WSsK.mjs";import{a as kt,c as At,h as jt,i as Mt,l as Nt,m as Pt,o as Ft,s as It,u as Lt}from"./src-CjUcbTUv.mjs";import{n as Rt,t as zt}from"./constants-C1DCSZPa.mjs";import{n as Bt,t as Vt}from"./loader-Djfd-Wlm.mjs";import{c as Ht,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-8SzMRIVy.mjs";import{S as Ut,_ as Wt,b as Gt,m as Kt,x as qt,y as Jt}from"./start-D6KVRcwv.mjs";import{n as Yt}from"./repair-skills-DSxz7qY4.mjs";import{execFile as Xt,execSync as Zt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as Qt,closeSync as $t,constants as en,cpSync as tn,createWriteStream as nn,existsSync as P,mkdirSync as F,mkdtempSync as rn,openSync as an,readFileSync as I,readdirSync as on,realpathSync as sn,rmSync as cn,statSync as ln,unlinkSync as un,writeFileSync as L}from"node:fs";import dn,{basename as R,dirname as fn,join as z,relative as pn,resolve as B,sep as mn}from"node:path";import hn from"node:process";import{arch as gn,freemem as _n,homedir as vn,platform as yn,release as bn,tmpdir as xn,totalmem as Sn,type as Cn,uptime as wn}from"node:os";import{fileURLToPath as Tn}from"node:url";import{rm as En}from"node:fs/promises";import{createHash as Dn,randomUUID as On}from"node:crypto";import{setTimeout as kn}from"node:timers/promises";import{promisify as An,stripVTControlCharacters as jn,styleText as V}from"node:util";import{AsyncLocalStorage as Mn,AsyncResource as Nn}from"node:async_hooks";import*as Pn from"node:readline";import{createInterface as Fn}from"node:readline/promises";const In={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Ln;(function(e){})(Ln||={});function Rn(e){return re(d,e)}async function zn(e,t,n,r){let i=Bn(await Vn(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function Bn(e){let t={};for(let n of e.split(`
2
+ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{$a as n,Bi as r,Ha as i,La as a,Li as o,Mo as s,No as c,Pn as l,Ra as u,Ya as d,ao as f,co as p,eo as m,f as h,fo as g,ga as _,ho as v,n as y,on as ee,oo as b,s as x,si as te,so as S,to as C,ui as ne,vo as re}from"./server-lock-CN2YHwpP-COM23IWb.mjs";import{a as ie,n as ae,r as oe,t as se}from"./gh-detect-BDIdc7oG.mjs";import{i as ce}from"./git-handle-DY9lXoT3-Cmzgvwd8.mjs";import{$ as le,An as ue,Cn as de,D as fe,Dn as pe,Dr as me,Ft as he,Gt as ge,Hn as _e,Kn as ve,Kt as ye,L as be,Mr as xe,O as Se,Or as Ce,Qr as w,Ur as we,Wt as Te,Yr as Ee,Zi as De,Zt as Oe,_t as ke,aa as Ae,ar as je,at as Me,b as Ne,bt as Pe,c as Fe,da as Ie,en as Le,et as Re,fa as ze,ga as Be,hn as Ve,ia as He,la as Ue,ln as We,ma as Ge,mi as Ke,mn as qe,na as Je,oa as Ye,or as Xe,ot as Ze,pa as Qe,ra as $e,rt as et,st as tt,ta as nt,ti as rt,wt as it,x as at,zn as ot}from"./dist-ctsYjUwZ.mjs";import{t as st}from"./yazl-Docqgl6q.mjs";import{n as ct,r as lt,t as T}from"./dist-bundle-D75dREX-.mjs";import{A as ut,C as dt,D as ft,E as pt,F as mt,I as ht,L as gt,M as _t,N as vt,O as yt,P as bt,S as xt,T as St,b as Ct,j as wt,k as Tt,u as Et,v as Dt,w as Ot}from"./init-DZYYr4Qo.mjs";import{a as kt,c as At,h as jt,i as Mt,l as Nt,m as Pt,o as Ft,s as It,u as Lt}from"./src-3-Gxdiww.mjs";import{n as Rt,t as zt}from"./constants-nTyY9ahE.mjs";import{n as Bt,t as Vt}from"./loader-DJ2_1TJm.mjs";import{c as Ht,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-8SzMRIVy.mjs";import{S as Ut,_ as Wt,b as Gt,m as Kt,x as qt,y as Jt}from"./start-79nR1Eky.mjs";import{n as Yt}from"./repair-skills-DmGQPZy4.mjs";import{execFile as Xt,execSync as Zt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as Qt,closeSync as $t,constants as en,cpSync as tn,createWriteStream as nn,existsSync as P,mkdirSync as F,mkdtempSync as rn,openSync as an,readFileSync as I,readdirSync as on,realpathSync as sn,rmSync as cn,statSync as ln,unlinkSync as un,writeFileSync as L}from"node:fs";import dn,{basename as R,dirname as fn,join as z,relative as pn,resolve as B,sep as mn}from"node:path";import hn from"node:process";import{arch as gn,freemem as _n,homedir as vn,platform as yn,release as bn,tmpdir as xn,totalmem as Sn,type as Cn,uptime as wn}from"node:os";import{fileURLToPath as Tn}from"node:url";import{rm as En}from"node:fs/promises";import{createHash as Dn,randomUUID as On}from"node:crypto";import{setTimeout as kn}from"node:timers/promises";import{promisify as An,stripVTControlCharacters as jn,styleText as V}from"node:util";import{AsyncLocalStorage as Mn,AsyncResource as Nn}from"node:async_hooks";import*as Pn from"node:readline";import{createInterface as Fn}from"node:readline/promises";const In={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Ln;(function(e){})(Ln||={});function Rn(e){return re(d,e)}async function zn(e,t,n,r){let i=Bn(await Vn(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function Bn(e){let t={};for(let n of e.split(`
3
3
  `)){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 Vn(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 Hn(e,n){let r=new t(`git-credential`);return r.description(`Git credential helper (git credential-helper protocol)`),r.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=n?.();try{let n,r=await e({onKeychainRead:e=>{n=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&t?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await zn(process.stdin,process.stdout,r,{log:t,getDiag:()=>n});await de(t),process.exit(i)}catch(e){t?.error({error:e instanceof Error?e.message:String(e)},`[auth] git-credential get: unexpected error`),await de(t),process.exit(1)}}),r}function Un(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Wn(e,t,n){let r={baseUrl:Un(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ct(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Gn(e){let t=e.request||T,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Wn(t,`POST /login/device/code`,n)}async function Kn(e){let t=await Wn(e.request||T,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=qn(e,t.data.expires_in),n.refreshTokenExpiresAt=qn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function qn(e,t){return new Date(e+t*1e3).toISOString()}async function Jn(e,t){let n=Yn(e,t.auth);if(n)return n;let{data:r}=await Gn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Zn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Yn(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Xn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Zn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Kn({...i,clientType:`oauth-app`}):await Kn({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Xn(r.interval),Zn(e,t,n,r);if(a===`slow_down`)return await Xn(r.interval+7),Zn(e,t,n,r);throw i}}async function Qn(e,t){return Jn(e,{auth:t})}async function $n(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await Jn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var er=`0.0.0-development`;function tr(e){let t=e.request||T.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${er} ${lt()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Qn.bind(null,i),{hook:$n.bind(null,i)})}async function nr(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=tr({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BnlRWriT.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function rr(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const ir=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function H(e){let t=e.toLowerCase().replace(/:\d+$/,``);ir.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 ar(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function or(e,t,n=nr){let r=rr(),{host:i,json:a}=e;H(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?ar(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?ar(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function sr(e){return new t(`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 t=>{await or(t,await e())})}const cr=e=>e.name===`enter`||e.name===`return`;var lr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},ur=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},dr=class extends Error{name=`ExitPromptError`},fr=class extends Error{name=`HookError`},pr=class extends Error{name=`ValidationError`};const mr=new Mn;function hr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function gr(e,t){let n=hr(e);return mr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function U(){let e=mr.getStore();if(!e)throw new fr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function _r(){return U().rl}function vr(e){return Nn.bind((...t)=>{let n=U(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function yr(e){let t=U(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function br(){U().handleChange()}const xr={queue(e){let t=U(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(_r());if(r!=null&&typeof r!=`function`)throw new pr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=U();vr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=U();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Sr(e){return typeof e==`function`}function W(e){return yr(t=>{let n=Nn.bind(function(e){t.get()!==e&&(t.set(e),br())});if(t.initialized)return[t.get(),n];let r=Sr(e)?e():e;return t.set(r),[r,n]})}function Cr(e,t){yr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&xr.queue(e),n.set(t)})}const wr={prefix:{idle:V(`blue`,`?`),done:V(`green`,gt.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>V(`yellow`,e))},style:{answer:e=>V(`cyan`,e),message:e=>V(`bold`,e),error:e=>V(`red`,`> ${e}`),defaultAnswer:e=>V(`dim`,`(${e})`),help:e=>V(`dim`,e),highlight:e=>V(`cyan`,e),key:e=>V(`cyan`,V(`bold`,`<${e}>`))}};function Tr(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Er(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=Tr(n)&&Tr(r)?Er(n,r):r}return t}function Dr(...e){return Er(wr,...e.filter(e=>e!=null))}function Or({status:e=`idle`,theme:t}){let[n,r]=W(!1),[i,a]=W(0),{prefix:o,spinner:s}=Dr(t);return Cr(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function kr(e){return W({current:e})[0]}function Ar(e){let t=kr(e);t.current=e,Cr(e=>{let n=!1,r=vr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var jr=e(ht(),1);function Mr(e,t){return e.split(`
4
4
  `).flatMap(e=>mt(e,t,{trim:!1,hard:!0}).split(`
5
5
  `).map(e=>e.trimEnd())).join(`
@@ -19,9 +19,9 @@ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";impor
19
19
  `),patterns:[...t],lineCount:n}}const Qi=z(vn(),`.ok`,`logs`),$i=z(vn(),`.ok`,`bug-reports`);function ea(e){let t=z(e,`.ok`,`config.yml`);if(P(t))try{let e=I(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return P(z(e,`.ok`))?Dn(`sha256`).update(B(e)).digest(`hex`).slice(0,12):null}function ta(){let e={timestamp:new Date().toISOString(),platform:yn(),osType:Cn(),osRelease:bn(),hostname:`[redacted]`,uptime:wn(),freeMem:_n(),totalMem:Sn(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Zt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=z(__dirname,`..`,`..`,`package.json`);P(t)&&(e.okVersion=JSON.parse(I(t,`utf8`)).version)}catch{}return e}function na(e){if(!P(Qi))return{files:[],dir:Qi};let t=on(Qi).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>z(Qi,e));if(e&&t.length>0){let n=t.filter(t=>{try{return I(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:Qi}}function ra(e){let t=z(e,`.ok`,`local`);return P(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}function ia(e){let t=z(e,`.ok`,`local`,`logs`);return P(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}async function aa(t){let n=Ku();F($i,{recursive:!0});let r=z($i,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=ta(),{files:a}=na(t.projectSlug),{files:o}=ra(t.cwd),{files:s}=ia(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CQSNnbvt.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Zi(I(e,`utf8`)),i=`logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of o)try{let{redacted:t,patterns:n,lineCount:r}=Zi(I(e,`utf8`)),i=`lockdir/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of s)try{let{redacted:t,patterns:n,lineCount:r}=Zi(I(e,`utf8`)),i=`local-logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}let f=JSON.stringify(i,null,2);d.addBuffer(Buffer.from(f,`utf8`),`sysinfo.json`),l.push(`sysinfo.json`);let p={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:t.projectSlug,files:l,redactions:c,sysinfo:i};d.addBuffer(Buffer.from(JSON.stringify(p,null,2),`utf8`),`MANIFEST.json`);let m=c.reduce((e,t)=>e+t.lineCount,0),h=[`# Bug Report Bundle`,``,`Generated: ${p.generatedAt}`,`Project: ${t.projectSlug??`(unscoped)`}`,`Discipline version: ${p.disciplineVersion}`,``,`## Contents`,``,...l.map(e=>`- ${e}`),``,`## Privacy`,``,`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Xi.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
20
20
  `);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=nn(r);if(d.outputStream.pipe(g),await new Promise((e,t)=>{g.on(`close`,e),g.on(`error`,t)}),n?.info({bundlePath:r,fileCount:l.length,redactionCount:m},`bundle written`),process.stdout.write(`${r}\n`),m>0&&process.stderr.write(`ok bug-report: ${m} line(s) auto-redacted across ${c.length} file(s)\n`),!t.noReveal&&yn()===`darwin`)try{M(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function oa(){return new t(`bug-report`).description(`Generate a diagnostic bundle for bug reporting`).option(`--reveal`,`Reveal the bundle in Finder (default: true)`,!0).option(`--no-reveal`,`Do not reveal the bundle in Finder`).action(async e=>{let t=process.cwd(),n=ea(t);try{await aa({projectSlug:n,cwd:t,noReveal:!e.reveal})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`ok bug-report: failed — ${t}\n`),process.exitCode=1}})}function sa(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 ca(e){let t=e.inspect??(t=>jt(e.lockDir,t)),n=e.unlink??(e=>un(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=sa(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 la(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),ca({lockDir:w(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function ua(e,t,n={},r=se){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`]}}async function da(e,t,n=fetch){let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{return(await n(`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{signal:r.signal,headers:{"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}})).status===200}catch{return!1}finally{clearTimeout(i)}}const fa=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function pa(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 fa)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function ma(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t.GIT_TERMINAL_PROMPT=`0`,t.LANG=`C`,t.LC_ALL=`C`,t}function ha(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const ga=o;async function _a(e){try{return await e.clone(ha(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&ga(t))return e.onFallback(e.branch),await e.clone(ha(null)),{fellBack:!0};throw t}}function va(e,t){return{baseDir:e,config:t,unsafe:{allowUnsafeCredentialHelper:!0,allowUnsafePager:!0,allowUnsafeSshCommand:!0,allowUnsafeAskPass:!0}}}function ya(e,t,n){return e===`https`&&t===`github.com`&&n}function ba(e,t){let n=`${t.owner}/${t.name}`;return e===n||e===`${n}.git`?`https://${t.hostname}/${n}`:e}async function xa(e,t,n,r=process.cwd()){let i=Pt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=ba(e,i),o=t.dir?B(r,t.dir):B(r,i.name);if(P(o)&&on(o).length>0)throw Error(`Target directory is not empty: ${o}`);let s=ie(),c=i.protocol===`https`&&i.hostname===`github.com`?await da(i.owner,i.name):!1,l=ya(i.protocol,i.hostname,c)?{tier:`none`,credentialArgs:[]}:await ua(i.hostname,s,{}),u=ma(),d=ce(va(r,l.credentialArgs.length>=2?[l.credentialArgs[1]]:[])).env(u),f=-1;d.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
21
21
  `)){let n=pa(e);n&&n.pct!==f&&(f=n.pct,q(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await _a({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:e=>d.clone(a,o,e),onFallback:e=>{q(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
22
- `);try{let{runInit:e}=await import(`./init-DaBG9Vt5.mjs`),n=await e({cwd:o,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Sa(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function Sa(e){let t=Ct(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const Ca=/^[A-Za-z0-9._/:@-]+$/;function wa(e){return Ca.test(e)?e:_(e)}function Ta(e,t){let n=typeof t==`string`&&t.length>0?` -b ${wa(t)}`:``;return`ok clone ${wa(e)}${n}`}function Ea(e){let t=te(e.error);if(t.kind!==`auth`)return null;if(r(t)){let t=Ta(e.url,e.branch);return[`✗ Couldn't clone ${e.url} — authentication is required.`,``,` To fix:`,` 1. Run: ok auth login`,` 2. Then re-run: ${t}`].join(`
22
+ `);try{let{runInit:e}=await import(`./init-B55_K_T8.mjs`),n=await e({cwd:o,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Sa(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function Sa(e){let t=Ct(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const Ca=/^[A-Za-z0-9._/:@-]+$/;function wa(e){return Ca.test(e)?e:_(e)}function Ta(e,t){let n=typeof t==`string`&&t.length>0?` -b ${wa(t)}`:``;return`ok clone ${wa(e)}${n}`}function Ea(e){let t=te(e.error);if(t.kind!==`auth`)return null;if(r(t)){let t=Ta(e.url,e.branch);return[`✗ Couldn't clone ${e.url} — authentication is required.`,``,` To fix:`,` 1. Run: ok auth login`,` 2. Then re-run: ${t}`].join(`
23
23
  `)}if(t.subclass===`403`){let t=typeof e.principal==`string`&&e.principal.length>0?` (signed in as @${e.principal} — may lack access)`:``;return`✗ Access denied when cloning ${e.url}${t}. Check that your account has access to the repository.`}return t.subclass===`ssh-auth`?`✗ Couldn't clone ${e.url} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`:["✗ Your GitHub token is missing required OAuth scopes — likely the `repo` scope.",``,` To fix:`," 1. Create a token with `repo` scope at https://github.com/settings/tokens",` 2. Run: ok auth pat`,` 3. Then re-run: ${Ta(e.url,e.branch)}`].join(`
24
- `)}function Da(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Ea({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Oa(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function ka(e){let t=te(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=Pt(e.url);t&&(n=await(e.resolvePrincipal??(e=>Oa(ie(),e)))(t.hostname))}Da({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function Aa(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await xa(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DYwAiJfq.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){await ka({error:e,url:t,branch:r.branch??null,json:r.json,emit:e=>q(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var ja=c();const Ma=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...u.map(e=>e.path)];function Na(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Bt;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Pa(e){let t=(0,ja.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Ma)t.hasIn(e)&&n.push(e.join(`.`));return n}function Fa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ia(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Fa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function La(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,a=e.dryRun??!1,o=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Ie,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:Ue(`project`,o,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:Ue(`user`,o,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Pa(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||a){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:o,scope:t,patch:Ia(Ma.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:i(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(a?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function Ra(){let e=new t(`config`).description(`Inspect and maintain OpenKnowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Na({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await La({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const za=[` 1. ${j(`Customize`)} (sidebar) → ${j(`Skills`)}`,` 2. Click the ${j(`+`)} button`,` 3. Click ${j(`Create skill`)}`,` 4. Click ${j(`Upload skill`)}`,` 5. Pick ${j(`openknowledge.skill`)} from Downloads`],Ba=E(` Open the Claude Desktop App, then: ${j(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Va(e){let t=[O(`Built ${e.outputPath}`),D(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(A(` Handoff failed: ${e.handoffError.message}`)),t.push(Ba),t.join(`
24
+ `)}function Da(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Ea({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Oa(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function ka(e){let t=te(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=Pt(e.url);t&&(n=await(e.resolvePrincipal??(e=>Oa(ie(),e)))(t.hostname))}Da({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function Aa(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await xa(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DGfnJdwS.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){await ka({error:e,url:t,branch:r.branch??null,json:r.json,emit:e=>q(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var ja=c();const Ma=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...u.map(e=>e.path)];function Na(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Bt;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Pa(e){let t=(0,ja.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Ma)t.hasIn(e)&&n.push(e.join(`.`));return n}function Fa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ia(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Fa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function La(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,a=e.dryRun??!1,o=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Ie,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:Ue(`project`,o,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:Ue(`user`,o,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Pa(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||a){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:o,scope:t,patch:Ia(Ma.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:i(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(a?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function Ra(){let e=new t(`config`).description(`Inspect and maintain OpenKnowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Na({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await La({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const za=[` 1. ${j(`Customize`)} (sidebar) → ${j(`Skills`)}`,` 2. Click the ${j(`+`)} button`,` 3. Click ${j(`Create skill`)}`,` 4. Click ${j(`Upload skill`)}`,` 5. Pick ${j(`openknowledge.skill`)} from Downloads`],Ba=E(` Open the Claude Desktop App, then: ${j(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Va(e){let t=[O(`Built ${e.outputPath}`),D(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(A(` Handoff failed: ${e.handoffError.message}`)),t.push(Ba),t.join(`
25
25
  `)}function Ha(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[E(`OpenKnowledge skill ${j(`v${t}`)} already delivered to Claude Desktop.`),D(` Recorded at ${n} in ~/.ok/skill-state.yml`),D(` Use ${j(`--force`)} to rebuild and re-open the install dialog.`)].join(`
26
26
  `)}function Ua(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[O(`Built ${e.outputPath}`),D(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),E(` Claude Desktop App opened. Now upload the file manually:`),...za,D(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
27
27
  `)}function Wa(e){return`${k(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Ga(e={}){let t=await it(e);return t.status===`failed`?{...t,message:Wa(t),exitCode:1}:t.status===`skip-current`?{...t,message:Ha(t),exitCode:0}:t.status===`installed`?{...t,message:Ua(t),exitCode:0}:{...t,message:Va(t),exitCode:0}}function Ka(){return new t(`cowork`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. (Advanced/rarely needed — `ok init` already wires Claude.)").option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).option(`--force`,`Bypass the install-state gate and rebuild unconditionally`).action(async e=>{let t=await Ga({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var qa=e(st(),1),J=e(Ht(),1);const Ja=new Set([`doc.name`]);function Ya(e){return`doc:${Dn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function Xa(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function Za(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Ya(e);return t.originalToHashed.set(e,r),Xa(t,e,r),r}function Qa(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function $a(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eo(e,t){if(typeof e==`string`)return Qa(e,t.contentDir);if(Array.isArray(e))return e.map(e=>eo(e,t));if(!$a(e))return e;let n=typeof e.key==`string`&&Ja.has(e.key)&&$a(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&$a(a)){let e=Za(n,t);r[i]={...a,stringValue:e}}else Ja.has(i)&&typeof a==`string`?r[i]=Za(a,t):r[i]=eo(a,t);return r}function to(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function no(e,t){let n=I(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
@@ -55,24 +55,24 @@ ws.addEventListener('error', () => process.exit(1));
55
55
  setTimeout(() => process.exit(2), ${t+1e4});
56
56
  `),r}async function ps(e,t,n,r,i){let a=fs(e,t,z(r,`cpu.cpuprofile`)),o=!1,s=M(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=cs(n);e&&i(e)},1e3);await new Promise(e=>{s.once(`close`,t=>{o=t===0,e()}),setTimeout(()=>{s.kill(),e()},t+12e3)}),clearInterval(c);try{cn(z(a,`..`),{recursive:!0,force:!0})}catch{}return o}function ms(e){let t;try{t=JSON.parse(e)}catch{return`(could not parse profile)`}let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map;for(let e of t.nodes)for(let t of e.children??[])r.set(t,e.id);let i=new Map;for(let e of t.samples??[])i.set(e,(i.get(e)??0)+1);let a=t.samples?.length??0,o=t.endTime!=null&&t.startTime!=null?((t.endTime-t.startTime)/1e3).toFixed(2):`?`,s=[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10),c=[`samples ${a} duration_ms ${o}`,``,`Top leaf nodes`];for(let[e,t]of s){let r=n.get(e);if(!r)continue;let i=a>0?(t/a*100).toFixed(1):`0.0`,{functionName:o,url:s,lineNumber:l,columnNumber:u}=r.callFrame;c.push(` ${t} ${i}% id=${e} ${o||`(anonymous)`} ${s}:${l}:${u} hit=${r.hitCount??0}`)}c.push(``,`Top stacks`);let l=e=>{let t=[],i=e;for(;i!=null;){let e=n.get(i);if(!e)break;let{functionName:a,url:o,lineNumber:s,columnNumber:c}=e.callFrame;t.unshift(` ${a||`(anonymous)`} ${o} ${s} ${c}`),i=r.get(i)}return t};for(let[e,t]of s.slice(0,5)){let n=a>0?(t/a*100).toFixed(1):`0.0`;c.push(``,`--- ${t} ${n}%`,...l(e))}return c.join(`
57
57
  `)}async function hs(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??At,s=t.inspect??jt,c=t.resolveCommand??Nt,l=t.resolveUsage??Lt,u=t.collectLsofFn??ls,d=t.getEndpoints??ds,f=t.profiler??ps,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(J.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let ee=new Date().toISOString().replace(/[:.]/g,`-`),b=e.output?e.output:v?z(v,`.ok`,`local`,`diagnostics`,`process-${n}-${ee}`):z(process.cwd(),`ok-diagnose-${n}-${ee}`);try{F(b,{recursive:!0})}catch(e){a(J.default.red(`Cannot create output directory ${b}: ${e.message}`));return}a(J.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${b}`),a(``);let x=(e,t)=>{L(z(b,e),t),a(` wrote ${e}`)},te=c(n),S=l(n);x(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:te,usage:S,lockInfo:y},null,2)),a(` sampling lsof`);let C=u(n);if(C&&x(`lsof.txt`,C),!i){let e=C?us(C).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(J.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){x(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,b,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(J.default.yellow(` CPU profile capture failed`)),t.length>0&&x(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
58
- `)}\n`);try{x(`stacks.txt`,ms(I(z(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(b)}`)}async function gs(e){let t=Fn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function _s(e){let t=rn(z(xn(),`ok-bundle-process-`));return await hs({pid:e,output:t}),t}function vs(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function ys(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function bs(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${vs(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function xs(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??gs,i=t.runProcessDiagnose??_s,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=fn(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Lo({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),bs(n,c,o),e.yes!==!0&&!ys(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Ro({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{cn(s,{recursive:!0,force:!0})}catch{}}}function Ss(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await hs({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ss()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-CpxBkx-l.mjs`),{resolveContentDir:r}=await import(`./dist-C7UX8Qzt.mjs`),i=process.cwd(),{config:a}=n(i);await xs({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function Cs(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Ur({message:`Enter OpenAI embeddings API key:`})).trim()}function ws(e){return xe(e)}async function Ts(){return(await We()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function Es(e){try{let t=h(w(e));if(!t||t.port<=0||!x(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function Ds(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await Cs();if(!e){process.stderr.write(`No key provided.
58
+ `)}\n`);try{x(`stacks.txt`,ms(I(z(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(b)}`)}async function gs(e){let t=Fn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function _s(e){let t=rn(z(xn(),`ok-bundle-process-`));return await hs({pid:e,output:t}),t}function vs(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function ys(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function bs(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${vs(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function xs(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??gs,i=t.runProcessDiagnose??_s,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=fn(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Lo({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),bs(n,c,o),e.yes!==!0&&!ys(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Ro({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{cn(s,{recursive:!0,force:!0})}catch{}}}function Ss(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await hs({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ss()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-DD-AnN5t.mjs`),{resolveContentDir:r}=await import(`./dist-Bf8Vy08L.mjs`),i=process.cwd(),{config:a}=n(i);await xs({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function Cs(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Ur({message:`Enter OpenAI embeddings API key:`})).trim()}function ws(e){return xe(e)}async function Ts(){return(await We()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function Es(e){try{let t=h(w(e));if(!t||t.port<=0||!x(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function Ds(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await Cs();if(!e){process.stderr.write(`No key provided.
59
59
  `),process.exitCode=1;return}await Oe().set(e),process.stderr.write(`✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).
60
60
  Now enable it per project — the easiest path is OK Desktop → Settings → This
61
61
  project → Search (a toggle with an egress-confirmation prompt), or run
62
62
  \`ok embeddings enable\` in the project folder.
63
63
  `)})}function Os(){return new t(`clear-key`).description(`Remove your stored OpenAI embeddings API key`).action(async()=>{let{touched:e}=await he();if(e.length===0){process.stderr.write(`No stored OpenAI embeddings key found.
64
64
  `);return}process.stderr.write(`✓ OpenAI embeddings API key cleared (${e.join(`, `)}).\n`)})}function ks(e,n){return new t(e).description(`Turn semantic search ${n?`on`:`off`} for this project (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async t=>{let r=B(t.cwd??process.cwd()),a=await Ie({cwd:r,scope:`project-local`,patch:{search:{semantic:{enabled:n}}}});if(!a.ok){process.stderr.write(`Failed to ${e} semantic search — ${i(a.error)}\n`),process.exitCode=1;return}if(process.stderr.write(`✓ Semantic search ${n?`enabled`:`disabled`} for ${r}\n`),n){let{present:e}=await Ts();e||process.stderr.write(" Note: no API key set yet — run `ok embeddings set-key`. Until then, search stays lexical.\n")}})}function As(){return new t(`status`).description(`Show semantic-search capability: key presence, enabled, coverage, provider`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.cwd??process.cwd()),n=ws(t),{present:r,source:i}=await Ts(),a=n.enabled&&r,o=a?await Es(t):null;if(e.json){process.stdout.write(`${JSON.stringify({project:t,machine:{keyPresent:r,keySource:i},project_config:{enabled:n.enabled,capable:a,coverage:o?{embedded:o.embedded,total:o.total}:null,provider:{baseUrl:n.baseUrl,model:n.model,dimensions:n.dimensions??null}}})}\n`);return}let s=r?`set — ${i===`env`?`environment (${at})`:`~/.ok/secrets.yml`}`:`not set`,c=a?o?`${o.embedded} / ${o.total} pages embedded`:`server not running — start it to index (or it has not embedded yet)`:null,l=[`Semantic search`,` project: ${t}`,``,` This machine (all projects):`,` API key: ${s}`,``,` This project:`,` enabled: ${n.enabled?`yes`:`no`}`,` capability: ${a?`AVAILABLE`:`unavailable (search stays lexical)`}`,...c?[` coverage: ${c}`]:[],` provider: ${n.baseUrl}`,` model: ${n.model}`,` dimensions: ${n.dimensions??`native (1536)`}`],u=[];r||u.push(`Set a key: ok embeddings set-key (or export ${at})`),n.enabled||u.push(`Enable it: ok embeddings enable (in this project folder)`),u.length>0&&l.push(``,...u.map(e=>` ${e}`)),process.stdout.write(`${l.join(`
65
- `)}\n`)})}function js(){return new t(`embeddings`).description(`Manage the semantic-search embeddings provider key + status`).addCommand(Ds()).addCommand(Os()).addCommand(ks(`enable`,!0)).addCommand(ks(`disable`,!1)).addCommand(As())}const Ms=z(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),Ns=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Ps(e,t,n){return e===`darwin`?[z(t,`Applications`,`OpenKnowledge.app`,Ms),z(`/Applications`,`OpenKnowledge.app`,Ms)].find(e=>n.existsSync(e))??null:null}function Fs(e,t,n){if(n!==`darwin`)return{proxy:!1,suppressedBy:`platform`};let r=e.OK_BUNDLE_PROXY?.toLowerCase();return r===`0`||r===`false`?{proxy:!1,suppressedBy:`env`}:t.includes(`--no-bundle-proxy`)?{proxy:!1,suppressedBy:`flag`}:typeof t[1]==`string`&&Ns.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function Is(e){e.stderr.write(`${JSON.stringify({event:`mcp-bundle-proxy`,mode:e.mode,bundlePath:e.bundlePath,reason:e.reason,hint:`Suppress with --no-bundle-proxy or OK_BUNDLE_PROXY=0.`})}\n`)}function Ls(e){Is({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??M,n=e.exitProcess??(e=>process.exit(e)),r=e.now??(()=>Date.now()),i=r(),a=e.startupFailureWindowMs??1e3;return new Promise((o,s)=>{let c=t(e.bundlePath,e.argv.filter(e=>e!==`--no-bundle-proxy`),{env:{...e.env,OK_BUNDLE_PROXY:`0`},stdio:`inherit`}),l=e=>{c.kill(e)},u=()=>{process.off(`SIGTERM`,l),process.off(`SIGINT`,l)};process.on(`SIGTERM`,l),process.on(`SIGINT`,l),c.once(`error`,e=>{u(),s(e)}),c.once(`exit`,(e,t)=>{if(u(),t){s(Error(`bundle process exited by signal ${t}`));return}let o=e??0,c=r()-i;if(o!==0&&c<=a){s(Error(`bundle process exited during startup with code ${o}`));return}n(o)})})}function Rs(e){let t=e.scheduler??{setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e)},n=e.initialBackoffMs??1e3,r=e.maxBackoffMs??3e4,i=e.rng??Math.random,a=e.createWebSocket??(e=>new WebSocket(e)),o=e.logger??null,s=e.log,c=null,l=null,u=!1,d=n;function f(e,t,n){try{o?o[e](t,n):s?.(t)}catch{}}function p(){if(u)return;l!==null&&t.clearTimeout(l);let e=d;d=Math.min(d*2,r);let n=i(),a=Math.max(1,Math.floor(e*(1-n/2)));f(`debug`,`scheduling reconnect`,{backoffMs:a,ceilMs:e}),l=t.setTimeout(()=>{l=null,m().catch(e=>f(`warn`,`reconnect failed`,{error:String(e)}))},a)}async function m(){if(u)return;let t;try{t=await e.resolveWsUrl()}catch(e){f(`warn`,`resolveWsUrl threw`,{error:String(e)}),p();return}if(!t){p();return}let r=e.connectionId?`&connectionId=${encodeURIComponent(e.connectionId)}`:``,i=e.connectionId&&e.displayName!==void 0&&e.clientName!==void 0&&e.colorSeed!==void 0?`&displayName=${encodeURIComponent(e.displayName)}&clientName=${encodeURIComponent(e.clientName)}&colorSeed=${encodeURIComponent(e.colorSeed)}`:``,o=`${t}/collab/keepalive?pid=${process.pid}${r}${i}`;try{c=a(o)}catch(e){f(`warn`,`WebSocket constructor failed`,{url:o,error:String(e)}),c=null,p();return}c.addEventListener(`open`,()=>{f(`info`,`connected`,{url:t}),d=n}),c.addEventListener(`close`,()=>{u||(f(`info`,`disconnected`,{url:t}),c=null,p())}),c.addEventListener(`error`,()=>{f(`debug`,`websocket error observed`,{url:t,readyState:c?.readyState,reason:`error-event`})})}return queueMicrotask(()=>{m().catch(e=>f(`warn`,`initial connect failed`,{error:String(e)}))}),{close:()=>{if(!u&&(u=!0,l!==null&&(t.clearTimeout(l),l=null),c)){try{c.close()}catch{}c=null}},isConnected:()=>c!==null&&c.readyState===1}}var zs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
65
+ `)}\n`)})}function js(){return new t(`embeddings`).description(`Manage the semantic-search embeddings provider key + status`).addCommand(Ds()).addCommand(Os()).addCommand(ks(`enable`,!0)).addCommand(ks(`disable`,!1)).addCommand(As())}const Ms=z(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),Ns=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Ps(e,t,n){return e===`darwin`?[z(t,`Applications`,`OpenKnowledge.app`,Ms),z(`/Applications`,`OpenKnowledge.app`,Ms)].find(e=>n.existsSync(e))??null:null}function Fs(e,t,n){if(n!==`darwin`)return{proxy:!1,suppressedBy:`platform`};let r=e.OK_BUNDLE_PROXY?.toLowerCase();return r===`0`||r===`false`?{proxy:!1,suppressedBy:`env`}:t.includes(`--no-bundle-proxy`)?{proxy:!1,suppressedBy:`flag`}:typeof t[1]==`string`&&Ns.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function Is(e){e.stderr.write(`${JSON.stringify({event:`mcp-bundle-proxy`,mode:e.mode,bundlePath:e.bundlePath,reason:e.reason,hint:`Suppress with --no-bundle-proxy or OK_BUNDLE_PROXY=0.`})}\n`)}function Ls(e){Is({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??M,n=e.exitProcess??(e=>process.exit(e)),r=e.now??(()=>Date.now()),i=r(),a=e.startupFailureWindowMs??1e3;return new Promise((o,s)=>{let c=t(e.bundlePath,e.argv.filter(e=>e!==`--no-bundle-proxy`),{env:{...e.env,OK_BUNDLE_PROXY:`0`},stdio:`inherit`}),l=e=>{c.kill(e)},u=()=>{process.off(`SIGTERM`,l),process.off(`SIGINT`,l)};process.on(`SIGTERM`,l),process.on(`SIGINT`,l),c.once(`error`,e=>{u(),s(e)}),c.once(`exit`,(e,t)=>{if(u(),t){s(Error(`bundle process exited by signal ${t}`));return}let o=e??0,c=r()-i;if(o!==0&&c<=a){s(Error(`bundle process exited during startup with code ${o}`));return}n(o)})})}function Rs(e){let t=e.scheduler??{setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e)},n=e.initialBackoffMs??1e3,r=e.maxBackoffMs??3e4,i=e.rng??Math.random,a=e.createWebSocket??(e=>new WebSocket(e)),o=e.logger??null,s=e.log,c=null,l=null,u=!1,d=n;function f(e,t,n){try{o?o[e](t,n):s?.(t)}catch{}}function p(){if(u)return;l!==null&&t.clearTimeout(l);let e=d;d=Math.min(d*2,r);let n=i(),a=Math.max(1,Math.floor(e*(1-n/2)));f(`debug`,`scheduling reconnect`,{backoffMs:a,ceilMs:e}),l=t.setTimeout(()=>{l=null,m().catch(e=>f(`warn`,`reconnect failed`,{error:String(e)}))},a)}async function m(){if(u)return;let t;try{t=await e.resolveWsUrl()}catch(e){f(`warn`,`resolveWsUrl threw`,{error:String(e)}),p();return}if(!t){p();return}let r=[];e.pid!==void 0&&r.push(`pid=${encodeURIComponent(String(e.pid))}`),e.connectionId&&r.push(`connectionId=${encodeURIComponent(e.connectionId)}`),e.connectionId&&e.displayName!==void 0&&e.clientName!==void 0&&e.colorSeed!==void 0&&(r.push(`displayName=${encodeURIComponent(e.displayName)}`),r.push(`clientName=${encodeURIComponent(e.clientName)}`),r.push(`colorSeed=${encodeURIComponent(e.colorSeed)}`));let i=r.length>0?`?${r.join(`&`)}`:``,o=`${t}/collab/keepalive${i}`;try{c=a(o)}catch(e){f(`warn`,`WebSocket constructor failed`,{url:o,error:String(e)}),c=null,p();return}c.addEventListener(`open`,()=>{f(`info`,`connected`,{url:t}),d=n}),c.addEventListener(`close`,()=>{u||(f(`info`,`disconnected`,{url:t}),c=null,p())}),c.addEventListener(`error`,()=>{f(`debug`,`websocket error observed`,{url:t,readyState:c?.readyState,reason:`error-event`})})}return queueMicrotask(()=>{m().catch(e=>f(`warn`,`initial connect failed`,{error:String(e)}))}),{close:()=>{if(!u&&(u=!0,l!==null&&(t.clearTimeout(l),l=null),c)){try{c.close()}catch{}c=null}},isConnected:()=>c!==null&&c.readyState===1}}var zs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
66
66
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Bs(t)}clear(){this._buffer=void 0}};function Bs(e){return Je.parse(JSON.parse(e))}function Vs(e){return JSON.stringify(e)+`
67
67
  `}var Hs=class{constructor(e=hn.stdin,t=hn.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new zs,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Vs(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function Us(e){if(e.platform!==`darwin`)return{kind:`unchanged`};let t;try{t=e.realpath(e.bundleAnchorPath)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}let n;try{n=e.statInode(t)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}return n===e.currentInode?{kind:`unchanged`}:{kind:`replaced`,currentInode:e.currentInode,onDiskInode:n}}function Ws(e){let t=e.setInterval??setInterval,n=e.clearInterval??clearInterval,r=e.intervalMs??3e5,i=!0,a=!1,o=!1,s=t(()=>{if(!i)return;let t;try{t=e.detect()}catch(t){e.log(`bundle identity check threw unexpectedly (contract violation): ${t instanceof Error?t.message:String(t)}`);return}if(t.kind===`unreadable`){o||(o=!0,e.log(`bundle identity check unreadable${t.reason?`: ${t.reason}`:``} — will retry on next tick`));return}o&&(o=!1,e.log(`bundle identity check recovered from unreadable`)),t.kind!==`unchanged`&&(i=!1,e.onReplaced(t))},r);return typeof s.unref==`function`&&s.unref(),{stop:()=>{a||(a=!0,i=!1,n(s))}}}function Gs(e,t){let n;try{n=t.realpathSync(e)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (realpath failed): ${e instanceof Error?e.message:String(e)}`);return}let r;try{r=t.statInoSync(n)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (stat failed): ${e instanceof Error?e.message:String(e)}`);return}return{resolvedPath:n,inode:r}}function Ks(e){let t=e.scheduler??{setInterval:(e,t)=>globalThis.setInterval(e,t),clearInterval:e=>globalThis.clearInterval(e)},n=e.getPpid();if(n<=1)return{stop:()=>{}};let r=!1,i=t.setInterval(()=>{if(r)return;let a=e.getPpid();a!==n&&(r=!0,t.clearInterval(i),e.onHostGone(`host process exited (ppid ${n} -> ${a})`))},e.intervalMs??1e3);return i.unref?.(),{stop:()=>t.clearInterval(i)}}function qs(e){let t=t=>{try{e.log(t)}catch{}},n=e.transport.onclose;e.transport.onclose=()=>{t(`[mcp] stdio transport closed (internal shutdown)`),n?.()},e.stdin.once(`end`,()=>t(`[mcp] stdin EOF (host closed pipe)`)),e.stdin.once(`close`,()=>t(`[mcp] stdin closed`)),e.process.on(`exit`,e=>{t(`[mcp] exit code=${e}`)}),e.process.on(`uncaughtExceptionMonitor`,(e,n)=>{t(`[mcp] uncaughtException origin=${n}: ${e instanceof Error?e.stack??e.message:String(e)}`)})}function Js(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Ys(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Js(t.headers),...Js(r.headers)}:t.headers}):e}let Xs;Xs=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Zs(e){return(await Xs).getRandomValues(new Uint8Array(e))}async function Qs(e){let t=``;for(;t.length<e;){let n=await Zs(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function $s(e){return await Qs(e)}async function ec(e){let t=await(await Xs).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function tc(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await $s(e);return{code_verifier:t,code_challenge:await ec(t)}}const X=v().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:In.custom,message:`URL must be parseable`,fatal:!0}),s}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),nc=b({resource:g().url(),authorization_servers:m(X).optional(),jwks_uri:g().url().optional(),scopes_supported:m(g()).optional(),bearer_methods_supported:m(g()).optional(),resource_signing_alg_values_supported:m(g()).optional(),resource_name:g().optional(),resource_documentation:g().optional(),resource_policy_uri:g().url().optional(),resource_tos_uri:g().url().optional(),tls_client_certificate_bound_access_tokens:C().optional(),authorization_details_types_supported:m(g()).optional(),dpop_signing_alg_values_supported:m(g()).optional(),dpop_bound_access_tokens_required:C().optional()}),rc=b({issuer:g(),authorization_endpoint:X,token_endpoint:X,registration_endpoint:X.optional(),scopes_supported:m(g()).optional(),response_types_supported:m(g()),response_modes_supported:m(g()).optional(),grant_types_supported:m(g()).optional(),token_endpoint_auth_methods_supported:m(g()).optional(),token_endpoint_auth_signing_alg_values_supported:m(g()).optional(),service_documentation:X.optional(),revocation_endpoint:X.optional(),revocation_endpoint_auth_methods_supported:m(g()).optional(),revocation_endpoint_auth_signing_alg_values_supported:m(g()).optional(),introspection_endpoint:g().optional(),introspection_endpoint_auth_methods_supported:m(g()).optional(),introspection_endpoint_auth_signing_alg_values_supported:m(g()).optional(),code_challenge_methods_supported:m(g()).optional(),client_id_metadata_document_supported:C().optional()}),ic=p({...b({issuer:g(),authorization_endpoint:X,token_endpoint:X,userinfo_endpoint:X.optional(),jwks_uri:X,registration_endpoint:X.optional(),scopes_supported:m(g()).optional(),response_types_supported:m(g()),response_modes_supported:m(g()).optional(),grant_types_supported:m(g()).optional(),acr_values_supported:m(g()).optional(),subject_types_supported:m(g()),id_token_signing_alg_values_supported:m(g()),id_token_encryption_alg_values_supported:m(g()).optional(),id_token_encryption_enc_values_supported:m(g()).optional(),userinfo_signing_alg_values_supported:m(g()).optional(),userinfo_encryption_alg_values_supported:m(g()).optional(),userinfo_encryption_enc_values_supported:m(g()).optional(),request_object_signing_alg_values_supported:m(g()).optional(),request_object_encryption_alg_values_supported:m(g()).optional(),request_object_encryption_enc_values_supported:m(g()).optional(),token_endpoint_auth_methods_supported:m(g()).optional(),token_endpoint_auth_signing_alg_values_supported:m(g()).optional(),display_values_supported:m(g()).optional(),claim_types_supported:m(g()).optional(),claims_supported:m(g()).optional(),service_documentation:g().optional(),claims_locales_supported:m(g()).optional(),ui_locales_supported:m(g()).optional(),claims_parameter_supported:C().optional(),request_parameter_supported:C().optional(),request_uri_parameter_supported:C().optional(),require_request_uri_registration:C().optional(),op_policy_uri:X.optional(),op_tos_uri:X.optional(),client_id_metadata_document_supported:C().optional()}).shape,...rc.pick({code_challenge_methods_supported:!0}).shape}),ac=p({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:Rn().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),oc=p({error:g(),error_description:g().optional(),error_uri:g().optional()}),sc=X.optional().or(f(``).transform(()=>void 0)),cc=p({redirect_uris:m(X),token_endpoint_auth_method:g().optional(),grant_types:m(g()).optional(),response_types:m(g()).optional(),client_name:g().optional(),client_uri:X.optional(),logo_uri:sc,scope:g().optional(),contacts:m(g()).optional(),tos_uri:sc,policy_uri:g().optional(),jwks_uri:X.optional(),jwks:n().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),lc=p({client_id:g(),client_secret:g().optional(),client_id_issued_at:S().optional(),client_secret_expires_at:S().optional()}).strip(),uc=cc.merge(lc);p({error:g(),error_description:g().optional()}).strip(),p({token:g(),token_type_hint:g().optional()}).strip();function dc(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function fc({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Z=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},pc=class extends Z{};pc.errorCode=`invalid_request`;var mc=class extends Z{};mc.errorCode=`invalid_client`;var hc=class extends Z{};hc.errorCode=`invalid_grant`;var gc=class extends Z{};gc.errorCode=`unauthorized_client`;var _c=class extends Z{};_c.errorCode=`unsupported_grant_type`;var vc=class extends Z{};vc.errorCode=`invalid_scope`;var yc=class extends Z{};yc.errorCode=`access_denied`;var bc=class extends Z{};bc.errorCode=`server_error`;var xc=class extends Z{};xc.errorCode=`temporarily_unavailable`;var Sc=class extends Z{};Sc.errorCode=`unsupported_response_type`;var Cc=class extends Z{};Cc.errorCode=`unsupported_token_type`;var wc=class extends Z{};wc.errorCode=`invalid_token`;var Tc=class extends Z{};Tc.errorCode=`method_not_allowed`;var Ec=class extends Z{};Ec.errorCode=`too_many_requests`;var Dc=class extends Z{};Dc.errorCode=`invalid_client_metadata`;var Oc=class extends Z{};Oc.errorCode=`insufficient_scope`;var kc=class extends Z{};kc.errorCode=`invalid_target`;const Ac={[pc.errorCode]:pc,[mc.errorCode]:mc,[hc.errorCode]:hc,[gc.errorCode]:gc,[_c.errorCode]:_c,[vc.errorCode]:vc,[yc.errorCode]:yc,[bc.errorCode]:bc,[xc.errorCode]:xc,[Sc.errorCode]:Sc,[Cc.errorCode]:Cc,[wc.errorCode]:wc,[Tc.errorCode]:Tc,[Ec.errorCode]:Ec,[Dc.errorCode]:Dc,[Oc.errorCode]:Oc,[kc.errorCode]:kc};var jc=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Mc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Nc=`code`,Pc=`S256`;function Fc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Mc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Ic(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Lc(i,a,n);return;case`client_secret_post`:Rc(i,a,r);return;case`none`:zc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Lc(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Rc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function zc(e,t){t.set(`client_id`,e)}async function Bc(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=oc.parse(JSON.parse(n));return new(Ac[e]||bc)(t||``,r)}catch(e){return new bc(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function Vc(e,t){try{return await Hc(e,t)}catch(n){if(n instanceof mc||n instanceof gc)return await e.invalidateCredentials?.(`all`),await Hc(e,t);if(n instanceof hc)return await e.invalidateCredentials?.(`tokens`),await Hc(e,t);throw n}}async function Hc(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await el(c,{fetchFn:a}),!s)try{s=await qc(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await tl(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await Wc(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!Uc(r))throw new Dc(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await sl(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await ol(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await al(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof Z)||e instanceof bc))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await nl(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function Uc(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Wc(e,t,n){let r=dc(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!fc({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Gc(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Kc(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Kc(e,`scope`)||void 0,s=Kc(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Kc(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function qc(e,t,n=fetch){let r=await Qc(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return nc.parse(await r.json())}async function Jc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Jc(e,void 0,n):void 0;throw r}}function Yc(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Xc(e,t,n=fetch){return await Jc(e,{"MCP-Protocol-Version":t},n)}function Zc(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Qc(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Yc(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Xc(o,a,n);return!r?.metadataUrl&&Zc(s,i.pathname)&&(s=await Xc(new URL(`/.well-known/${t}`,i),a,n)),s}function $c(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function el(e,{fetchFn:t=fetch,protocolVersion:n=$e}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=$c(e);for(let{url:e,type:n}of i){let i=await Jc(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?rc.parse(await i.json()):ic.parse(await i.json())}}}async function tl(e,t){let n,r;try{n=await qc(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await el(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function nl(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Nc))throw Error(`Incompatible auth server: does not support response type ${Nc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Pc))throw Error(`Incompatible auth server: does not support code challenge method ${Pc}`)}else s=new URL(`/authorize`,e);let c=await tc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Nc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Pc),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function rl(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function il(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Ic(Fc(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Bc(l);return ac.parse(await l.json())}async function al(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await il(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function ol(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=rl(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return il(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function sl(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await Bc(o);return uc.parse(await o.json())}var cl=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ll(e){}function ul(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ll,onError:n=ll,onRetry:r=ll,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=dl(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
68
68
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new cl(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new cl(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
69
69
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function dl(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
70
70
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
71
- `&&r++}}return[t,n]}var fl=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=ul({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const pl={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var ml=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},hl=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Ys(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??pl}async _authThenStart(){if(!this._authProvider)throw new jc(`No auth provider`);let e;try{e=await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new jc;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Js(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new ml(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new fl({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Je.parse(JSON.parse(e.data));Ye(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new jc(`No auth provider`);if(await Vc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new jc(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ae(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ml(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Gc(o);if(this._resourceMetadataUrl=t,this._scope=n,await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new jc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Gc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new ml(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new jc;return this.send(e)}}throw new ml(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),He(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Je.parse(e)):[Je.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new ml(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new ml(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function gl(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function _l(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function vl(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function yl(e,t){return`http://${vl(e)}:${t}/mcp`}function bl(e,t){return`ws://${vl(e)}:${t}`}function xl(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Sl(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Cl(e){return P(e)?I(e,`utf-8`).trim():``}function wl(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Tl(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function El(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function Dl(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Ol(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??x,r=e.sleep??(e=>kn(e)),i=e.spawn??M,a=e.readErrorLog??Cl,o=e.openErrorLog??(e=>an(e,`w`)),s=e.closeFd??$t,c=e.timeoutMs??5e3,u=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return yl(`localhost`,t)}let d=Sl(t(),n);if(d!==void 0)return yl(`localhost`,d);if(e.envAutoStart===`0`)throw new Fe(`OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||F(e.lockDir,{recursive:!0});let f=z(e.lockDir,l),p=o(f),m,g,_=Jt();try{try{m=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),m.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}await r(u);let e=Sl(t(),n);if(e!==void 0)return yl(`localhost`,e)}if(g){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}throw Error(wl(c,a(f)))}function kl(e,t){if(e.portOverride!==void 0)return xl(t);let n=e.readLock??(()=>h(e.lockDir)),r=e.isAlive??x,i=Sl(n(),r);if(i!==void 0)return bl(`localhost`,i)}async function Al(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Hs(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new hl(new URL(e),{fetch:gl(r),requestInit:{headers:{...ne({kind:`mcp`,runtimeVersion:y}),...t.connectionId===void 0?{}:{[be]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let c=Promise.resolve();i.onmessage=e=>{c=c.then(async()=>{try{await a.send(e)}catch(t){let r=Tl(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(Dl(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=El(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function jl(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Al,r=await Ol(e),i=e.createConnectionId?.()??On(),a=!1,o=(e.startKeepalive??Rs)({connectionId:i,resolveWsUrl:async()=>kl(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}const Ml=Tn(import.meta.url),Nl=An(Xt);async function Pl(e){try{let{stdout:t}=await Nl(`git`,[`-C`,e,`worktree`,`list`,`--porcelain`],{timeout:2e3});return t.split(`
72
- `).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function Fl(e){let t=B(e);for(;;){if(je(t))return t;let n=fn(t);if(n===t)throw Error(`No OpenKnowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${a}\`).`);t=n}}function Il(e){try{let t=new URL(e);return t.protocol===`file:`?Tn(t):void 0}catch{return}}async function Ll(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Il(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Rl(e,t,n,r=Fl){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function zl(e){let t=process.stderr,n=e.spawnTimeoutMs??_l(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Vt({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new nt({name:ee,version:y});ve(a);let o=On(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=ue(e),r=s.current,i=Rs({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>kl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Ll({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d,f=!1,p=async e=>{if(f)return;f=!0;let n=await Pl(e);if(n<=1){f=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${n} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{t.write(`[mcp] ${r}\n`),await a.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},m=async e=>{let t=await Rl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an OpenKnowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&p(t.projectDir),t.projectDir},h=async e=>{let t=await Rl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)return;t.viaRootGuess&&p(t.projectDir);let a=t.projectDir,o=await i(a),s=await Ol({lockDir:ue(a),contentDir:Ee(o,a),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(a),s.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Ke(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},we(a,{serverUrl:h,resolveCwd:m,config:i,identityRef:s});let g=new Hs,_=!1,v,b,x=async()=>{if(_)return;_=!0,v?.stop(),b?.stop();for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),g.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await a.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
71
+ `&&r++}}return[t,n]}var fl=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=ul({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const pl={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var ml=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},hl=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Ys(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??pl}async _authThenStart(){if(!this._authProvider)throw new jc(`No auth provider`);let e;try{e=await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new jc;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Js(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new ml(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new fl({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Je.parse(JSON.parse(e.data));Ye(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new jc(`No auth provider`);if(await Vc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new jc(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ae(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ml(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Gc(o);if(this._resourceMetadataUrl=t,this._scope=n,await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new jc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Gc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new ml(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Vc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new jc;return this.send(e)}}throw new ml(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),He(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Je.parse(e)):[Je.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new ml(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new ml(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function gl(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function _l(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function vl(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function yl(e,t){return`http://${vl(e)}:${t}/mcp`}function bl(e,t){return`ws://${vl(e)}:${t}`}function xl(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Sl(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Cl(e){return P(e)?I(e,`utf-8`).trim():``}function wl(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Tl(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function El(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function Dl(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Ol(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??x,r=e.sleep??(e=>kn(e)),i=e.spawn??M,a=e.readErrorLog??Cl,o=e.openErrorLog??(e=>an(e,`w`)),s=e.closeFd??$t,c=e.timeoutMs??5e3,u=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return yl(`localhost`,t)}let d=Sl(t(),n);if(d!==void 0)return yl(`localhost`,d);if(e.envAutoStart===`0`)throw new Fe(`OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||F(e.lockDir,{recursive:!0});let f=z(e.lockDir,l),p=o(f),m,g,_=Jt();try{try{m=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),m.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}await r(u);let e=Sl(t(),n);if(e!==void 0)return yl(`localhost`,e)}if(g){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}throw Error(wl(c,a(f)))}function kl(e,t){if(e.portOverride!==void 0)return xl(t);let n=e.readLock??(()=>h(e.lockDir)),r=e.isAlive??x,i=Sl(n(),r);if(i!==void 0)return bl(`localhost`,i)}async function Al(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Hs(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new hl(new URL(e),{fetch:gl(r),requestInit:{headers:{...ne({kind:`mcp`,runtimeVersion:y}),...t.connectionId===void 0?{}:{[be]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let c=Promise.resolve();i.onmessage=e=>{c=c.then(async()=>{try{await a.send(e)}catch(t){let r=Tl(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(Dl(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=El(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function jl(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Al,r=await Ol(e),i=e.createConnectionId?.()??On(),a=!1,o=(e.startKeepalive??Rs)({connectionId:i,pid:process.pid,resolveWsUrl:async()=>kl(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}const Ml=Tn(import.meta.url),Nl=An(Xt);async function Pl(e){try{let{stdout:t}=await Nl(`git`,[`-C`,e,`worktree`,`list`,`--porcelain`],{timeout:2e3});return t.split(`
72
+ `).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function Fl(e){let t=B(e);for(;;){if(je(t))return t;let n=fn(t);if(n===t)throw Error(`No OpenKnowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${a}\`).`);t=n}}function Il(e){try{let t=new URL(e);return t.protocol===`file:`?Tn(t):void 0}catch{return}}async function Ll(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Il(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Rl(e,t,n,r=Fl){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function zl(e){let t=process.stderr,n=e.spawnTimeoutMs??_l(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Vt({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new nt({name:ee,version:y});ve(a);let o=On(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=ue(e),r=s.current,i=Rs({connectionId:o,pid:process.pid,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>kl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Ll({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d,f=!1,p=async e=>{if(f)return;f=!0;let n=await Pl(e);if(n<=1){f=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${n} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{t.write(`[mcp] ${r}\n`),await a.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},m=async e=>{let t=await Rl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an OpenKnowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&p(t.projectDir),t.projectDir},h=async e=>{let t=await Rl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)return;t.viaRootGuess&&p(t.projectDir);let a=t.projectDir,o=await i(a),s=await Ol({lockDir:ue(a),contentDir:Ee(o,a),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(a),s.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Ke(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},we(a,{serverUrl:h,resolveCwd:m,config:i,identityRef:s});let g=new Hs,_=!1,v,b,x=async()=>{if(_)return;_=!0,v?.stop(),b?.stop();for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),g.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await a.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
73
73
  `);let te=!1,S=()=>{te||(te=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
74
74
  `),process.exit(1)},5e3).unref(),x().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,S),process.once(`SIGTERM`,S),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
75
- `),S()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),S()}),b=Ks({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),S()}}),qs({log:e=>t.write(`${e}\n`),transport:g,process,stdin:process.stdin}),process.platform===`darwin`){let e=Gs(Ml,{realpathSync:sn,statInoSync:e=>ln(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${y}\n`);let{resolvedPath:n,inode:r}=e;v=Ws({detect:()=>Us({bundleAnchorPath:Ml,currentInode:r,platform:process.platform,realpath:sn,statInode:e=>ln(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${y} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function Bl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=_l(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await jl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Fs(process.env,i,process.platform);if(a.proxy){let e=Ps(process.platform,vn(),{existsSync:P});if(e===null)Is({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed OpenKnowledge.app bundle found`});else try{await Ls({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Is({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Is({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await zl({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Vl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Hl(e=()=>qt(Gt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>rt({lockDir:w(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Vl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Ul(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No OpenKnowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Ve(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the OpenKnowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No OpenKnowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Wl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Ul(e,t,Hl())})}function Gl(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DmtYPtUD.mjs`),r=e(),i=process.cwd(),a=Ee(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Kl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function ql(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(w(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...ne({kind:`cli`,runtimeVersion:y})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Kl(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=ce({baseDir:n});if(r===`sync`||r===`pull`){Kl(e.json,{type:`step`,step:`pull`});let t=await a.pull();Kl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Kl(e.json,{type:`step`,step:`push`}),await a.push(),Kl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
75
+ `),S()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),S()}),b=Ks({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),S()}}),qs({log:e=>t.write(`${e}\n`),transport:g,process,stdin:process.stdin}),process.platform===`darwin`){let e=Gs(Ml,{realpathSync:sn,statInoSync:e=>ln(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${y}\n`);let{resolvedPath:n,inode:r}=e;v=Ws({detect:()=>Us({bundleAnchorPath:Ml,currentInode:r,platform:process.platform,realpath:sn,statInode:e=>ln(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${y} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function Bl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=_l(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await jl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Fs(process.env,i,process.platform);if(a.proxy){let e=Ps(process.platform,vn(),{existsSync:P});if(e===null)Is({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed OpenKnowledge.app bundle found`});else try{await Ls({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Is({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Is({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await zl({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Vl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Hl(e=()=>qt(Gt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>rt({lockDir:w(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Vl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Ul(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No OpenKnowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Ve(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the OpenKnowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No OpenKnowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Wl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Ul(e,t,Hl())})}function Gl(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-BEK2Jwjs.mjs`),r=e(),i=process.cwd(),a=Ee(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Kl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function ql(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(w(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...ne({kind:`cli`,runtimeVersion:y})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Kl(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=ce({baseDir:n});if(r===`sync`||r===`pull`){Kl(e.json,{type:`step`,step:`pull`});let t=await a.pull();Kl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Kl(e.json,{type:`step`,step:`push`}),await a.push(),Kl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
76
76
  `)),Kl(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Jl(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await ql({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 Yl(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await ql({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 Xl(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await ql({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 Zl(e){return typeof e==`string`&&Re.includes(e)}async function Ql(e={}){let t=B(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!le[n])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${n}". Available: ${Re.join(`, `)}`,exitCode:1};let r;try{r=await me({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof et?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=le[n].name;return{status:`no-op`,message:`${O(`Your ${e} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun){let e=pe(le[n]);return{status:`dry-run`,message:`${j(`Reference this pack for inspiration (dry-run — no changes made):`)}\n\n${e}\n\n${j(`Plan:`)}\n\n${eu(r,t)}`,plan:r,exitCode:0}}if(!e.yes&&!await tu(`${j(`Plan:`)}\n\n${eu(r,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:r,exitCode:0};let i=await ke(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${i.applied} entries, ${A(String(i.errors.length))} error(s):`,...e].join(`
77
77
  `),plan:r,exitCode:1}}let a=le[n].name,o=i.packSkillsInstalled.length>0?`\n${D(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${O(`✓ Seeded ${a}`)} ${D(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function $l(){let e=[j(`Available packs:`)];for(let t of Re){let n=le[t];e.push(` ${O(t)} ${D(`—`)} ${n.name}: ${n.description}`)}return e.join(`
78
78
  `)}function eu(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(j(`Folders to create:`));for(let e of r)n.push(` ${O(`+`)} ${E(pn(t,B(t,e.path))||e.path)}${D(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(j(`Files to create:`));for(let e of i)n.push(` ${O(`+`)} ${E(pn(t,B(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(D(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${D(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(A(`Warnings:`));for(let t of e.warnings)n.push(` ${A(`!`)} ${t}`)}return n.join(`
@@ -81,7 +81,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
81
81
  `);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function au(e){return new t(`name-check`).description(`Check if owner/name is available on GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await iu(t,await e())})}async function ou(e){try{let t=[],n=await e.users.getAuthenticated();t.push({login:n.data.login,kind:`user`,avatarUrl:n.data.avatar_url});for await(let n of e.paginate.iterator(e.orgs.listMembershipsForAuthenticatedUser,{state:`active`,per_page:100}))for(let e of n.data)(e.permissions?.can_create_repository===!0||e.role===`admin`)&&t.push({login:e.organization.login,kind:`org`,avatarUrl:e.organization.avatar_url??void 0});return{kind:`ok`,owners:t}}catch(e){return e.status===401?{kind:`auth-required`}:{kind:`network`}}}async function su(e,t){let{host:n,json:r}=e;H(n);let i=await zi(n,t);if(i==null){if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=await ou(new K({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function cu(e){return new t(`owners`).description(`List GitHub owners eligible to host a new repository`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await su(t,await e())})}function lu(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
82
82
  `)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function uu(e){let{octokit:t,ownerLogin:n,ownerKind:r,name:i,visibility:a,description:o}=e,s=a===`private`;if(r===`user`){let{data:e}=await t.repos.createForAuthenticatedUser({name:i,private:s,...o?{description:o}:{}});return{cloneUrl:e.clone_url,defaultBranch:e.default_branch??`main`}}let{data:c}=await t.repos.createInOrg({org:n,name:i,visibility:a,...o?{description:o}:{}});return{cloneUrl:c.clone_url,defaultBranch:c.default_branch??`main`}}async function du(e,t,n){try{let{data:r}=await e.repos.get({owner:t,repo:n});return{cloneUrl:r.clone_url,defaultBranch:r.default_branch??`main`}}catch{return null}}async function fu(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function pu(e){return ce({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function mu(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const hu={ensureOkScaffold:e=>{_e(e)},gitFactory:pu};async function gu(e){let t={...hu,...e.deps},n=B(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await fu(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:lu(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!P(z(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await uu({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(lu(t)===`name-conflict`){let t=await du(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:lu(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=mu(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function _u(e,t){if(!e){t.kind===`ok`?process.stdout.write(`✓ Published ${t.value.cloneUrl}\n`):(process.stderr.write(`✗ share publish failed: ${t.code}\n`),process.exit(1));return}if(t.kind===`ok`){process.stdout.write(`${JSON.stringify({type:`publish`,...t.value})}\n`);return}process.stdout.write(`${JSON.stringify({type:`error`,code:t.code})}\n`)}async function vu(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;H(n);let l=await zi(n,t);if(l==null){_u(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new K({auth:l,...u?{baseUrl:u}:{}});try{Zt(`git config user.email`,{cwd:s,stdio:`ignore`})}catch{process.env.GIT_AUTHOR_NAME??=`OpenKnowledge`,process.env.GIT_AUTHOR_EMAIL??=`noreply@inkeep.com`,process.env.GIT_COMMITTER_NAME??=`OpenKnowledge`,process.env.GIT_COMMITTER_EMAIL??=`noreply@inkeep.com`}_u(c,await gu({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function yu(e){return new t(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
83
83
  `),process.exit(1)),await vu(t,await e())})}function bu(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>oe();return e.addCommand(cu(n)),e.addCommand(au(n)),e.addCommand(yu(n)),e}function xu(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=St(t),r=pt(t,dt(t));if(r.kind===`no-exclude`){Su(e.json,t,r.reason);return}let i=St(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${E(`Sharing mode is already`)} ${j(`shared`)} ${E(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${j(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function Su(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Cu(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=St(t),r=[...xt(t)],i=Ot(t,dt(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`OpenKnowledge sharing mode: ${wu(n)}`),a.push(``),a.push(`Excluded from git via ${j(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${E(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
84
- `)}\n`)})}function wu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function Tu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=Ct(t,dt(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){Eu(e.json,t,n.reason);return}let r=St(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Eu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Du(){let e=new t(`config-sharing`);return e.description(`Manage OpenKnowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(xu()),e.addCommand(Tu()),e.addCommand(Cu()),e}const Ou=new Set([`--cwd`,`--log-level`]);function ku(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){Ou.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Au(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ju(e){return/\.(md|mdx)$/i.test(e)}function Mu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Nu(e=()=>qt(Gt())){return{prepare:Ce,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Mu(process.env)}).unref()},runProjectOpen:(e,t)=>Ul(e,{project:t},Hl()),runBrowserOpen:e=>Iu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Pu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ze||e instanceof Me||e instanceof tt)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the OpenKnowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function Fu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function Iu(e){let{createEphemeralProjectDir:t}=await import(`./dist-C7UX8Qzt.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-DYwAiJfq.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=Fu();o||(process.stderr.write("OpenKnowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await En(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${qe(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
84
+ `)}\n`)})}function wu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function Tu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=Ct(t,dt(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){Eu(e.json,t,n.reason);return}let r=St(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Eu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Du(){let e=new t(`config-sharing`);return e.description(`Manage OpenKnowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(xu()),e.addCommand(Tu()),e.addCommand(Cu()),e}const Ou=new Set([`--cwd`,`--log-level`]);function ku(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){Ou.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Au(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ju(e){return/\.(md|mdx)$/i.test(e)}function Mu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Nu(e=()=>qt(Gt())){return{prepare:Ce,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Mu(process.env)}).unref()},runProjectOpen:(e,t)=>Ul(e,{project:t},Hl()),runBrowserOpen:e=>Iu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Pu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ze||e instanceof Me||e instanceof tt)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the OpenKnowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function Fu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function Iu(e){let{createEphemeralProjectDir:t}=await import(`./dist-Bf8Vy08L.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-DGfnJdwS.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=Fu();o||(process.stderr.write("OpenKnowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await En(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${qe(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
85
85
  `),a(m),await new Promise(()=>{})}function Lu(){let e=new t(`skills`).description(`Manage Open Knowledge skills for this project.`);return e.command(`manage`).description(`Control whether OK adopts your editor skills into this project. Default: off — OK only manages skills already under .ok/skills.`).option(`--on`,`Make this project OK-managed: import existing editor skills and adopt new ones.`).option(`--off`,`Stop adopting editor skills (non-destructive — existing .ok/skills + symlinks stay).`).option(`--status`,`Print the current setting.`).action(async e=>{let t=B(process.cwd());if([e.on,e.off,e.status].filter(Boolean).length!==1){process.stderr.write(`${k(`Error:`)} pass exactly one of --on, --off, --status.\n`),process.exitCode=1;return}if(e.status){let e=Xe(t);process.stdout.write(`Skill management for ${j(t)}: ${e?O(`on`):D(`off (default)`)}\n`);return}let n=!!e.on;try{await De(t,{manageEditorSkills:n,surface:`cli`})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${k(`Error:`)} could not write skill-management marker: ${t}\n`),process.exitCode=1;return}process.stdout.write(n?`${O(`OK now manages skills for this project.`)} Existing editor skills are imported into ${j(`.ok/skills`)} on the next ${j(`ok start`)} / project open, and new ones adopted automatically.\n`:`${E(`OK will no longer adopt editor skills here.`)} Existing ${j(`.ok/skills`)} content + symlinks are left intact.\n`)}),e}function Ru(e,t){return{server:zu(`server`,e),ui:zu(`ui`,t)}}function zu(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 Bu(e){return`${Vu(e.server)}\n${Vu(e.ui)}`}function Vu(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 Hu(e){let t=e.inspect??(t=>jt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Ru(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Bu(r)),r}function Uu(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),Hu({lockDir:w(process.cwd()),json:t.json===!0})})}function Wu(e){return[e,`Copyright (C) 2026 Inkeep, Inc.`,`License GPL-3.0-or-later: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.`,`This is free software: you are free to change and redistribute it.`,`There is NO WARRANTY, to the extent permitted by law.`].join(`
86
86
  `)}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 t;let $,Gu;function Ku(){return Gu}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Wu(Rt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=Ft(n,process.cwd());r!==null&&(kt(process.cwd()),process.chdir(r),console.error(`[ok] Using OpenKnowledge project at ${r}`));let{config:i}=Bt(r??t);$=i;let a=e.args?.[0]??e.name()??`cli`;Gu=Le({name:`cli`,project:i.project?.name??void 0}),Gu.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(qt(Gt()).available){Ut({spawn:M});return}await Kt($,{})});const qu=Wt(()=>$);Q.addCommand(qu);const Ju=Bl(()=>$);Q.addCommand(Ju),Q.addCommand(Et()),Q.addCommand(nu()),Q.addCommand(Ka(),{hidden:!0}),Q.addCommand(Yt()),Q.addCommand(Lu());const Yu=Gl(()=>$);Q.addCommand(Yu);const Xu=Dt(()=>$);Q.addCommand(Xu),Q.addCommand(Wl()),Q.addCommand(Mt(()=>$)),Q.addCommand(la(()=>$)),Q.addCommand(Uu(()=>$)),Q.addCommand(It()),Q.addCommand(Ss()),Q.addCommand(oa()),Q.addCommand(Ra()),Q.addCommand(Ji(Ku)),Q.addCommand(js()),Q.addCommand(Aa(()=>$)),Q.addCommand(Jl(()=>$)),Q.addCommand(Xl(()=>$)),Q.addCommand(Yl(()=>$)),Q.addCommand(bu()),Q.addCommand(Du()),Q.addHelpText(`after`,`
87
87
  Examples:
@@ -0,0 +1,2 @@
1
+ import"./server-lock-CN2YHwpP-COM23IWb.mjs";var e=`0.20.0-beta.9`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-nTyY9ahE.mjs.map
@@ -1 +1 @@
1
- import{Fi as e,Gt as t,Hi as n,In as r,Y as i,a,c as o,d as s,di as c,dn as l,f as u,g as d,gn as f,h as p,i as m,jn as h,l as g,m as _,n as v,o as y,on as b,p as x,r as S,s as C,t as w,u as T}from"./server-lock-CN2YHwpP-COM23IWb.mjs";import{$ as E,$i as D,$n as O,$r as k,$t as A,A as j,Ai as M,An as N,Ar as P,At as F,B as I,Bi as L,Bn as R,Br as z,Bt as B,C as V,Ci as H,Cn as U,Cr as W,Ct as G,D as K,Di as q,Dn as J,Dr as Y,Dt as X,E as Z,Ei as Q,En as $,Er as ee,Et as te,F as ne,Fi as re,Fn as ie,Fr as ae,Ft as oe,G as se,Gi as ce,Gn as le,Gr as ue,Gt as de,H as fe,Hi as pe,Hn as me,Hr as he,Ht as ge,I as _e,Ii as ve,In as ye,Ir as be,It as xe,J as Se,Ji as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,Oi as Je,On as Ye,Or as Xe,Ot as Ze,P as Qe,Pi as $e,Pn as et,Pr as tt,Pt as nt,Q as rt,Qi as it,Qn as at,Qr as ot,Qt as st,R as ct,Ri as lt,Rn as ut,Rr as dt,Rt as ft,S as pt,Si as mt,Sn as ht,Sr as gt,St as _t,T as vt,Ti as yt,Tn as bt,Tr as xt,Tt as St,U as Ct,Ui as wt,Un as Tt,Ur as Et,Ut as Dt,V as Ot,Vi as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wi as Pt,Wn as Ft,Wr as It,Wt as Lt,X as Rt,Xi as zt,Xn as Bt,Xr as Vt,Xt as Ht,Y as Ut,Yi as Wt,Yn as Gt,Yr as Kt,Yt as qt,Z as Jt,Zi as Yt,Zn as Xt,Zr as Zt,Zt as Qt,_ as $t,_i as en,_n as tn,_r as nn,_t as rn,a as an,ai as on,an as sn,ar as cn,at as ln,b as un,bi as dn,bn as fn,br as pn,bt as mn,c as hn,ci as gn,cn as _n,cr as vn,ct as yn,d as bn,di as xn,dn as Sn,dr as Cn,dt as wn,ea as Tn,ei as En,en as Dn,er as On,et as kn,f as An,fa as jn,fi as Mn,fn as Nn,fr as Pn,ft as Fn,g as In,gi as Ln,gn as Rn,gr as zn,gt as Bn,h as Vn,hi as Hn,hn as Un,hr as Wn,ht as Gn,i as Kn,ii as qn,in as Jn,ir as Yn,it as Xn,j as Zn,ji as Qn,jn as $n,jr as er,jt as tr,k as nr,ki as rr,kn as ir,kr as ar,kt as or,l as sr,li as cr,ln as lr,lr as ur,lt as dr,m as fr,mi as pr,mn as mr,mr as hr,mt as gr,n as _r,ni as vr,nn as yr,nr as br,nt as xr,o as Sr,oi as Cr,on as wr,or as Tr,ot as Er,p as Dr,pa as Or,pi as kr,pn as Ar,pr as jr,pt as Mr,q as Nr,qi as Pr,qn as Fr,qr as Ir,qt as Lr,r as Rr,ri as zr,rn as Br,rr as Vr,rt as Hr,s as Ur,si as Wr,sn as Gr,sr as Kr,st as qr,t as Jr,ti as Yr,tn as Xr,tr as Zr,tt as Qr,u as $r,ui as ei,un as ti,ur as ni,ut as ri,v as ii,vi as ai,vn as oi,vr as si,vt as ci,w as li,wi as ui,wn as di,wr as fi,wt as pi,x as mi,xi as hi,xn as gi,xr as _i,xt as vi,y as yi,yi as bi,yn as xi,yr as Si,yt as Ci,z as wi,zi as Ti,zn as Ei,zr as Di,zt as Oi}from"./dist-BD4HwRwv.mjs";export{Jr as AGENT_ID_MAX_LEN,_r as AGENT_ID_RE,Rr as AGENT_WRITE_ORIGIN,Kn as AgentFocusBroadcaster,an as AgentPresenceBroadcaster,Sr as AgentSessionCapacityError,Ur as AgentSessionManager,hn as AutoStartDisabledError,sr as BUNDLE_IDS,$r as BUNDLE_SCOPE,bn as BUNDLE_SKILL_NAME,An as BacklinkIndex,Dr as CC1Broadcaster,i as CC1_CONTRACT_VERSION,fr as CONFIG_FILENAME,Vn as CONFLICT_MARKER_RE,In as CURSOR_BUNDLE_PATHS_BY_PLATFORM,$t as ConfigSchema,ii as DEFAULT_CHECKPOINT_RETENTION,yi as DEFAULT_EMBEDDINGS_DIMENSIONS,un as DEFAULT_PACK_ID,mi as EMBEDDINGS_API_KEY_ENV,pt as FILE_SYSTEM_WRITER,V as FILE_WATCHER_ORIGIN,li as FileEmbeddingsBackend,vt as GIT_PREFLIGHT_FAIL_SPAN_NAME,Z as GIT_UPSTREAM_WRITER,jn as GitDirAccessError,K as GitNotAvailableError,qe as GitTooOldError,nr as HOCUSPOCUS_AUTH_REJECTION_REASONS,j as HocuspocusAuthRejection,Zn as HocuspocusAuthTokenSchema,Le as INSTALLED_AGENTS_SCHEMES,t as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Qe as LOG_MD_TEMPLATE,ne as MANAGED_RENAME_ORIGIN,_e as MAX_AGENT_SESSIONS,Me as MCP_CONNECTION_ID_HEADER,b as MCP_SERVER_NAME,ct as MIN_GIT_VERSION,wi as MISSING_OK_CONFIG_MESSAGE,Or as MalformedGitPointerError,I as McpLogger,Ot as MissingOkConfigError,fe as OBSERVER_SYNC_ORIGIN,Ct as OK_OKIGNORE_TEMPLATE,l as ORPHAN_MODES,Nt as PANE_TARGET_TTL_MS,f as PROTOCOL_VERSION,se as PinoLogger,w as ProcessLockCollisionError,De as ProjectGitInitError,Nr as ROLLBACK_ORIGIN,Se as ROOT_GITIGNORE_TEMPLATE,v as RUNTIME_VERSION,Ut as SERVICE_WRITER,Rt as SKILL_INSTALL_EVENTS_FILE_REL,h as SKILL_STATE_TARGETS,Jt as STARTER_FOLDERS,rt as STARTER_FOLDER_FRONTMATTER_FILENAME,E as STARTER_PACKS,kn as STARTER_PACK_IDS,Qr as STARTER_TEMPLATES,xr as STATE_MANIFEST_FILENAME,S as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Hr as SeedPrerequisiteError,Xn as SeedRootDirError,m as ServerLockCollisionError,ln as SingleFileNotAFileError,Er as SingleFileNotFoundError,qr as SingleFileNotMarkdownError,yn as StateManifestError,dr as TagIndex,ri as USER_GLOBAL_BUNDLE_IDS,wn as UiLockCollisionError,Fn as __getShowAllWalkStatsForTesting,Mr as __resetShowAllWalkStatsForTesting,a as acquireProcessLock,y as acquireServerLock,gr as acquireUiLock,Gn as applyAgentMarkdownWrite,Bn as applyExternalChange,rn as applySeed,ci as armPaneTarget,Ci as assertCompatibleStateManifest,mn as assertGitAvailable,vi as assertNeverDiskEvent,_t as attachIdleShutdown,G as bootServer,pi as buildAndOpenSkill,St as buildConfigYmlContent,te as buildExecResult,X as buildSkillZip,Ze as buildStarterFolderFrontmatterYaml,or as buildWipTree,F as bundleSkillMdPath,tr as classifyEvents,Ve as classifyFsPath,Ke as clearArmedPaneTarget,nt as clearContributors,oe as clearEmbeddingsKeyFromAllBackends,xe as coercePackId,c as colorFromSeed,Ie as commitUpstreamImport,ft as commitWip,Oi as commitWipFromTree,B as compareSemver,Mt as containsConflictMarkers,ge as contentHash,Dt as contributorCount,Lt as countShadowObjects,de as countStaleAgentWipRefs,je as countWipRefs,Lr as createApiExtension,Ee as createAssetServeMiddleware,qt as createContentFilter,Ht as createContentFilterAsync,Qt as createEmbeddingsSecretStore,st as createEphemeralProjectDir,A as createExternalChangeHandler,Dn as createFileLogger,Xr as createLiveDerivedIndexExtension,yr as createMcpHttpHandler,Br as createOsProbe,Jn as createPersistenceExtension,sn as createServer,wr as createServerObserverExtension,Gr as createStreamingErrorWriter,_n as createTestLogger,lr as describeStoredEmbeddingsKey,ti as detectClaudeDesktopPresence,Sn as detectGit,Nn as detectProjectShape,Ar as emitPreflightFailureSpan,mr as encodeDocName,Un as encodeFolderRoute,Rn as ensureProjectGit,tn as errorResponse,oi as evictStaleTrackerEntries,xi as extractWikiLinksFromMarkdown,fn as fallbackPaths,gi as findEnclosingGitRoot,ht as findEnclosingProjectRoot,U as flushFileLogger,di as formatAuthRejectionWire,bt as formatContributors,$ as formatContributorsFrom,J as formatPackRationale,Ye as gcCheckpointRefs,ir as getCurrentMcpLogger,N as getLocalDir,$n as getLogFilePath,ze as getLogger,We as getLogsDir,et as getMeter,ie as getMetrics,ye as getTracer,Pe as handleCollabSocketError,ut as handleSpawnCursor,Ei as hasGcLogLatch,e as iconFromClientName,R as incrementCollabSocketFilteredError,At as incrementServerObserverFire,me as initContent,Tt as initShadowRepo,Ft as initTelemetry,le as initToleranceTelemetryWriter,ke as installPrettyZodErrors,Fr as installTestLoggers,we as installUserSkill,Gt as isAllowedApiOrigin,Bt as isAllowedWorkspaceHostHeader,Xt as isConfigDoc,at as isHocuspocusAuthRejectionReason,O as isKnownPackId,On as isLinkIndexExcludedDoc,Zr as isLoopbackAddress,br as isManagedArtifactDoc,n as isOrphanMode,Vr as isPairedWriteOrigin,Yn as isPathWithinDir,C as isProcessAlive,cn as isProjectRoot,Tr as isProjectSkillManaged,Kr as isReservedForUserTree,vn as isSelfWrite,ur as isSystemDoc,ni as isToleranceTelemetryEnabled,o as isValidLockPid,Cn as lastKnownHash,Pn as listRescueCheckpoints,jr as listStarterPacks,hr as loadPrincipal,g as lockFilePath,Wn as loggerFactory,zn as logsCurrentPath,nn as logsPreviousPath,si as makeLazyEmbeddingsKeyStore,Si as mountMcpAndApi,pn as normalizeFsPath,_i as packageVersionMajorMinor,gt as parseAuthRejectionWire,W as parseGitVersion,fi as parseHocuspocusAuthToken,xt as parseKeepaliveConnectionId,ee as pathToDocName,Y as planSeed,Xe as prepareSingleFileOpen,ar as readAllTargets,P as readArmedPaneTarget,er as readBranchFromHead,T as readProcessLock,s as readProcessLockDetailed,Be as readProjectLocalSemanticConfig,u as readServerLock,Ge as readServerPackageVersion,tt as readSkillInstallStateSnapshot,ae as readSkillManagement,be as readStateManifest,Fe as readTargetRecordedAt,dt as readTargetVersion,Di as readUiLock,z as reconcile,jt as recordContributor,he as recordSkillInstallEvent,Et as registerAllTools,It as registerWrite,x as releaseProcessLock,_ as releaseServerLock,ue as releaseUiLock,Ae as removeLastKnownHash,Ir as resetMetrics,Te as resolveBundledSkillDir,Kt as resolveContentDir,Vt as resolveCursorBinaryDefault,Zt as resolveCursorSpawnInvocation,ot as resolveLockDir,k as resolvePack,En as resolvePackageVersion,Yr as resolveUiInfo,vr as restoreContributors,zr as restoreLifecycleFromConflictsJson,qn as rewriteMarkdownLinksForDocumentRename,on as rewriteWikiLinksForDocumentRename,Cr as runAuthReposSubprocess,Wr as runAuthStatusSubprocess,gn as runCloneSubprocess,cr as runDeviceFlowSubprocess,ei as runWithMcpLogger,xn as safeContentPath,Mn as safeSubdir,kr as safetyCheckpoint,pr as sanitizeClientName,Hn as saveInMemoryCheckpoint,Ln as saveVersion,en as seedBasenameIndex,ai as serializeError,bi as setActiveSpanAttributes,dn as shadowGit,hi as shutdownTelemetry,mt as skillManagementPath,H as spansCurrentPath,ui as spansPreviousPath,yt as spawnDetached,Q as splitMarkdownBlocks,q as startWatcher,Je as streamingProblemEvent,rr as swapContributors,M as teardownToleranceTelemetryWriter,Qn as toBroadcasterKey,Re as tracedAppendFileSync,Ue as tracedLinkSync,$e as tracedMkdir,re as tracedMkdirSync,ve as tracedRename,Ne as tracedRenameSync,lt as tracedRmSync,Ti as tracedRmdirSync,L as tracedUnlinkSync,kt as tracedWriteFile,pe as tracedWriteFileSync,wt as updateLastKnownHash,p as updateProcessLockPort,d as updateServerLockPort,Pt as updateUiLockPort,ce as validateAgentId,Oe as validateCloneInputs,Pr as validateSkillZip,Ce as withSpan,Wt as withSpanSync,zt as writeRootGitignoreForNewRepo,Yt as writeSkillManagement,it as writeStateManifest,D as writeTargetVersion,Tn as writeTracker};
1
+ import{Fi as e,Gt as t,Hi as n,In as r,Y as i,a,c as o,d as s,di as c,dn as l,f as u,g as d,gn as f,h as p,i as m,jn as h,l as g,m as _,n as v,o as y,on as b,p as x,r as S,s as C,t as w,u as T}from"./server-lock-CN2YHwpP-COM23IWb.mjs";import{$ as E,$i as D,$n as O,$r as k,$t as A,A as j,Ai as M,An as N,Ar as P,At as F,B as I,Bi as L,Bn as R,Br as z,Bt as B,C as V,Ci as H,Cn as U,Cr as W,Ct as G,D as K,Di as q,Dn as J,Dr as Y,Dt as X,E as Z,Ei as Q,En as $,Er as ee,Et as te,F as ne,Fi as re,Fn as ie,Fr as ae,Ft as oe,G as se,Gi as ce,Gn as le,Gr as ue,Gt as de,H as fe,Hi as pe,Hn as me,Hr as he,Ht as ge,I as _e,Ii as ve,In as ye,Ir as be,It as xe,J as Se,Ji as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,Oi as Je,On as Ye,Or as Xe,Ot as Ze,P as Qe,Pi as $e,Pn as et,Pr as tt,Pt as nt,Q as rt,Qi as it,Qn as at,Qr as ot,Qt as st,R as ct,Ri as lt,Rn as ut,Rr as dt,Rt as ft,S as pt,Si as mt,Sn as ht,Sr as gt,St as _t,T as vt,Ti as yt,Tn as bt,Tr as xt,Tt as St,U as Ct,Ui as wt,Un as Tt,Ur as Et,Ut as Dt,V as Ot,Vi as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wi as Pt,Wn as Ft,Wr as It,Wt as Lt,X as Rt,Xi as zt,Xn as Bt,Xr as Vt,Xt as Ht,Y as Ut,Yi as Wt,Yn as Gt,Yr as Kt,Yt as qt,Z as Jt,Zi as Yt,Zn as Xt,Zr as Zt,Zt as Qt,_ as $t,_i as en,_n as tn,_r as nn,_t as rn,a as an,ai as on,an as sn,ar as cn,at as ln,b as un,bi as dn,bn as fn,br as pn,bt as mn,c as hn,ci as gn,cn as _n,cr as vn,ct as yn,d as bn,di as xn,dn as Sn,dr as Cn,dt as wn,ea as Tn,ei as En,en as Dn,er as On,et as kn,f as An,fa as jn,fi as Mn,fn as Nn,fr as Pn,ft as Fn,g as In,gi as Ln,gn as Rn,gr as zn,gt as Bn,h as Vn,hi as Hn,hn as Un,hr as Wn,ht as Gn,i as Kn,ii as qn,in as Jn,ir as Yn,it as Xn,j as Zn,ji as Qn,jn as $n,jr as er,jt as tr,k as nr,ki as rr,kn as ir,kr as ar,kt as or,l as sr,li as cr,ln as lr,lr as ur,lt as dr,m as fr,mi as pr,mn as mr,mr as hr,mt as gr,n as _r,ni as vr,nn as yr,nr as br,nt as xr,o as Sr,oi as Cr,on as wr,or as Tr,ot as Er,p as Dr,pa as Or,pi as kr,pn as Ar,pr as jr,pt as Mr,q as Nr,qi as Pr,qn as Fr,qr as Ir,qt as Lr,r as Rr,ri as zr,rn as Br,rr as Vr,rt as Hr,s as Ur,si as Wr,sn as Gr,sr as Kr,st as qr,t as Jr,ti as Yr,tn as Xr,tr as Zr,tt as Qr,u as $r,ui as ei,un as ti,ur as ni,ut as ri,v as ii,vi as ai,vn as oi,vr as si,vt as ci,w as li,wi as ui,wn as di,wr as fi,wt as pi,x as mi,xi as hi,xn as gi,xr as _i,xt as vi,y as yi,yi as bi,yn as xi,yr as Si,yt as Ci,z as wi,zi as Ti,zn as Ei,zr as Di,zt as Oi}from"./dist-ctsYjUwZ.mjs";export{Jr as AGENT_ID_MAX_LEN,_r as AGENT_ID_RE,Rr as AGENT_WRITE_ORIGIN,Kn as AgentFocusBroadcaster,an as AgentPresenceBroadcaster,Sr as AgentSessionCapacityError,Ur as AgentSessionManager,hn as AutoStartDisabledError,sr as BUNDLE_IDS,$r as BUNDLE_SCOPE,bn as BUNDLE_SKILL_NAME,An as BacklinkIndex,Dr as CC1Broadcaster,i as CC1_CONTRACT_VERSION,fr as CONFIG_FILENAME,Vn as CONFLICT_MARKER_RE,In as CURSOR_BUNDLE_PATHS_BY_PLATFORM,$t as ConfigSchema,ii as DEFAULT_CHECKPOINT_RETENTION,yi as DEFAULT_EMBEDDINGS_DIMENSIONS,un as DEFAULT_PACK_ID,mi as EMBEDDINGS_API_KEY_ENV,pt as FILE_SYSTEM_WRITER,V as FILE_WATCHER_ORIGIN,li as FileEmbeddingsBackend,vt as GIT_PREFLIGHT_FAIL_SPAN_NAME,Z as GIT_UPSTREAM_WRITER,jn as GitDirAccessError,K as GitNotAvailableError,qe as GitTooOldError,nr as HOCUSPOCUS_AUTH_REJECTION_REASONS,j as HocuspocusAuthRejection,Zn as HocuspocusAuthTokenSchema,Le as INSTALLED_AGENTS_SCHEMES,t as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Qe as LOG_MD_TEMPLATE,ne as MANAGED_RENAME_ORIGIN,_e as MAX_AGENT_SESSIONS,Me as MCP_CONNECTION_ID_HEADER,b as MCP_SERVER_NAME,ct as MIN_GIT_VERSION,wi as MISSING_OK_CONFIG_MESSAGE,Or as MalformedGitPointerError,I as McpLogger,Ot as MissingOkConfigError,fe as OBSERVER_SYNC_ORIGIN,Ct as OK_OKIGNORE_TEMPLATE,l as ORPHAN_MODES,Nt as PANE_TARGET_TTL_MS,f as PROTOCOL_VERSION,se as PinoLogger,w as ProcessLockCollisionError,De as ProjectGitInitError,Nr as ROLLBACK_ORIGIN,Se as ROOT_GITIGNORE_TEMPLATE,v as RUNTIME_VERSION,Ut as SERVICE_WRITER,Rt as SKILL_INSTALL_EVENTS_FILE_REL,h as SKILL_STATE_TARGETS,Jt as STARTER_FOLDERS,rt as STARTER_FOLDER_FRONTMATTER_FILENAME,E as STARTER_PACKS,kn as STARTER_PACK_IDS,Qr as STARTER_TEMPLATES,xr as STATE_MANIFEST_FILENAME,S as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Hr as SeedPrerequisiteError,Xn as SeedRootDirError,m as ServerLockCollisionError,ln as SingleFileNotAFileError,Er as SingleFileNotFoundError,qr as SingleFileNotMarkdownError,yn as StateManifestError,dr as TagIndex,ri as USER_GLOBAL_BUNDLE_IDS,wn as UiLockCollisionError,Fn as __getShowAllWalkStatsForTesting,Mr as __resetShowAllWalkStatsForTesting,a as acquireProcessLock,y as acquireServerLock,gr as acquireUiLock,Gn as applyAgentMarkdownWrite,Bn as applyExternalChange,rn as applySeed,ci as armPaneTarget,Ci as assertCompatibleStateManifest,mn as assertGitAvailable,vi as assertNeverDiskEvent,_t as attachIdleShutdown,G as bootServer,pi as buildAndOpenSkill,St as buildConfigYmlContent,te as buildExecResult,X as buildSkillZip,Ze as buildStarterFolderFrontmatterYaml,or as buildWipTree,F as bundleSkillMdPath,tr as classifyEvents,Ve as classifyFsPath,Ke as clearArmedPaneTarget,nt as clearContributors,oe as clearEmbeddingsKeyFromAllBackends,xe as coercePackId,c as colorFromSeed,Ie as commitUpstreamImport,ft as commitWip,Oi as commitWipFromTree,B as compareSemver,Mt as containsConflictMarkers,ge as contentHash,Dt as contributorCount,Lt as countShadowObjects,de as countStaleAgentWipRefs,je as countWipRefs,Lr as createApiExtension,Ee as createAssetServeMiddleware,qt as createContentFilter,Ht as createContentFilterAsync,Qt as createEmbeddingsSecretStore,st as createEphemeralProjectDir,A as createExternalChangeHandler,Dn as createFileLogger,Xr as createLiveDerivedIndexExtension,yr as createMcpHttpHandler,Br as createOsProbe,Jn as createPersistenceExtension,sn as createServer,wr as createServerObserverExtension,Gr as createStreamingErrorWriter,_n as createTestLogger,lr as describeStoredEmbeddingsKey,ti as detectClaudeDesktopPresence,Sn as detectGit,Nn as detectProjectShape,Ar as emitPreflightFailureSpan,mr as encodeDocName,Un as encodeFolderRoute,Rn as ensureProjectGit,tn as errorResponse,oi as evictStaleTrackerEntries,xi as extractWikiLinksFromMarkdown,fn as fallbackPaths,gi as findEnclosingGitRoot,ht as findEnclosingProjectRoot,U as flushFileLogger,di as formatAuthRejectionWire,bt as formatContributors,$ as formatContributorsFrom,J as formatPackRationale,Ye as gcCheckpointRefs,ir as getCurrentMcpLogger,N as getLocalDir,$n as getLogFilePath,ze as getLogger,We as getLogsDir,et as getMeter,ie as getMetrics,ye as getTracer,Pe as handleCollabSocketError,ut as handleSpawnCursor,Ei as hasGcLogLatch,e as iconFromClientName,R as incrementCollabSocketFilteredError,At as incrementServerObserverFire,me as initContent,Tt as initShadowRepo,Ft as initTelemetry,le as initToleranceTelemetryWriter,ke as installPrettyZodErrors,Fr as installTestLoggers,we as installUserSkill,Gt as isAllowedApiOrigin,Bt as isAllowedWorkspaceHostHeader,Xt as isConfigDoc,at as isHocuspocusAuthRejectionReason,O as isKnownPackId,On as isLinkIndexExcludedDoc,Zr as isLoopbackAddress,br as isManagedArtifactDoc,n as isOrphanMode,Vr as isPairedWriteOrigin,Yn as isPathWithinDir,C as isProcessAlive,cn as isProjectRoot,Tr as isProjectSkillManaged,Kr as isReservedForUserTree,vn as isSelfWrite,ur as isSystemDoc,ni as isToleranceTelemetryEnabled,o as isValidLockPid,Cn as lastKnownHash,Pn as listRescueCheckpoints,jr as listStarterPacks,hr as loadPrincipal,g as lockFilePath,Wn as loggerFactory,zn as logsCurrentPath,nn as logsPreviousPath,si as makeLazyEmbeddingsKeyStore,Si as mountMcpAndApi,pn as normalizeFsPath,_i as packageVersionMajorMinor,gt as parseAuthRejectionWire,W as parseGitVersion,fi as parseHocuspocusAuthToken,xt as parseKeepaliveConnectionId,ee as pathToDocName,Y as planSeed,Xe as prepareSingleFileOpen,ar as readAllTargets,P as readArmedPaneTarget,er as readBranchFromHead,T as readProcessLock,s as readProcessLockDetailed,Be as readProjectLocalSemanticConfig,u as readServerLock,Ge as readServerPackageVersion,tt as readSkillInstallStateSnapshot,ae as readSkillManagement,be as readStateManifest,Fe as readTargetRecordedAt,dt as readTargetVersion,Di as readUiLock,z as reconcile,jt as recordContributor,he as recordSkillInstallEvent,Et as registerAllTools,It as registerWrite,x as releaseProcessLock,_ as releaseServerLock,ue as releaseUiLock,Ae as removeLastKnownHash,Ir as resetMetrics,Te as resolveBundledSkillDir,Kt as resolveContentDir,Vt as resolveCursorBinaryDefault,Zt as resolveCursorSpawnInvocation,ot as resolveLockDir,k as resolvePack,En as resolvePackageVersion,Yr as resolveUiInfo,vr as restoreContributors,zr as restoreLifecycleFromConflictsJson,qn as rewriteMarkdownLinksForDocumentRename,on as rewriteWikiLinksForDocumentRename,Cr as runAuthReposSubprocess,Wr as runAuthStatusSubprocess,gn as runCloneSubprocess,cr as runDeviceFlowSubprocess,ei as runWithMcpLogger,xn as safeContentPath,Mn as safeSubdir,kr as safetyCheckpoint,pr as sanitizeClientName,Hn as saveInMemoryCheckpoint,Ln as saveVersion,en as seedBasenameIndex,ai as serializeError,bi as setActiveSpanAttributes,dn as shadowGit,hi as shutdownTelemetry,mt as skillManagementPath,H as spansCurrentPath,ui as spansPreviousPath,yt as spawnDetached,Q as splitMarkdownBlocks,q as startWatcher,Je as streamingProblemEvent,rr as swapContributors,M as teardownToleranceTelemetryWriter,Qn as toBroadcasterKey,Re as tracedAppendFileSync,Ue as tracedLinkSync,$e as tracedMkdir,re as tracedMkdirSync,ve as tracedRename,Ne as tracedRenameSync,lt as tracedRmSync,Ti as tracedRmdirSync,L as tracedUnlinkSync,kt as tracedWriteFile,pe as tracedWriteFileSync,wt as updateLastKnownHash,p as updateProcessLockPort,d as updateServerLockPort,Pt as updateUiLockPort,ce as validateAgentId,Oe as validateCloneInputs,Pr as validateSkillZip,Ce as withSpan,Wt as withSpanSync,zt as writeRootGitignoreForNewRepo,Yt as writeSkillManagement,it as writeStateManifest,D as writeTargetVersion,Tn as writeTracker};