@inkeep/open-knowledge 0.9.0-beta.12 → 0.9.0-beta.14

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 (43) 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 +5 -5
  4. package/dist/constants-D9hc7LX4.mjs +2 -0
  5. package/dist/{dist-CpYAbkBw.mjs → dist-D-rWIekL.mjs} +1 -1
  6. package/dist/{dist-BBbP7DxV.mjs → dist-DKgq69uI.mjs} +3 -3
  7. package/dist/index.mjs +1 -1
  8. package/dist/init-BPJN5KYj.mjs +1 -0
  9. package/dist/{init-CANrNVDk.mjs → init-BrOIE7gK.mjs} +4 -4
  10. package/dist/loader-BIxKasBW.mjs +1 -0
  11. package/dist/{loader-DyckoSTu.mjs → loader-CxaZzLDi.mjs} +2 -2
  12. package/dist/{preview-CtJlOfbB.mjs → preview-BGoO3Ogd.mjs} +2 -2
  13. package/dist/preview-CcHJG_2a.mjs +1 -0
  14. package/dist/public/assets/{ActivityModeContent-Bds2tgDc.js → ActivityModeContent-BscrBati.js} +1 -1
  15. package/dist/public/assets/DocumentContext-CCtVCYnM.js +62 -0
  16. package/dist/public/assets/SettingsDialogBody-CIS9SfKb.js +7 -0
  17. package/dist/public/assets/SourceEditor-CXHj9br1.js +2 -0
  18. package/dist/public/assets/{config-validation-events-ITinmoyE.js → config-validation-events-DaxQexzg.js} +5 -5
  19. package/dist/public/assets/index-U93cGbUs.css +1 -0
  20. package/dist/public/assets/index-mHmG_FVB.js +1914 -0
  21. package/dist/public/assets/typing-burst-detector-D3uL_-1i.js +1 -0
  22. package/dist/public/index.html +6 -6
  23. package/dist/{repair-launch-json-CC3QjG7G.mjs → repair-launch-json-k1Ihx-tm.mjs} +2 -2
  24. package/dist/{repair-mcp-configs-6tRBtwd-.mjs → repair-mcp-configs-s8YtscAj.mjs} +2 -2
  25. package/dist/repair-skills-BimjofqV.mjs +1 -0
  26. package/dist/{repair-skills-DL_fR7iS.mjs → repair-skills-D2S7rOZx.mjs} +2 -2
  27. package/dist/{src-DsuG24c2.mjs → src-pmNhkR0H.mjs} +2 -2
  28. package/dist/start-NCx0aFju.mjs +1 -0
  29. package/dist/{start-46USgv8o.mjs → start-PfFarWKH.mjs} +2 -2
  30. package/dist/{write-project-skill-BNMnZE-x.mjs → write-project-skill-BQGm1G4f.mjs} +2 -2
  31. package/package.json +1 -1
  32. package/dist/constants-BsDF_COe.mjs +0 -2
  33. package/dist/init-hMRmtJMS.mjs +0 -1
  34. package/dist/loader-BsENTmPa.mjs +0 -1
  35. package/dist/preview-1nz8JsfK.mjs +0 -1
  36. package/dist/public/assets/DocumentContext-QeMOWx_9.js +0 -61
  37. package/dist/public/assets/SettingsDialogBody-5tbTYUhy.js +0 -7
  38. package/dist/public/assets/SourceEditor-eAWbTIpy.js +0 -2
  39. package/dist/public/assets/index-1-IrF-IN.js +0 -1914
  40. package/dist/public/assets/index-BuqVcYKx.css +0 -1
  41. package/dist/public/assets/typing-burst-detector-Dwn4lC9Q.js +0 -2
  42. package/dist/repair-skills-CaLjuijU.mjs +0 -1
  43. package/dist/start-CR8iLsn1.mjs +0 -1
@@ -3,7 +3,7 @@ name: open-knowledge-discovery
3
3
  description: "Read when the user asks what Open Knowledge is, wants to install it on a repository, wants to share an Open Knowledge project with collaborators, or asks how `ok init` / `ok install-skill` / OK Desktop set up a project. Do NOT load to perform Open Knowledge 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.9.0-beta.12"
6
+ version: "0.9.0-beta.14"
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: "MUST invoke before reading or editing any `.md` / `.mdx` file, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write_document`, `edit_document`, and the rest). This skill is installed into the repository by `ok init`, so its presence alone means this is an Open Knowledge project — its runtime contract governs every markdown file here, with no need to probe for a `.ok/` directory. Authoritative agent-runtime contract; supersedes the overlapping MCP server `instructions` echo."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.9.0-beta.12"
6
+ version: "0.9.0-beta.14"
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{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Bi as n,Di as r,Li as i,Mi as a,Ni as o,Ri as s,Sn as c,Vr as l,Wi as u,Xi as d,c as f,da as p,f as m,ji as h,l as g,n as _,qi as v,s as y,ua as ee,vr as b,yi as x,zi as te,zr as ne}from"./server-lock-BpjJj3OD-B9uBbH7Z.mjs";import{a as S,n as re,r as ie,t as ae}from"./gh-detect-D3_evne3.mjs";import{n as oe,r as se,t as C}from"./dist-bundle-BK4P1EQn.mjs";import{A as ce,C as le,D as ue,E as de,O as fe,S as pe,T as me,b as he,k as ge,o as _e,p as ve,w as ye,x as be}from"./init-CANrNVDk.mjs";import{r as xe}from"./git-handle-uz8TUFSi-DaMTjKLA.mjs";import{A as Se,Ci as Ce,Ei as we,K as Te,Nt as Ee,Ti as De,X as Oe,_i as ke,ar as Ae,b as je,dr as Me,gi as Ne,h as Pe,hi as Fe,hn as Ie,in as Le,it as Re,j as ze,kn as Be,kr as Ve,mi as He,mr as w,ot as Ue,pi as We,pt as Ge,q as Ke,qn as qe,ut as Je,vi as Ye,vn as Xe,wi as Ze,x as Qe,xi as $e}from"./dist-BBbP7DxV.mjs";import{t as et}from"./yazl-DjRp4wSy.mjs";import{n as tt,t as nt}from"./constants-BsDF_COe.mjs";import{i as rt}from"./src-DsuG24c2.mjs";import{n as it,t as at}from"./loader-DyckoSTu.mjs";import{c as ot,f as st,h as ct,m as lt,p as ut,u as dt}from"./start-46USgv8o.mjs";import{c as ft,i as pt,n as T,o as E,r as D,s as mt,t as O}from"./colors-BtKMHmBX.mjs";import{n as ht}from"./repair-skills-DL_fR7iS.mjs";import{execSync as gt,spawn as _t,spawnSync as k}from"node:child_process";import vt,{basename as A,dirname as yt,isAbsolute as bt,join as j,relative as xt,resolve as M,sep as St}from"node:path";import{accessSync as Ct,closeSync as wt,constants as Tt,cpSync as Et,createWriteStream as Dt,existsSync as N,lstatSync as Ot,mkdirSync as P,mkdtempSync as kt,openSync as At,readFileSync as F,readdirSync as jt,realpathSync as Mt,rmSync as Nt,statSync as Pt,unlinkSync as Ft,writeFileSync as I}from"node:fs";import It from"node:process";import{arch as Lt,freemem as Rt,homedir as zt,hostname as Bt,platform as Vt,release as Ht,tmpdir as Ut,totalmem as Wt,type as Gt,uptime as Kt}from"node:os";import{fileURLToPath as qt}from"node:url";import{AsyncLocalStorage as Jt,AsyncResource as Yt}from"node:async_hooks";import{stripVTControlCharacters as Xt,styleText as L}from"node:util";import*as Zt from"node:readline";import{createHash as Qt,randomUUID as $t}from"node:crypto";import{realpath as en}from"node:fs/promises";import{setTimeout as tn}from"node:timers/promises";import{createInterface as nn}from"node:readline/promises";async function rn(e,t,n){let r=an(await on(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function an(e){let t={};for(let n of e.split(`
2
+ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Bi as n,Di as r,Li as i,Mi as a,Ni as o,Ri as s,Sn as c,Vr as l,Wi as u,Xi as d,c as f,da as p,f as m,ji as h,l as g,n as _,qi as v,s as y,ua as ee,vr as b,yi as x,zi as te,zr as ne}from"./server-lock-BpjJj3OD-B9uBbH7Z.mjs";import{a as S,n as re,r as ie,t as ae}from"./gh-detect-D3_evne3.mjs";import{n as oe,r as se,t as C}from"./dist-bundle-BK4P1EQn.mjs";import{A as ce,C as le,D as ue,E as de,O as fe,S as pe,T as me,b as he,k as ge,o as _e,p as ve,w as ye,x as be}from"./init-BrOIE7gK.mjs";import{r as xe}from"./git-handle-uz8TUFSi-DaMTjKLA.mjs";import{A as Se,Ci as Ce,Ei as we,K as Te,Nt as Ee,Ti as De,X as Oe,_i as ke,ar as Ae,b as je,dr as Me,gi as Ne,h as Pe,hi as Fe,hn as Ie,in as Le,it as Re,j as ze,kn as Be,kr as Ve,mi as He,mr as w,ot as Ue,pi as We,pt as Ge,q as Ke,qn as qe,ut as Je,vi as Ye,vn as Xe,wi as Ze,x as Qe,xi as $e}from"./dist-DKgq69uI.mjs";import{t as et}from"./yazl-DjRp4wSy.mjs";import{n as tt,t as nt}from"./constants-D9hc7LX4.mjs";import{i as rt}from"./src-pmNhkR0H.mjs";import{n as it,t as at}from"./loader-CxaZzLDi.mjs";import{c as ot,f as st,h as ct,m as lt,p as ut,u as dt}from"./start-PfFarWKH.mjs";import{c as ft,i as pt,n as T,o as E,r as D,s as mt,t as O}from"./colors-BtKMHmBX.mjs";import{n as ht}from"./repair-skills-D2S7rOZx.mjs";import{execSync as gt,spawn as _t,spawnSync as k}from"node:child_process";import vt,{basename as A,dirname as yt,isAbsolute as bt,join as j,relative as xt,resolve as M,sep as St}from"node:path";import{accessSync as Ct,closeSync as wt,constants as Tt,cpSync as Et,createWriteStream as Dt,existsSync as N,lstatSync as Ot,mkdirSync as P,mkdtempSync as kt,openSync as At,readFileSync as F,readdirSync as jt,realpathSync as Mt,rmSync as Nt,statSync as Pt,unlinkSync as Ft,writeFileSync as I}from"node:fs";import It from"node:process";import{arch as Lt,freemem as Rt,homedir as zt,hostname as Bt,platform as Vt,release as Ht,tmpdir as Ut,totalmem as Wt,type as Gt,uptime as Kt}from"node:os";import{fileURLToPath as qt}from"node:url";import{AsyncLocalStorage as Jt,AsyncResource as Yt}from"node:async_hooks";import{stripVTControlCharacters as Xt,styleText as L}from"node:util";import*as Zt from"node:readline";import{createHash as Qt,randomUUID as $t}from"node:crypto";import{realpath as en}from"node:fs/promises";import{setTimeout as tn}from"node:timers/promises";import{createInterface as nn}from"node:readline/promises";async function rn(e,t,n){let r=an(await on(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function an(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 on(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 sn(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await rn(process.stdin,process.stdout,t);process.exit(n)}),n}function cn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function ln(e,t,n){let r={baseUrl:cn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new oe(`${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 un(e){let t=e.request||C,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),ln(t,`POST /login/device/code`,n)}async function dn(e){let t=await ln(e.request||C,`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=fn(e,t.data.expires_in),n.refreshTokenExpiresAt=fn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function fn(e,t){return new Date(e+t*1e3).toISOString()}async function pn(e,t){let n=mn(e,t.auth);if(n)return n;let{data:r}=await un({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await gn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function mn(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 hn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function gn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await dn({...i,clientType:`oauth-app`}):await dn({...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 hn(r.interval),gn(e,t,n,r);if(a===`slow_down`)return await hn(r.interval+7),gn(e,t,n,r);throw i}}async function _n(e,t){return pn(e,{auth:t})}async function vn(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 pn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var yn=`0.0.0-development`;function bn(e){let t=e.request||C.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${yn} ${se()}`}}),{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(_n.bind(null,i),{hook:vn.bind(null,i)})}async function xn(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=bn({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-CjV1Pdeo.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??[]}}const Sn={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 Cn;(function(e){})(Cn||={});function wn(e){return d(r,e)}function Tn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const En=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function R(e){let t=e.toLowerCase().replace(/:\d+$/,``);En.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 Dn(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function On(e,t,n=xn){let r=Tn(),{host:i,json:a}=e;R(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?Dn(!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?Dn(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function kn(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 On(t,await e())})}const An=e=>e.name===`enter`||e.name===`return`;var jn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Mn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Nn=class extends Error{name=`ExitPromptError`},Pn=class extends Error{name=`HookError`},Fn=class extends Error{name=`ValidationError`};const In=new Jt;function Ln(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Rn(e,t){let n=Ln(e);return In.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function z(){let e=In.getStore();if(!e)throw new Pn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function zn(){return z().rl}function Bn(e){return Yt.bind((...t)=>{let n=z(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Vn(e){let t=z(),{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 Hn(){z().handleChange()}const Un={queue(e){let t=z(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(zn());if(r!=null&&typeof r!=`function`)throw new Fn(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=z();Bn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=z();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Wn(e){return typeof e==`function`}function B(e){return Vn(t=>{let n=Yt.bind(function(e){t.get()!==e&&(t.set(e),Hn())});if(t.initialized)return[t.get(),n];let r=Wn(e)?e():e;return t.set(r),[r,n]})}function Gn(e,t){Vn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Un.queue(e),n.set(t)})}const Kn={prefix:{idle:L(`blue`,`?`),done:L(`green`,ce.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>L(`yellow`,e))},style:{answer:e=>L(`cyan`,e),message:e=>L(`bold`,e),error:e=>L(`red`,`> ${e}`),defaultAnswer:e=>L(`dim`,`(${e})`),help:e=>L(`dim`,e),highlight:e=>L(`cyan`,e),key:e=>L(`cyan`,L(`bold`,`<${e}>`))}};function qn(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 Jn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=qn(n)&&qn(r)?Jn(n,r):r}return t}function Yn(...e){return Jn(Kn,...e.filter(e=>e!=null))}function Xn({status:e=`idle`,theme:t}){let[n,r]=B(!1),[i,a]=B(0),{prefix:o,spinner:s}=Yn(t);return Gn(()=>{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 Zn(e){return B({current:e})[0]}function Qn(e){let t=Zn(e);t.current=e,Gn(e=>{let n=!1,r=Bn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var $n=e(ge(),1);function er(e,t){return e.split(`
4
4
  `).flatMap(e=>fe(e,t,{trim:!1,hard:!0}).split(`
5
5
  `).map(e=>e.trimEnd())).join(`
@@ -20,10 +20,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
20
20
  `),patterns:[...t],lineCount:n}}const yi=j(zt(),`.ok`,`logs`),bi=j(zt(),`.ok`,`bug-reports`);function xi(e){let t=j(e,`.ok`,`config.yml`);if(N(t))try{let e=F(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return N(j(e,`.ok`))?Qt(`sha256`).update(M(e)).digest(`hex`).slice(0,12):null}function Si(){let e={timestamp:new Date().toISOString(),platform:Vt(),osType:Gt(),osRelease:Ht(),hostname:`[redacted]`,uptime:Kt(),freeMem:Rt(),totalMem:Wt(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=gt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=j(__dirname,`..`,`..`,`package.json`);N(t)&&(e.okVersion=JSON.parse(F(t,`utf8`)).version)}catch{}return e}function Ci(e){if(!N(yi))return{files:[],dir:yi};let t=jt(yi).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>j(yi,e));if(e&&t.length>0){let n=t.filter(t=>{try{return F(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:yi}}function wi(e){let t=j(e,`.ok`,`local`);return N(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>j(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}function Ti(e){let t=j(e,`.ok`,`local`,`logs`);return N(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>j(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}async function Ei(t){let n=$l();P(bi,{recursive:!0});let r=j(bi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Si(),{files:a}=Ci(t.projectSlug),{files:o}=wi(t.cwd),{files:s}=Ti(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CJayzk0b.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=vi(F(e,`utf8`)),i=`logs/${A(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}=vi(F(e,`utf8`)),i=`lockdir/${A(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}=vi(F(e,`utf8`)),i=`local-logs/${A(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: ${_i.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(`
21
21
  `);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Dt(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&&Vt()===`darwin`)try{_t(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function Di(){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=xi(t);try{await Ei({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 U(e,t,n={}){let r=g(e,t);if(!N(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(F(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!f(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??y)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??Bt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Oi(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 ki(e){let t=e.inspect??(t=>U(e.lockDir,t)),n=e.unlink??(e=>Ft(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Oi(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 Ai(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),ki({lockDir:w(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function ji(e,t,n={},r=ae){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 Mi(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 Ni=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Pi(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 Ni)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function W(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function Fi(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const Ii=l;async function Li(e){try{return await e.clone(Fi(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&Ii(t))return e.onFallback(e.branch),await e.clone(Fi(null)),{fellBack:!0};throw t}}function Ri(e,t,n){return e===`https`&&t===`github.com`&&n}async function zi(e,t,n,r=process.cwd()){let i=rt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?M(r,t.dir):M(r,i.name);if(N(a)&&jt(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=S(),s=i.protocol===`https`&&i.hostname===`github.com`?await Mi(i.owner,i.name):!1,c=Ri(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await ji(i.hostname,o,{}),l=xe({baseDir:r,config:c.credentialArgs.length>=2?[c.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),u=-1;l.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
22
22
  `)){let n=Pi(e);n&&n.pct!==u&&(u=n.pct,W(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await Li({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>l.clone(e,a,t),onFallback:e=>{W(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(`
23
- `);try{let{runInit:e}=await import(`./init-hMRmtJMS.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?W(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?W(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Bi(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?W(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Bi(e){let t=j(e,`.git`,`info`,`exclude`);if(!N(t))return`no-exclude`;let n=F(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
23
+ `);try{let{runInit:e}=await import(`./init-BPJN5KYj.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?W(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?W(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Bi(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?W(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Bi(e){let t=j(e,`.git`,`info`,`exclude`);if(!N(t))return`no-exclude`;let n=F(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
24
24
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(I(t,`${n}${n.length===0||n.endsWith(`
25
25
  `)?``:`
26
- `}.ok/\n`,`utf-8`),`appended`)}function Vi(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 zi(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)W(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CR8iLsn1.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?W(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var Hi=p();const Ui=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function Wi(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??it;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 Gi(e){let t=(0,Hi.parseDocument)(F(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 Ui)t.hasIn(e)&&n.push(e.join(`.`));return n}function Ki(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qi(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=Ki(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ji(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Ce,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:$e(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:$e(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!N(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Gi(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:qi(Ui.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:ne(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function Yi(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Wi({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).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 Ji({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Xi=e(et(),1),G=e(ft(),1);const Zi=new Set([`doc.name`]);function Qi(e){return`doc:${Qt(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function $i(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 ea(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Qi(e);return t.originalToHashed.set(e,r),$i(t,e,r),r}function ta(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function na(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ra(e,t){if(typeof e==`string`)return ta(e,t.contentDir);if(Array.isArray(e))return e.map(e=>ra(e,t));if(!na(e))return e;let n=typeof e.key==`string`&&Zi.has(e.key)&&na(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`&&na(a)){let e=ea(n,t);r[i]={...a,stringValue:e}}else Zi.has(i)&&typeof a==`string`?r[i]=ea(a,t):r[i]=ra(a,t);return r}function ia(e,t){let n=F(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
26
+ `}.ok/\n`,`utf-8`),`appended`)}function Vi(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 zi(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)W(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-NCx0aFju.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?W(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var Hi=p();const Ui=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function Wi(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??it;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 Gi(e){let t=(0,Hi.parseDocument)(F(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 Ui)t.hasIn(e)&&n.push(e.join(`.`));return n}function Ki(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qi(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=Ki(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ji(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Ce,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:$e(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:$e(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!N(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Gi(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:qi(Ui.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:ne(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function Yi(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Wi({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).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 Ji({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Xi=e(et(),1),G=e(ft(),1);const Zi=new Set([`doc.name`]);function Qi(e){return`doc:${Qt(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function $i(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 ea(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Qi(e);return t.originalToHashed.set(e,r),$i(t,e,r),r}function ta(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function na(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ra(e,t){if(typeof e==`string`)return ta(e,t.contentDir);if(Array.isArray(e))return e.map(e=>ra(e,t));if(!na(e))return e;let n=typeof e.key==`string`&&Zi.has(e.key)&&na(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`&&na(a)){let e=ea(n,t);r[i]={...a,stringValue:e}}else Zi.has(i)&&typeof a==`string`?r[i]=ea(a,t):r[i]=ra(a,t);return r}function ia(e,t){let n=F(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
27
27
  `),i=n.split(`
28
28
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=ra(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}I(e,r?`${a.join(`
29
29
  `)}\n`:a.join(`
@@ -57,7 +57,7 @@ ws.addEventListener('error', () => process.exit(1));
57
57
  setTimeout(() => process.exit(2), ${t+1e4});
58
58
  `),r}async function ko(e,t,n,r,i){let a=Oo(e,t,j(r,`cpu.cpuprofile`)),o=!1,s=_t(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=wo(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{Nt(j(a,`..`),{recursive:!0,force:!0})}catch{}return o}function Ao(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(`
59
59
  `)}async function jo(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??no,s=t.inspect??U,c=t.resolveCommand??Ya,l=t.resolveUsage??Xa,u=t.collectLsofFn??To,d=t.getEndpoints??Do,f=t.profiler??ko,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(G.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?j(v,`.ok`,`local`,`diagnostics`,`process-${n}-${ee}`):j(process.cwd(),`ok-diagnose-${n}-${ee}`);try{P(b,{recursive:!0})}catch(e){a(G.default.red(`Cannot create output directory ${b}: ${e.message}`));return}a(G.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${b}`),a(``);let x=(e,t)=>{I(j(b,e),t),a(` wrote ${e}`)},te=c(n),ne=l(n);x(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:te,usage:ne,lockInfo:y},null,2)),a(` sampling lsof`);let S=u(n);if(S&&x(`lsof.txt`,S),!i){let e=S?Eo(S).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(G.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(G.default.yellow(` CPU profile capture failed`)),t.length>0&&x(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
60
- `)}\n`);try{x(`stacks.txt`,Ao(F(j(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(G.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(G.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(G.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: ${G.default.bold(b)}`)}async function Mo(e){let t=nn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function No(e){let t=kt(j(Ut(),`ok-bundle-process-`));return await jo({pid:e,output:t}),t}function Po(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 Fo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Io(e,t,n){let{summary:r,manifest:i}=t;e(``),e(G.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Po(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 Lo(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Mo,i=t.runProcessDiagnose??No,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=yt(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=j(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=j(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(G.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Ra({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(G.default.yellow(` server not running — live state unavailable`)),Io(n,c,o),e.yes!==!0&&!Fo(await r(`Write bundle? [y/N]: `))?(n(G.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await za({collected:c,outputPath:o}),n(G.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Nt(s,{recursive:!0,force:!0})}catch{}}}function Ro(){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(G.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(G.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await jo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Co()),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(G.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-BsENTmPa.mjs`),{resolveContentDir:r}=await import(`./dist-CpYAbkBw.mjs`),i=process.cwd(),{config:a}=n(i);await Lo({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(G.default.red(t)),process.exit(1)}}),e}const zo=[` 1. ${O(`Customize`)} (sidebar) → ${O(`Skills`)}`,` 2. Click the ${O(`+`)} button`,` 3. Click ${O(`Create skill`)}`,` 4. Click ${O(`Upload skill`)}`,` 5. Pick ${O(`openknowledge.skill`)} from Downloads`],Bo=pt(` Open the Claude Desktop App, then: ${O(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Vo(e){let t=[E(`Built ${e.outputPath}`),T(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(mt(` Handoff failed: ${e.handoffError.message}`)),t.push(Bo),t.join(`
60
+ `)}\n`);try{x(`stacks.txt`,Ao(F(j(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(G.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(G.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(G.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: ${G.default.bold(b)}`)}async function Mo(e){let t=nn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function No(e){let t=kt(j(Ut(),`ok-bundle-process-`));return await jo({pid:e,output:t}),t}function Po(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 Fo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Io(e,t,n){let{summary:r,manifest:i}=t;e(``),e(G.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Po(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 Lo(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Mo,i=t.runProcessDiagnose??No,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=yt(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=j(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=j(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(G.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Ra({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(G.default.yellow(` server not running — live state unavailable`)),Io(n,c,o),e.yes!==!0&&!Fo(await r(`Write bundle? [y/N]: `))?(n(G.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await za({collected:c,outputPath:o}),n(G.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Nt(s,{recursive:!0,force:!0})}catch{}}}function Ro(){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(G.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(G.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await jo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Co()),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(G.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-BIxKasBW.mjs`),{resolveContentDir:r}=await import(`./dist-D-rWIekL.mjs`),i=process.cwd(),{config:a}=n(i);await Lo({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(G.default.red(t)),process.exit(1)}}),e}const zo=[` 1. ${O(`Customize`)} (sidebar) → ${O(`Skills`)}`,` 2. Click the ${O(`+`)} button`,` 3. Click ${O(`Create skill`)}`,` 4. Click ${O(`Upload skill`)}`,` 5. Pick ${O(`openknowledge.skill`)} from Downloads`],Bo=pt(` Open the Claude Desktop App, then: ${O(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Vo(e){let t=[E(`Built ${e.outputPath}`),T(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(mt(` Handoff failed: ${e.handoffError.message}`)),t.push(Bo),t.join(`
61
61
  `)}function Ho(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[pt(`Open Knowledge skill ${O(`v${t}`)} already delivered to Claude Desktop.`),T(` Recorded at ${n} in ~/.ok/skill-state.yml`),T(` Use ${O(`--force`)} to rebuild and re-open the install dialog.`)].join(`
62
62
  `)}function Uo(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[E(`Built ${e.outputPath}`),T(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),pt(` Claude Desktop App opened. Now upload the file manually:`),...zo,T(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
63
63
  `)}function Wo(e){return`${D(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Go(e={}){let t=await Je(e);return t.status===`failed`?{...t,message:Wo(t),exitCode:1}:t.status===`skip-current`?{...t,message:Ho(t),exitCode:0}:t.status===`installed`?{...t,message:Uo(t),exitCode:0}:{...t,message:Vo(t),exitCode:0}}function Ko(){return new t(`install-skill`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude — `ok init` covers that separately.").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 Go({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}const qo=j(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),Jo=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Yo(e,t,n){return e===`darwin`?[j(t,`Applications`,`Open Knowledge.app`,qo),j(`/Applications`,`Open Knowledge.app`,qo)].find(e=>n.existsSync(e))??null:null}function Xo(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`&&Jo.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function Zo(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 Qo(e){Zo({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??_t,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 $o(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 es=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
@@ -68,7 +68,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
68
68
  `,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]===`
69
69
  `&&r++}}return[t,n]}var wc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Sc({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 Tc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Ec=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Dc=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=ls(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Tc}async _authThenStart(){if(!this._authProvider)throw new Z(`No auth provider`);let e;try{e=await $s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Z;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=cs(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 Ec(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 wc({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=He.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 Z(`No auth provider`);if(await $s(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ke(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 Ec(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=rc(o);if(this._resourceMetadataUrl=t,this._scope=n,await $s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=rc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Ec(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await $s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Z;return this.send(e)}}throw new Ec(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ne(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=>He.parse(e)):[He.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Ec(-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 Ec(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 Oc(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 kc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Ac(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function jc(e,t){return`http://${Ac(e)}:${t}/mcp`}function Mc(e,t){return`ws://${Ac(e)}:${t}`}function Nc(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Pc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Fc(e){return N(e)?F(e,`utf-8`).trim():``}function Ic(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Lc(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Rc(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 zc(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Bc(e){let t=e.readLock??(()=>m(e.lockDir)),n=e.isAlive??y,r=e.sleep??(e=>tn(e)),i=e.spawn??_t,a=e.readErrorLog??Fc,o=e.openErrorLog??(e=>At(e,`w`)),s=e.closeFd??wt,l=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 jc(`localhost`,t)}let d=Pc(t(),n);if(d!==void 0)return jc(`localhost`,d);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);N(e.lockDir)||P(e.lockDir,{recursive:!0});let f=j(e.lockDir,c),p=o(f),h,g,_=st();try{try{h=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`}}),h.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),h.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let v=Date.now()+l;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=Pc(t(),n);if(e!==void 0)return jc(`localhost`,e)}if(g){let e=a(f),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}throw Error(Ic(l,a(f)))}function Vc(e,t){if(e.portOverride!==void 0)return Nc(t);let n=e.readLock??(()=>m(e.lockDir)),r=e.isAlive??y,i=Pc(n(),r);if(i!==void 0)return Mc(`localhost`,i)}async function Hc(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new rs(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new Dc(new URL(e),{fetch:Oc(r),requestInit:{headers:{...b({kind:`mcp`,runtimeVersion:_}),...t.connectionId===void 0?{}:{[Se]: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=Lc(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(zc(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=Rc(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 Uc(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Hc,r=await Bc(e),i=e.createConnectionId?.()??$t(),a=!1,o=(e.startKeepalive??$o)({connectionId:i,resolveWsUrl:async()=>Vc(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 Wc=qt(import.meta.url);function Gc(e){let t=M(e);for(;;){if(Be(t))return t;let n=yt(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${x}\`).`);t=n}}function Kc(e){try{let t=new URL(e);return t.protocol===`file:`?qt(t):void 0}catch{return}}async function qc(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=Kc(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Jc(e,t){if(e!==void 0)return Gc(e);let n=await t();if(n!==void 0)return Gc(n);throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.")}async function Yc(e){let t=process.stderr,n=e.spawnTimeoutMs??kc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=at({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new We({name:ze,version:_},{instructions:Ge({dir:`.`})});Xe(a);let o=$t(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=Le(e),r=s.current,i=$o({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Vc({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>qc({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>Jc(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=Gc(e)}else t=Gc(e);let a=await i(t),o=await Bc({lockDir:Le(t),contentDir:Me(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Ve(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},Ae(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new rs,m=!1,h,g=async()=>{if(m)return;m=!0,h?.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(),p.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(p),t.write(`[mcp] global stdio server ready (per-call project routing)
70
70
  `);let v=!1,y=()=>{v||(v=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
71
- `),process.exit(1)},5e3).unref(),g().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,y),process.once(`SIGTERM`,y),ss({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=os(Wc,{realpathSync:Mt,statInoSync:e=>Pt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${_}\n`);let{resolvedPath:n,inode:r}=e;h=as({detect:()=>is({bundleAnchorPath:Wc,currentInode:r,platform:process.platform,realpath:Mt,statInode:e=>Pt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${_} — exiting for host respawn\n`),y()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:g}}function Xc(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=kc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Uc({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=Xo(process.env,i,process.platform);if(a.proxy){let e=Yo(process.platform,zt(),{existsSync:N});if(e===null)Zo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Qo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Zo({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`;Zo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Yc({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 Zc(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-1nz8JsfK.mjs`),r=e(),i=process.cwd(),a=Me(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 Qc(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function $c(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function el(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:Ja(r),command:r,isDesktop:Qc(r)}}function tl(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function nl(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&tl(e)?`ui-orphan`:`stale`}const rl=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function il(e){switch(e){case`running`:return G.default.green(e);case`desktop`:return G.default.blue(e);case`foreign`:return G.default.cyan(e);case`ui-orphan`:return G.default.magenta(e);case`stale`:return G.default.yellow(e)}}function al(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ol(e){return`${al(e.server.usage)} | ${al(e.ui?.usage??null)}`}function sl(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function cl(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=nl(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,sl(e),ol(e),t,String(n),$c(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=il(nl(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=G.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
71
+ `),process.exit(1)},5e3).unref(),g().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,y),process.once(`SIGTERM`,y),ss({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=os(Wc,{realpathSync:Mt,statInoSync:e=>Pt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${_}\n`);let{resolvedPath:n,inode:r}=e;h=as({detect:()=>is({bundleAnchorPath:Wc,currentInode:r,platform:process.platform,realpath:Mt,statInode:e=>Pt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${_} — exiting for host respawn\n`),y()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:g}}function Xc(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=kc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Uc({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=Xo(process.env,i,process.platform);if(a.proxy){let e=Yo(process.platform,zt(),{existsSync:N});if(e===null)Zo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Qo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Zo({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`;Zo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Yc({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 Zc(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-CcHJG_2a.mjs`),r=e(),i=process.cwd(),a=Me(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 Qc(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function $c(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function el(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:Ja(r),command:r,isDesktop:Qc(r)}}function tl(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function nl(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&tl(e)?`ui-orphan`:`stale`}const rl=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function il(e){switch(e){case`running`:return G.default.green(e);case`desktop`:return G.default.blue(e);case`foreign`:return G.default.cyan(e);case`ui-orphan`:return G.default.magenta(e);case`stale`:return G.default.yellow(e)}}function al(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ol(e){return`${al(e.server.usage)} | ${al(e.ui?.usage??null)}`}function sl(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function cl(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=nl(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,sl(e),ol(e),t,String(n),$c(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=il(nl(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=G.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
72
72
  `)}async function ll(e={}){let t=e.discover??no,n=e.inspect??U,r=e.log??(e=>console.log(e)),i=e.resolveCommand??Ya,a=e.resolveUsage??Xa,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=el(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:nl(e)}));r(JSON.stringify(e,null,2));return}r(cl(e.all?s:s.filter(e=>rl.has(nl(e)))))}function ul(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await ll({all:t.all===!0||e===`all`,json:t.json===!0})})}function dl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function fl(e,t,n=process.cwd()){let r=e.op??`sync`,i=m(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`,...b({kind:`cli`,runtimeVersion:_})},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}`)}dl(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=xe({baseDir:n});if(r===`sync`||r===`pull`){dl(e.json,{type:`step`,step:`pull`});let t=await a.pull();dl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(dl(e.json,{type:`step`,step:`push`}),await a.push(),dl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
73
73
  `)),dl(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function pl(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 fl({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 ml(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await fl({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 hl(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await fl({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 gl(e){return typeof e==`string`&&Ke.includes(e)}async function _l(e={}){let t=M(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!Te[n])return{status:`failed`,message:`${D(`Error:`)} Unknown pack "${n}". Available: ${Ke.join(`, `)}`,exitCode:1};let r;try{r=await qe({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Oe?{status:`prerequisite-missing`,message:`${D(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${D(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=Te[n].name;return{status:`no-op`,message:`${E(`Your ${e} pack is already seeded.`)}\n${T(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${O(`Plan (dry-run — no changes made):`)}\n\n${yl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await bl(`${O(`Plan:`)}\n\n${yl(r,t)}\n\n${O(`Apply?`)} ${T(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:T(`Cancelled.`),plan:r,exitCode:0};let i=await Re(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${D(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${mt(`Applied`)} ${i.applied} entries, ${mt(String(i.errors.length))} error(s):`,...e].join(`
74
74
  `),plan:r,exitCode:1}}let a=Te[n].name;return{status:`applied`,message:`${E(`✓ Seeded ${a}`)} ${T(`(${i.applied} entries, ${i.durationMs}ms)`)}`,plan:r,exitCode:0}}function vl(){let e=[O(`Available packs:`)];for(let t of Ke){let n=Te[t];e.push(` ${E(t)} ${T(`—`)} ${n.name}: ${n.description}`)}return e.join(`
@@ -0,0 +1,2 @@
1
+ import"./server-lock-BpjJj3OD-B9uBbH7Z.mjs";var e=`0.9.0-beta.14`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-D9hc7LX4.mjs.map
@@ -1 +1 @@
1
- import{Br as e,Cn as t,K as n,Wr as r,a as i,an as a,bn as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,ln as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S,yr as C}from"./server-lock-BpjJj3OD-B9uBbH7Z.mjs";import{$ as w,$n as T,$r as E,$t as D,A as O,An as k,Ar as A,At as j,B as M,Bn as N,Br as P,Bt as F,C as I,Cn as L,Cr as R,Ct as z,D as B,Dn as V,Dr as H,Dt as U,E as W,En as G,Er as K,Et as q,F as J,Fn as Y,Fr as X,Ft as Z,G as Q,Gn as $,Gr as ee,Gt as te,H as ne,Hn as re,Hr as ie,Ht as ae,I as oe,In as se,Ir as ce,It as le,J as ue,Jn as de,Jr as fe,Jt as pe,K as me,Kn as he,Kr as ge,Kt as _e,L as ve,Ln as ye,Lr as be,Lt as xe,M as Se,Mn as Ce,Mr as we,Mt as Te,N as Ee,Nn as De,Nr as Oe,Nt as ke,O as Ae,On as je,Or as Me,Ot as Ne,P as Pe,Pn as Fe,Pr as Ie,Pt as Le,Q as Re,Qn as ze,Qr as Be,Qt as Ve,R as He,Rn as Ue,Rr as We,Rt as Ge,S as Ke,Sn as qe,Sr as Je,St as Ye,T as Xe,Ti as Ze,Tn as Qe,Tr as $e,Tt as et,U as tt,Un as nt,Ur as rt,Ut as it,V as at,Vn as ot,Vr as st,Vt as ct,W as lt,Wn as ut,Wr as dt,Wt as ft,X as pt,Xn as mt,Xr as ht,Xt as gt,Y as _t,Yn as vt,Yr as yt,Yt as bt,Z as xt,Zn as St,Zr as Ct,Zt as wt,_ as Tt,_n as Et,_r as Dt,_t as Ot,a as kt,ai as At,an as jt,ar as Mt,at as Nt,b as Pt,bn as Ft,br as It,bt as Lt,c as Rt,ci as zt,cn as Bt,cr as Vt,ct as Ht,d as Ut,di as Wt,dn as Gt,dr as Kt,dt as qt,ei as Jt,en as Yt,er as Xt,et as Zt,f as Qt,fi as $t,fn as en,fr as tn,ft as nn,g as rn,gn as an,gr as on,gt as sn,h as cn,hn as ln,hr as un,ht as dn,i as fn,ii as pn,in as mn,ir as hn,it as gn,j as _n,jn as vn,jr as yn,jt as bn,k as xn,kn as Sn,kr as Cn,kt as wn,l as Tn,li as En,ln as Dn,lr as On,lt as kn,m as An,mn as jn,mr as Mn,mt as Nn,n as Pn,ni as Fn,nn as In,nr as Ln,nt as Rn,o as zn,oi as Bn,on as Vn,or as Hn,ot as Un,p as Wn,pn as Gn,pr as Kn,pt as qn,q as Jn,qn as Yn,qr as Xn,qt as Zn,r as Qn,ri as $n,rn as er,rr as tr,rt as nr,s as rr,si as ir,sn as ar,sr as or,st as sr,t as cr,ti as lr,tn as ur,tr as dr,tt as fr,u as pr,ui as mr,un as hr,ur as gr,ut as _r,v as vr,vn as yr,vr as br,vt as xr,w as Sr,wi as Cr,wn as wr,wr as Tr,wt as Er,x as Dr,xn as Or,xr as kr,xt as Ar,y as jr,yn as Mr,yr as Nr,yt as Pr,z as Fr,zn as Ir,zr as Lr,zt as Rr}from"./dist-BBbP7DxV.mjs";export{cr as AGENT_ID_MAX_LEN,Pn as AGENT_ID_RE,Qn as AGENT_WRITE_ORIGIN,fn as AgentFocusBroadcaster,kt as AgentPresenceBroadcaster,zn as AgentSessionCapacityError,rr as AgentSessionManager,Rt as BacklinkIndex,Tn as CC1Broadcaster,n as CC1_CONTRACT_VERSION,pr as CONFIG_FILENAME,Ut as CONFLICT_MARKER_RE,Qt as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Wn as ConfigSchema,An as DEFAULT_CHECKPOINT_RETENTION,cn as DEFAULT_PACK_ID,rn as FILE_SYSTEM_WRITER,Tt as FILE_WATCHER_ORIGIN,vr as GIT_PREFLIGHT_FAIL_SPAN_NAME,jr as GIT_UPSTREAM_WRITER,Cr as GitDirAccessError,Pt as GitNotAvailableError,Dr as GitTooOldError,Ke as HOCUSPOCUS_AUTH_REJECTION_REASONS,I as HocuspocusAuthRejection,Sr as HocuspocusAuthTokenSchema,Xe as INSTALLED_AGENTS_SCHEMES,W as LIVE_DERIVED_INDEX_DEBOUNCE_MS,B as LOG_MD_TEMPLATE,Ae as MANAGED_RENAME_ORIGIN,xn as MAX_AGENT_SESSIONS,O as MCP_CONNECTION_ID_HEADER,_n as MCP_SERVER_NAME,Se as MIN_GIT_VERSION,Ee as MISSING_OK_CONFIG_MESSAGE,Ze as MalformedGitPointerError,Pe as McpLogger,J as MissingOkConfigError,oe as OBSERVER_SYNC_ORIGIN,ve as OK_OKIGNORE_TEMPLATE,a as ORPHAN_MODES,m as PROTOCOL_VERSION,He as PinoLogger,x as ProcessLockCollisionError,Fr as ProjectGitInitError,M as ROLLBACK_ORIGIN,at as ROOT_GITIGNORE_TEMPLATE,g as RUNTIME_VERSION,ne as SERVICE_WRITER,tt as SKILL_INSTALL_EVENTS_FILE_REL,o as SKILL_STATE_TARGETS,lt as STARTER_FOLDERS,Q as STARTER_FOLDER_FRONTMATTER_FILENAME,me as STARTER_PACKS,Jn as STARTER_PACK_IDS,ue as STARTER_TEMPLATES,_t as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,t as SYSTEM_DOC_NAME,pt as SeedPrerequisiteError,xt as SeedRootDirError,f as ServerLockCollisionError,Re as StateManifestError,w as TagIndex,Zt as UiLockCollisionError,i as acquireProcessLock,_ as acquireServerLock,fr as acquireUiLock,Rn as applyAgentMarkdownWrite,nr as applyExternalChange,gn as applySeed,Nt as assertCompatibleStateManifest,Un as assertGitAvailable,sr as assertNeverDiskEvent,Ht as attachIdleShutdown,kn as bootServer,_r as buildAndOpenSkill,qt as buildConfigYmlContent,nn as buildExecResult,qn as buildInstructions,Nn as buildSkillZip,dn as buildStarterFolderFrontmatterYaml,sn as buildWipTree,Ot as classifyEvents,xr as classifyFsPath,Pr as clearContributors,Lt as coercePackId,C as colorFromSeed,Ar as commitUpstreamImport,Ye as commitWip,z as commitWipFromTree,Er as compareSemver,et as containsConflictMarkers,q as contentHash,U as contributorCount,Ne as createApiExtension,wn as createAssetServeMiddleware,j as createContentFilter,bn as createContentFilterAsync,Te as createExternalChangeHandler,ke as createFileLogger,Le as createLiveDerivedIndexExtension,Z as createMcpHttpHandler,le as createOsProbe,xe as createPersistenceExtension,Ge as createServer,Rr as createServerObserverExtension,F as createStreamingErrorWriter,ct as createTestLogger,ae as detectClaudeDesktopPresence,it as detectGit,ft as detectProjectShape,te as emitPreflightFailureSpan,_e as ensureProjectGit,Zn as errorResponse,pe as evictStaleTrackerEntries,bt as extractWikiLinksFromMarkdown,gt as fallbackPaths,wt as findEnclosingGitRoot,Ve as findEnclosingProjectRoot,D as formatAuthRejectionWire,Yt as formatContributors,ur as formatContributorsFrom,In as gcCheckpointRefs,er as getCurrentMcpLogger,mn as getLocalDir,jt as getLogFilePath,Vn as getLogger,ar as getLogsDir,Bt as getMeter,Dn as getMetrics,hr as getTracer,Gt as handleCollabSocketError,en as handleSpawnCursor,e as iconFromClientName,Gn as incrementCollabSocketFilteredError,jn as incrementServerObserverFire,ln as initContent,an as initShadowRepo,Et as initTelemetry,yr as installPrettyZodErrors,Mr as installTestLoggers,Ft as installUserSkill,Or as isAllowedApiOrigin,qe as isAllowedWorkspaceHostHeader,L as isConfigDoc,wr as isHocuspocusAuthRejectionReason,Qe as isKnownPackId,G as isLoopbackAddress,r as isOrphanMode,V as isPairedWriteOrigin,je as isPathWithinDir,b as isProcessAlive,Sn as isProjectRoot,k as isSelfWrite,vn as isSystemDoc,s as isValidLockPid,Ce as lastKnownHash,De as listRescueCheckpoints,Fe as listStarterPacks,Y as loadPrincipal,p as lockFilePath,se as loggerFactory,ye as logsCurrentPath,Ue as logsPreviousPath,Ir as mountMcpAndApi,N as normalizeFsPath,ot as packageVersionMajorMinor,re as parseAuthRejectionWire,nt as parseGitVersion,ut as parseHocuspocusAuthToken,$ as parseKeepaliveConnectionId,he as pathToDocName,Yn as planSeed,de as readAllTargets,vt as readBranchFromHead,S as readProcessLock,c as readProcessLockDetailed,l as readServerLock,mt as readServerPackageVersion,St as readSkillInstallStateSnapshot,ze as readStateManifest,T as readTargetRecordedAt,Xt as readTargetVersion,dr as readUiLock,Ln as reconcile,tr as recordContributor,hn as recordSkillInstallEvent,Mt as registerAllTools,Hn as registerWrite,v as releaseProcessLock,h as releaseServerLock,or as releaseUiLock,Vt as removeLastKnownHash,On as resetMetrics,gr as resolveBundledSkillDir,Kt as resolveContentDir,tn as resolveCursorBinaryDefault,Kn as resolveCursorSpawnInvocation,Mn as resolveLockDir,un as resolvePack,on as resolvePackageVersion,Dt as restoreContributors,br as restoreLifecycleFromConflictsJson,Nr as rewriteMarkdownLinksForDocumentRename,It as rewriteWikiLinksForDocumentRename,kr as runAuthReposSubprocess,Je as runAuthStatusSubprocess,R as runCloneSubprocess,Tr as runDeviceFlowSubprocess,$e as runWithMcpLogger,K as safeContentPath,H as safeSubdir,Me as safetyCheckpoint,Cn as sanitizeClientName,A as saveInMemoryCheckpoint,yn as saveVersion,we as seedBasenameIndex,Oe as serializeError,Ie as setActiveSpanAttributes,X as shadowGit,ce as shutdownTelemetry,be as spansCurrentPath,We as spansPreviousPath,Lr as spawnDetached,P as splitMarkdownBlocks,st as startWatcher,ie as streamingProblemEvent,rt as swapContributors,dt as toBroadcasterKey,ee as tracedAppendFileSync,ge as tracedLinkSync,Xn as tracedMkdir,fe as tracedMkdirSync,yt as tracedRename,ht as tracedRenameSync,Ct as tracedRmSync,Be as tracedRmdirSync,E as tracedUnlinkSync,Jt as tracedWriteFile,lr as tracedWriteFileSync,Fn as updateLastKnownHash,d as updateProcessLockPort,u as updateServerLockPort,$n as updateUiLockPort,pn as validateAgentId,At as validateCloneInputs,Bn as validateSkillZip,ir as withSpan,zt as withSpanSync,En as writeRootGitignoreForNewRepo,mr as writeStateManifest,Wt as writeTargetVersion,$t as writeTracker};
1
+ import{Br as e,Cn as t,K as n,Wr as r,a as i,an as a,bn as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,ln as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S,yr as C}from"./server-lock-BpjJj3OD-B9uBbH7Z.mjs";import{$ as w,$n as T,$r as E,$t as D,A as O,An as k,Ar as A,At as j,B as M,Bn as N,Br as P,Bt as F,C as I,Cn as L,Cr as R,Ct as z,D as B,Dn as V,Dr as H,Dt as U,E as W,En as G,Er as K,Et as q,F as J,Fn as Y,Fr as X,Ft as Z,G as Q,Gn as $,Gr as ee,Gt as te,H as ne,Hn as re,Hr as ie,Ht as ae,I as oe,In as se,Ir as ce,It as le,J as ue,Jn as de,Jr as fe,Jt as pe,K as me,Kn as he,Kr as ge,Kt as _e,L as ve,Ln as ye,Lr as be,Lt as xe,M as Se,Mn as Ce,Mr as we,Mt as Te,N as Ee,Nn as De,Nr as Oe,Nt as ke,O as Ae,On as je,Or as Me,Ot as Ne,P as Pe,Pn as Fe,Pr as Ie,Pt as Le,Q as Re,Qn as ze,Qr as Be,Qt as Ve,R as He,Rn as Ue,Rr as We,Rt as Ge,S as Ke,Sn as qe,Sr as Je,St as Ye,T as Xe,Ti as Ze,Tn as Qe,Tr as $e,Tt as et,U as tt,Un as nt,Ur as rt,Ut as it,V as at,Vn as ot,Vr as st,Vt as ct,W as lt,Wn as ut,Wr as dt,Wt as ft,X as pt,Xn as mt,Xr as ht,Xt as gt,Y as _t,Yn as vt,Yr as yt,Yt as bt,Z as xt,Zn as St,Zr as Ct,Zt as wt,_ as Tt,_n as Et,_r as Dt,_t as Ot,a as kt,ai as At,an as jt,ar as Mt,at as Nt,b as Pt,bn as Ft,br as It,bt as Lt,c as Rt,ci as zt,cn as Bt,cr as Vt,ct as Ht,d as Ut,di as Wt,dn as Gt,dr as Kt,dt as qt,ei as Jt,en as Yt,er as Xt,et as Zt,f as Qt,fi as $t,fn as en,fr as tn,ft as nn,g as rn,gn as an,gr as on,gt as sn,h as cn,hn as ln,hr as un,ht as dn,i as fn,ii as pn,in as mn,ir as hn,it as gn,j as _n,jn as vn,jr as yn,jt as bn,k as xn,kn as Sn,kr as Cn,kt as wn,l as Tn,li as En,ln as Dn,lr as On,lt as kn,m as An,mn as jn,mr as Mn,mt as Nn,n as Pn,ni as Fn,nn as In,nr as Ln,nt as Rn,o as zn,oi as Bn,on as Vn,or as Hn,ot as Un,p as Wn,pn as Gn,pr as Kn,pt as qn,q as Jn,qn as Yn,qr as Xn,qt as Zn,r as Qn,ri as $n,rn as er,rr as tr,rt as nr,s as rr,si as ir,sn as ar,sr as or,st as sr,t as cr,ti as lr,tn as ur,tr as dr,tt as fr,u as pr,ui as mr,un as hr,ur as gr,ut as _r,v as vr,vn as yr,vr as br,vt as xr,w as Sr,wi as Cr,wn as wr,wr as Tr,wt as Er,x as Dr,xn as Or,xr as kr,xt as Ar,y as jr,yn as Mr,yr as Nr,yt as Pr,z as Fr,zn as Ir,zr as Lr,zt as Rr}from"./dist-DKgq69uI.mjs";export{cr as AGENT_ID_MAX_LEN,Pn as AGENT_ID_RE,Qn as AGENT_WRITE_ORIGIN,fn as AgentFocusBroadcaster,kt as AgentPresenceBroadcaster,zn as AgentSessionCapacityError,rr as AgentSessionManager,Rt as BacklinkIndex,Tn as CC1Broadcaster,n as CC1_CONTRACT_VERSION,pr as CONFIG_FILENAME,Ut as CONFLICT_MARKER_RE,Qt as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Wn as ConfigSchema,An as DEFAULT_CHECKPOINT_RETENTION,cn as DEFAULT_PACK_ID,rn as FILE_SYSTEM_WRITER,Tt as FILE_WATCHER_ORIGIN,vr as GIT_PREFLIGHT_FAIL_SPAN_NAME,jr as GIT_UPSTREAM_WRITER,Cr as GitDirAccessError,Pt as GitNotAvailableError,Dr as GitTooOldError,Ke as HOCUSPOCUS_AUTH_REJECTION_REASONS,I as HocuspocusAuthRejection,Sr as HocuspocusAuthTokenSchema,Xe as INSTALLED_AGENTS_SCHEMES,W as LIVE_DERIVED_INDEX_DEBOUNCE_MS,B as LOG_MD_TEMPLATE,Ae as MANAGED_RENAME_ORIGIN,xn as MAX_AGENT_SESSIONS,O as MCP_CONNECTION_ID_HEADER,_n as MCP_SERVER_NAME,Se as MIN_GIT_VERSION,Ee as MISSING_OK_CONFIG_MESSAGE,Ze as MalformedGitPointerError,Pe as McpLogger,J as MissingOkConfigError,oe as OBSERVER_SYNC_ORIGIN,ve as OK_OKIGNORE_TEMPLATE,a as ORPHAN_MODES,m as PROTOCOL_VERSION,He as PinoLogger,x as ProcessLockCollisionError,Fr as ProjectGitInitError,M as ROLLBACK_ORIGIN,at as ROOT_GITIGNORE_TEMPLATE,g as RUNTIME_VERSION,ne as SERVICE_WRITER,tt as SKILL_INSTALL_EVENTS_FILE_REL,o as SKILL_STATE_TARGETS,lt as STARTER_FOLDERS,Q as STARTER_FOLDER_FRONTMATTER_FILENAME,me as STARTER_PACKS,Jn as STARTER_PACK_IDS,ue as STARTER_TEMPLATES,_t as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,t as SYSTEM_DOC_NAME,pt as SeedPrerequisiteError,xt as SeedRootDirError,f as ServerLockCollisionError,Re as StateManifestError,w as TagIndex,Zt as UiLockCollisionError,i as acquireProcessLock,_ as acquireServerLock,fr as acquireUiLock,Rn as applyAgentMarkdownWrite,nr as applyExternalChange,gn as applySeed,Nt as assertCompatibleStateManifest,Un as assertGitAvailable,sr as assertNeverDiskEvent,Ht as attachIdleShutdown,kn as bootServer,_r as buildAndOpenSkill,qt as buildConfigYmlContent,nn as buildExecResult,qn as buildInstructions,Nn as buildSkillZip,dn as buildStarterFolderFrontmatterYaml,sn as buildWipTree,Ot as classifyEvents,xr as classifyFsPath,Pr as clearContributors,Lt as coercePackId,C as colorFromSeed,Ar as commitUpstreamImport,Ye as commitWip,z as commitWipFromTree,Er as compareSemver,et as containsConflictMarkers,q as contentHash,U as contributorCount,Ne as createApiExtension,wn as createAssetServeMiddleware,j as createContentFilter,bn as createContentFilterAsync,Te as createExternalChangeHandler,ke as createFileLogger,Le as createLiveDerivedIndexExtension,Z as createMcpHttpHandler,le as createOsProbe,xe as createPersistenceExtension,Ge as createServer,Rr as createServerObserverExtension,F as createStreamingErrorWriter,ct as createTestLogger,ae as detectClaudeDesktopPresence,it as detectGit,ft as detectProjectShape,te as emitPreflightFailureSpan,_e as ensureProjectGit,Zn as errorResponse,pe as evictStaleTrackerEntries,bt as extractWikiLinksFromMarkdown,gt as fallbackPaths,wt as findEnclosingGitRoot,Ve as findEnclosingProjectRoot,D as formatAuthRejectionWire,Yt as formatContributors,ur as formatContributorsFrom,In as gcCheckpointRefs,er as getCurrentMcpLogger,mn as getLocalDir,jt as getLogFilePath,Vn as getLogger,ar as getLogsDir,Bt as getMeter,Dn as getMetrics,hr as getTracer,Gt as handleCollabSocketError,en as handleSpawnCursor,e as iconFromClientName,Gn as incrementCollabSocketFilteredError,jn as incrementServerObserverFire,ln as initContent,an as initShadowRepo,Et as initTelemetry,yr as installPrettyZodErrors,Mr as installTestLoggers,Ft as installUserSkill,Or as isAllowedApiOrigin,qe as isAllowedWorkspaceHostHeader,L as isConfigDoc,wr as isHocuspocusAuthRejectionReason,Qe as isKnownPackId,G as isLoopbackAddress,r as isOrphanMode,V as isPairedWriteOrigin,je as isPathWithinDir,b as isProcessAlive,Sn as isProjectRoot,k as isSelfWrite,vn as isSystemDoc,s as isValidLockPid,Ce as lastKnownHash,De as listRescueCheckpoints,Fe as listStarterPacks,Y as loadPrincipal,p as lockFilePath,se as loggerFactory,ye as logsCurrentPath,Ue as logsPreviousPath,Ir as mountMcpAndApi,N as normalizeFsPath,ot as packageVersionMajorMinor,re as parseAuthRejectionWire,nt as parseGitVersion,ut as parseHocuspocusAuthToken,$ as parseKeepaliveConnectionId,he as pathToDocName,Yn as planSeed,de as readAllTargets,vt as readBranchFromHead,S as readProcessLock,c as readProcessLockDetailed,l as readServerLock,mt as readServerPackageVersion,St as readSkillInstallStateSnapshot,ze as readStateManifest,T as readTargetRecordedAt,Xt as readTargetVersion,dr as readUiLock,Ln as reconcile,tr as recordContributor,hn as recordSkillInstallEvent,Mt as registerAllTools,Hn as registerWrite,v as releaseProcessLock,h as releaseServerLock,or as releaseUiLock,Vt as removeLastKnownHash,On as resetMetrics,gr as resolveBundledSkillDir,Kt as resolveContentDir,tn as resolveCursorBinaryDefault,Kn as resolveCursorSpawnInvocation,Mn as resolveLockDir,un as resolvePack,on as resolvePackageVersion,Dt as restoreContributors,br as restoreLifecycleFromConflictsJson,Nr as rewriteMarkdownLinksForDocumentRename,It as rewriteWikiLinksForDocumentRename,kr as runAuthReposSubprocess,Je as runAuthStatusSubprocess,R as runCloneSubprocess,Tr as runDeviceFlowSubprocess,$e as runWithMcpLogger,K as safeContentPath,H as safeSubdir,Me as safetyCheckpoint,Cn as sanitizeClientName,A as saveInMemoryCheckpoint,yn as saveVersion,we as seedBasenameIndex,Oe as serializeError,Ie as setActiveSpanAttributes,X as shadowGit,ce as shutdownTelemetry,be as spansCurrentPath,We as spansPreviousPath,Lr as spawnDetached,P as splitMarkdownBlocks,st as startWatcher,ie as streamingProblemEvent,rt as swapContributors,dt as toBroadcasterKey,ee as tracedAppendFileSync,ge as tracedLinkSync,Xn as tracedMkdir,fe as tracedMkdirSync,yt as tracedRename,ht as tracedRenameSync,Ct as tracedRmSync,Be as tracedRmdirSync,E as tracedUnlinkSync,Jt as tracedWriteFile,lr as tracedWriteFileSync,Fn as updateLastKnownHash,d as updateProcessLockPort,u as updateServerLockPort,$n as updateUiLockPort,pn as validateAgentId,At as validateCloneInputs,Bn as validateSkillZip,ir as withSpan,zt as withSpanSync,En as writeRootGitignoreForNewRepo,mr as writeStateManifest,Wt as writeTargetVersion,$t as writeTracker};