@inkeep/open-knowledge 0.9.2-beta.10 → 0.9.2-beta.8

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 (44) 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 +12 -12
  4. package/dist/constants-Dz5iTLUD.mjs +2 -0
  5. package/dist/{dist-jwEG_6T7.mjs → dist-Bj_IaFF5.mjs} +1 -1
  6. package/dist/{dist-CILctbXr.mjs → dist-sld-_d9T.mjs} +70 -73
  7. package/dist/{gh-detect-DCIXLWuz.mjs → gh-detect-BveVRAue.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-CUcCpmsn.mjs → init-BjjtQpJ4.mjs} +6 -6
  10. package/dist/init-CxAAKK9q.mjs +1 -0
  11. package/dist/{loader-BCv9KNqV.mjs → loader-BSyhsuGY.mjs} +2 -2
  12. package/dist/loader-D6ZQW0bM.mjs +1 -0
  13. package/dist/{preview-DPstoQIF.mjs → preview-C6kOnHJr.mjs} +2 -2
  14. package/dist/preview-DRATXrPN.mjs +1 -0
  15. package/dist/public/assets/{ActivityModeContent-BS7V4qxK.js → ActivityModeContent-ryZpdhrg.js} +1 -1
  16. package/dist/public/assets/{DocumentContext-BITHYueY.js → DocumentContext-B0qDv4j7.js} +1 -1
  17. package/dist/public/assets/{GraphPanel-OqhIPCR-.js → GraphPanel-DUQL1b5J.js} +1 -1
  18. package/dist/public/assets/{SettingsDialogBody-CFdp-KB6.js → SettingsDialogBody-D3PLgmQr.js} +1 -1
  19. package/dist/public/assets/{SourceEditor-CFy3TwZl.js → SourceEditor-DOh6wSxy.js} +1 -1
  20. package/dist/public/assets/{config-validation-events-BPrwAxE8.js → config-validation-events-S5hCYFuT.js} +1 -1
  21. package/dist/public/assets/{index-vPoUqMuk.js → index-C1LyLfKJ.js} +5 -5
  22. package/dist/public/assets/{keyboard-shortcuts-AT0jBk2u.js → keyboard-shortcuts-xl_TcQeg.js} +1 -1
  23. package/dist/public/assets/{prop-types-N7Ts5qWw.js → prop-types-DgfF561f.js} +110 -110
  24. package/dist/public/assets/{target-navigation-intent-DQhKf-lZ.js → target-navigation-intent-D3XZeIgO.js} +1 -1
  25. package/dist/public/assets/{typing-burst-detector-CycCFGLG.js → typing-burst-detector-D53pUunD.js} +1 -1
  26. package/dist/public/index.html +7 -7
  27. package/dist/{repair-launch-json-DCk5kTOp.mjs → repair-launch-json-CBHiWTWu.mjs} +2 -2
  28. package/dist/{repair-mcp-configs-DRGW4wJG.mjs → repair-mcp-configs-s94bDnZZ.mjs} +2 -2
  29. package/dist/repair-skills-B9lFVB-G.mjs +1 -0
  30. package/dist/{repair-skills-8cPy8M95.mjs → repair-skills-BP58ginR.mjs} +2 -2
  31. package/dist/{server-lock-BpjJj3OD-DBIqFE7p.mjs → server-lock-BpjJj3OD-2pOoEhSP.mjs} +3 -3
  32. package/dist/server-lock-CyhBidkz-Blwoi-6-.mjs +1 -0
  33. package/dist/{src-CwDGjVlW.mjs → src-B1QW6YWQ.mjs} +2 -2
  34. package/dist/{start-BH5qbvRW.mjs → start-7bpluiOA.mjs} +2 -2
  35. package/dist/start-BjSIXm8g.mjs +1 -0
  36. package/dist/{write-project-skill-Da4v8WUu.mjs → write-project-skill-ppRYJ9T2.mjs} +2 -2
  37. package/package.json +1 -1
  38. package/dist/constants-BcktYfXJ.mjs +0 -2
  39. package/dist/init-DcESVtGW.mjs +0 -1
  40. package/dist/loader-F1SNlrhF.mjs +0 -1
  41. package/dist/preview-BcqzxVzi.mjs +0 -1
  42. package/dist/repair-skills-CTGGxNTm.mjs +0 -1
  43. package/dist/server-lock-CyhBidkz-DbELIlyl.mjs +0 -1
  44. package/dist/start-9-UwiAwy.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.2-beta.10"
6
+ version: "0.9.2-beta.8"
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.2-beta.10"
6
+ version: "0.9.2-beta.8"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Br as n,Gi as r,Hi as i,Ii as a,Li as o,Mi as s,Qi as c,Ri as l,Ui as u,Wi as d,Yi as f,bi as p,f as m,ga as h,ha as g,n as _,s as v,ta as y,vr as b,wi as x,yi as S,yn as ee}from"./server-lock-BpjJj3OD-DBIqFE7p.mjs";import{a as te,n as C,r as ne,t as re}from"./gh-detect-DCIXLWuz.mjs";import{n as ie,r as ae,t as w}from"./dist-bundle-BK4P1EQn.mjs";import{B as oe,C as se,E as ce,F as le,H as ue,I as de,L as fe,M as pe,N as me,P as he,R as ge,S as _e,T as ve,V as ye,b as be,u as xe,v as Se,w as Ce,z as we}from"./init-CUcCpmsn.mjs";import{r as Te}from"./git-handle-BSAUg1L_-CUJRlGhd.mjs";import{A as Ee,Ai as De,Ci as Oe,Di as ke,Ei as Ae,Ii as je,In as Me,J as Ne,Mi as Pe,Ni as Fe,Pi as Ie,Qt as Le,Rr as Re,Rt as ze,Si as Be,Sn as Ve,Sr as He,Ti as Ue,Tn as We,Tr as Ge,Z as Ke,Zt as qe,_t as Je,b as Ye,dn as Xe,er as Ze,h as Qe,j as $e,mt as et,pr as tt,q as nt,st as rt,ut as it,wi as at,x as ot,yr as st}from"./dist-CILctbXr.mjs";import{t as ct}from"./yazl-DjRp4wSy.mjs";import{a as lt,c as ut,f as dt,i as ft,o as pt,p as mt,s as ht}from"./src-CwDGjVlW.mjs";import{n as gt,t as _t}from"./constants-BcktYfXJ.mjs";import{n as vt,t as yt}from"./loader-BCv9KNqV.mjs";import{_ as bt,b as xt,f as St,h as Ct,v as wt,y as Tt}from"./start-BH5qbvRW.mjs";import{c as Et,i as T,n as E,o as D,r as Dt,s as O,t as k}from"./colors-BtKMHmBX.mjs";import{n as Ot}from"./repair-skills-8cPy8M95.mjs";import{execSync as kt,spawn as A,spawnSync as j}from"node:child_process";import At,{basename as M,dirname as jt,join as N,relative as Mt,resolve as P,sep as Nt}from"node:path";import{accessSync as Pt,closeSync as Ft,constants as It,cpSync as Lt,createWriteStream as Rt,existsSync as F,mkdirSync as I,mkdtempSync as zt,openSync as Bt,readFileSync as L,readdirSync as Vt,realpathSync as Ht,rmSync as Ut,statSync as Wt,unlinkSync as Gt,writeFileSync as R}from"node:fs";import Kt from"node:process";import{arch as qt,freemem as Jt,homedir as Yt,platform as Xt,release as Zt,tmpdir as Qt,totalmem as $t,type as en,uptime as tn}from"node:os";import{fileURLToPath as nn}from"node:url";import{AsyncLocalStorage as rn,AsyncResource as an}from"node:async_hooks";import{stripVTControlCharacters as on,styleText as z}from"node:util";import*as sn from"node:readline";import{createHash as cn,randomUUID as ln}from"node:crypto";import{setTimeout as un}from"node:timers/promises";import{createInterface as dn}from"node:readline/promises";async function fn(e,t,n){let r=pn(await mn(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 pn(e){let t={};for(let n of e.split(`
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 mn(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function hn(e){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 fn(process.stdin,process.stdout,t);process.exit(n)}),n}function gn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function _n(e,t,n){let r={baseUrl:gn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ie(`${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 vn(e){let t=e.request||w,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),_n(t,`POST /login/device/code`,n)}async function yn(e){let t=await _n(e.request||w,`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=bn(e,t.data.expires_in),n.refreshTokenExpiresAt=bn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function bn(e,t){return new Date(e+t*1e3).toISOString()}async function xn(e,t){let n=Sn(e,t.auth);if(n)return n;let{data:r}=await vn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await wn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Sn(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 Cn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function wn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await yn({...i,clientType:`oauth-app`}):await yn({...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 Cn(r.interval),wn(e,t,n,r);if(a===`slow_down`)return await Cn(r.interval+7),wn(e,t,n,r);throw i}}async function Tn(e,t){return xn(e,{auth:t})}async function En(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 xn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Dn=`0.0.0-development`;function On(e){let t=e.request||w.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Dn} ${ae()}`}}),{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(Tn.bind(null,i),{hook:En.bind(null,i)})}async function kn(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=On({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 An={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 jn;(function(e){})(jn||={});function Mn(e){return y(s,e)}function Nn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Pn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function B(e){let t=e.toLowerCase().replace(/:\d+$/,``);Pn.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 Fn(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function In(e,t,n=kn){let r=Nn(),{host:i,json:a}=e;B(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?Fn(!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?Fn(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function Ln(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 In(t,await e())})}const Rn=e=>e.name===`enter`||e.name===`return`;var zn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Bn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Vn=class extends Error{name=`ExitPromptError`},Hn=class extends Error{name=`HookError`},Un=class extends Error{name=`ValidationError`};const Wn=new rn;function Gn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Kn(e,t){let n=Gn(e);return Wn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function V(){let e=Wn.getStore();if(!e)throw new Hn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function qn(){return V().rl}function Jn(e){return an.bind((...t)=>{let n=V(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Yn(e){let t=V(),{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 Xn(){V().handleChange()}const Zn={queue(e){let t=V(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(qn());if(r!=null&&typeof r!=`function`)throw new Un(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=V();Jn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=V();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Qn(e){return typeof e==`function`}function H(e){return Yn(t=>{let n=an.bind(function(e){t.get()!==e&&(t.set(e),Xn())});if(t.initialized)return[t.get(),n];let r=Qn(e)?e():e;return t.set(r),[r,n]})}function $n(e,t){Yn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Zn.queue(e),n.set(t)})}const er={prefix:{idle:z(`blue`,`?`),done:z(`green`,ue.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>z(`yellow`,e))},style:{answer:e=>z(`cyan`,e),message:e=>z(`bold`,e),error:e=>z(`red`,`> ${e}`),defaultAnswer:e=>z(`dim`,`(${e})`),help:e=>z(`dim`,e),highlight:e=>z(`cyan`,e),key:e=>z(`cyan`,z(`bold`,`<${e}>`))}};function tr(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function nr(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=tr(n)&&tr(r)?nr(n,r):r}return t}function rr(...e){return nr(er,...e.filter(e=>e!=null))}function ir({status:e=`idle`,theme:t}){let[n,r]=H(!1),[i,a]=H(0),{prefix:o,spinner:s}=rr(t);return $n(()=>{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 ar(e){return H({current:e})[0]}function or(e){let t=ar(e);t.current=e,$n(e=>{let n=!1,r=Jn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var sr=e(ye(),1);function cr(e,t){return e.split(`
2
+ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Br as n,Gi as r,Hi as i,Ii as a,Li as o,Mi as s,Qi as c,Ri as l,Ui as u,Wi as d,Yi as f,bi as p,bn as m,f as h,ga as g,ha as _,n as v,s as y,ta as b,vr as x,wi as S,yi as ee}from"./server-lock-BpjJj3OD-2pOoEhSP.mjs";import{a as te,n as C,r as ne,t as re}from"./gh-detect-BveVRAue.mjs";import{n as ie,r as ae,t as w}from"./dist-bundle-BK4P1EQn.mjs";import{B as oe,C as se,E as ce,F as le,H as ue,I as de,L as fe,M as pe,N as me,P as he,R as ge,S as _e,T as ve,V as ye,b as be,u as xe,v as Se,w as Ce,z as we}from"./init-BjjtQpJ4.mjs";import{r as Te}from"./git-handle-BSAUg1L_-CUJRlGhd.mjs";import{A as Ee,Ai as De,Ci as Oe,Di as ke,Ei as Ae,Ii as je,In as Me,J as Ne,Mi as Pe,Ni as Fe,Pi as Ie,Qt as Le,Rr as Re,Rt as ze,Si as Be,Sn as Ve,Sr as He,Ti as Ue,Tn as We,Tr as Ge,Z as Ke,Zt as qe,_t as Je,b as Ye,dn as Xe,er as Ze,h as Qe,j as $e,mt as et,pr as tt,q as nt,st as rt,ut as it,wi as at,x as ot,yr as st}from"./dist-sld-_d9T.mjs";import{t as ct}from"./yazl-DjRp4wSy.mjs";import{a as lt,c as ut,f as dt,i as ft,o as pt,p as mt,s as ht}from"./src-B1QW6YWQ.mjs";import{n as gt,t as _t}from"./constants-Dz5iTLUD.mjs";import{n as vt,t as yt}from"./loader-BSyhsuGY.mjs";import{_ as bt,b as xt,f as St,h as Ct,v as wt,y as Tt}from"./start-7bpluiOA.mjs";import{c as Et,i as T,n as E,o as D,r as Dt,s as O,t as k}from"./colors-BtKMHmBX.mjs";import{n as Ot}from"./repair-skills-BP58ginR.mjs";import{execSync as kt,spawn as A,spawnSync as j}from"node:child_process";import At,{basename as M,dirname as jt,join as N,relative as Mt,resolve as P,sep as Nt}from"node:path";import{accessSync as Pt,closeSync as Ft,constants as It,cpSync as Lt,createWriteStream as Rt,existsSync as F,mkdirSync as I,mkdtempSync as zt,openSync as Bt,readFileSync as L,readdirSync as Vt,realpathSync as Ht,rmSync as Ut,statSync as Wt,unlinkSync as Gt,writeFileSync as R}from"node:fs";import Kt from"node:process";import{arch as qt,freemem as Jt,homedir as Yt,platform as Xt,release as Zt,tmpdir as Qt,totalmem as $t,type as en,uptime as tn}from"node:os";import{fileURLToPath as nn}from"node:url";import{AsyncLocalStorage as rn,AsyncResource as an}from"node:async_hooks";import{stripVTControlCharacters as on,styleText as z}from"node:util";import*as sn from"node:readline";import{createHash as cn,randomUUID as ln}from"node:crypto";import{setTimeout as un}from"node:timers/promises";import{createInterface as dn}from"node:readline/promises";async function fn(e,t,n){let r=pn(await mn(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 pn(e){let t={};for(let n of e.split(`
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 mn(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function hn(e){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 fn(process.stdin,process.stdout,t);process.exit(n)}),n}function gn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function _n(e,t,n){let r={baseUrl:gn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ie(`${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 vn(e){let t=e.request||w,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),_n(t,`POST /login/device/code`,n)}async function yn(e){let t=await _n(e.request||w,`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=bn(e,t.data.expires_in),n.refreshTokenExpiresAt=bn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function bn(e,t){return new Date(e+t*1e3).toISOString()}async function xn(e,t){let n=Sn(e,t.auth);if(n)return n;let{data:r}=await vn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await wn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Sn(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 Cn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function wn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await yn({...i,clientType:`oauth-app`}):await yn({...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 Cn(r.interval),wn(e,t,n,r);if(a===`slow_down`)return await Cn(r.interval+7),wn(e,t,n,r);throw i}}async function Tn(e,t){return xn(e,{auth:t})}async function En(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 xn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Dn=`0.0.0-development`;function On(e){let t=e.request||w.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Dn} ${ae()}`}}),{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(Tn.bind(null,i),{hook:En.bind(null,i)})}async function kn(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=On({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 An={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 jn;(function(e){})(jn||={});function Mn(e){return b(s,e)}function Nn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Pn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function B(e){let t=e.toLowerCase().replace(/:\d+$/,``);Pn.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 Fn(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function In(e,t,n=kn){let r=Nn(),{host:i,json:a}=e;B(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?Fn(!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?Fn(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function Ln(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 In(t,await e())})}const Rn=e=>e.name===`enter`||e.name===`return`;var zn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Bn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Vn=class extends Error{name=`ExitPromptError`},Hn=class extends Error{name=`HookError`},Un=class extends Error{name=`ValidationError`};const Wn=new rn;function Gn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Kn(e,t){let n=Gn(e);return Wn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function V(){let e=Wn.getStore();if(!e)throw new Hn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function qn(){return V().rl}function Jn(e){return an.bind((...t)=>{let n=V(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Yn(e){let t=V(),{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 Xn(){V().handleChange()}const Zn={queue(e){let t=V(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(qn());if(r!=null&&typeof r!=`function`)throw new Un(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=V();Jn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=V();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Qn(e){return typeof e==`function`}function H(e){return Yn(t=>{let n=an.bind(function(e){t.get()!==e&&(t.set(e),Xn())});if(t.initialized)return[t.get(),n];let r=Qn(e)?e():e;return t.set(r),[r,n]})}function $n(e,t){Yn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Zn.queue(e),n.set(t)})}const er={prefix:{idle:z(`blue`,`?`),done:z(`green`,ue.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>z(`yellow`,e))},style:{answer:e=>z(`cyan`,e),message:e=>z(`bold`,e),error:e=>z(`red`,`> ${e}`),defaultAnswer:e=>z(`dim`,`(${e})`),help:e=>z(`dim`,e),highlight:e=>z(`cyan`,e),key:e=>z(`cyan`,z(`bold`,`<${e}>`))}};function tr(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function nr(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=tr(n)&&tr(r)?nr(n,r):r}return t}function rr(...e){return nr(er,...e.filter(e=>e!=null))}function ir({status:e=`idle`,theme:t}){let[n,r]=H(!1),[i,a]=H(0),{prefix:o,spinner:s}=rr(t);return $n(()=>{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 ar(e){return H({current:e})[0]}function or(e){let t=ar(e);t.current=e,$n(e=>{let n=!1,r=Jn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var sr=e(ye(),1);function cr(e,t){return e.split(`
4
4
  `).flatMap(e=>oe(e,t,{trim:!1,hard:!0}).split(`
5
5
  `).map(e=>e.trimEnd())).join(`
6
6
  `)}function lr(){return(0,sr.default)({defaultWidth:80,output:qn().output})}const ur=e=>e.split(`
@@ -20,7 +20,7 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
20
20
  `),patterns:[...t],lineCount:n}}const Di=N(Yt(),`.ok`,`logs`),Oi=N(Yt(),`.ok`,`bug-reports`);function ki(e){let t=N(e,`.ok`,`config.yml`);if(F(t))try{let e=L(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return F(N(e,`.ok`))?cn(`sha256`).update(P(e)).digest(`hex`).slice(0,12):null}function Ai(){let e={timestamp:new Date().toISOString(),platform:Xt(),osType:en(),osRelease:Zt(),hostname:`[redacted]`,uptime:tn(),freeMem:Jt(),totalMem:$t(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=kt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);F(t)&&(e.okVersion=JSON.parse(L(t,`utf8`)).version)}catch{}return e}function ji(e){if(!F(Di))return{files:[],dir:Di};let t=Vt(Di).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(Di,e));if(e&&t.length>0){let n=t.filter(t=>{try{return L(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:Di}}function Mi(e){let t=N(e,`.ok`,`local`);return F(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>N(t,e)).filter(e=>F(e)),dir:t}:{files:[],dir:null}}function Ni(e){let t=N(e,`.ok`,`local`,`logs`);return F(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>F(e)),dir:t}:{files:[],dir:null}}async function Pi(t){let n=Rl();I(Oi,{recursive:!0});let r=N(Oi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Ai(),{files:a}=ji(t.projectSlug),{files:o}=Mi(t.cwd),{files:s}=Ni(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}=Ei(L(e,`utf8`)),i=`logs/${M(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}=Ei(L(e,`utf8`)),i=`lockdir/${M(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}=Ei(L(e,`utf8`)),i=`local-logs/${M(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: ${Ti.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=Rt(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&&Xt()===`darwin`)try{A(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function Fi(){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=ki(t);try{await Pi({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 Ii(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 Li(e){let t=e.inspect??(t=>mt(e.lockDir,t)),n=e.unlink??(e=>Gt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ii(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 Ri(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Li({lockDir:He(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function zi(e,t,n={},r=re){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 Bi(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 Vi=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Hi(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 Vi)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function G(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function Ui(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const Wi=n;async function Gi(e){try{return await e.clone(Ui(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&Wi(t))return e.onFallback(e.branch),await e.clone(Ui(null)),{fellBack:!0};throw t}}function Ki(e,t,n){return e===`https`&&t===`github.com`&&n}async function qi(e,t,n,r=process.cwd()){let i=dt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?P(r,t.dir):P(r,i.name);if(F(a)&&Vt(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=te(),s=i.protocol===`https`&&i.hostname===`github.com`?await Bi(i.owner,i.name):!1,c=Ki(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await zi(i.hostname,o,{}),l=Te({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=Hi(e);n&&n.pct!==u&&(u=n.pct,G(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await Gi({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>l.clone(e,a,t),onFallback:e=>{G(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-DcESVtGW.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?G(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?G(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Ji(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?G(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Ji(e){let t=be(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function Yi(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 qi(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)G(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-9-UwiAwy.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?G(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var Xi=h();const Zi=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...p.map(e=>e.path)];function Qi(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??vt;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 $i(e){let t=(0,Xi.parseDocument)(L(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 Zi)t.hasIn(e)&&n.push(e.join(`.`));return n}function ea(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ta(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=ea(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function na(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??Pe,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:De(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:De(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=$i(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:ta(Zi.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:x(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 ra(){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(()=>{Qi({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await na({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var ia=e(ct(),1),K=e(Et(),1);const aa=new Set([`doc.name`]);function oa(e){return`doc:${cn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function sa(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 ca(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=oa(e);return t.originalToHashed.set(e,r),sa(t,e,r),r}function la(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function da(e,t){if(typeof e==`string`)return la(e,t.contentDir);if(Array.isArray(e))return e.map(e=>da(e,t));if(!ua(e))return e;let n=typeof e.key==`string`&&aa.has(e.key)&&ua(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`&&ua(a)){let e=ca(n,t);r[i]={...a,stringValue:e}}else aa.has(i)&&typeof a==`string`?r[i]=ca(a,t):r[i]=da(a,t);return r}function fa(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function pa(e,t){let n=L(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
23
+ `);try{let{runInit:e}=await import(`./init-CxAAKK9q.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?G(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?G(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Ji(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?G(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Ji(e){let t=be(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function Yi(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 qi(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)G(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BjSIXm8g.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?G(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var Xi=g();const Zi=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...p.map(e=>e.path)];function Qi(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??vt;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 $i(e){let t=(0,Xi.parseDocument)(L(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 Zi)t.hasIn(e)&&n.push(e.join(`.`));return n}function ea(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ta(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=ea(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function na(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??Pe,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:De(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:De(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=$i(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:ta(Zi.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:S(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 ra(){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(()=>{Qi({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await na({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var ia=e(ct(),1),K=e(Et(),1);const aa=new Set([`doc.name`]);function oa(e){return`doc:${cn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function sa(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 ca(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=oa(e);return t.originalToHashed.set(e,r),sa(t,e,r),r}function la(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function da(e,t){if(typeof e==`string`)return la(e,t.contentDir);if(Array.isArray(e))return e.map(e=>da(e,t));if(!ua(e))return e;let n=typeof e.key==`string`&&aa.has(e.key)&&ua(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`&&ua(a)){let e=ca(n,t);r[i]={...a,stringValue:e}}else aa.has(i)&&typeof a==`string`?r[i]=ca(a,t):r[i]=da(a,t);return r}function fa(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function pa(e,t){let n=L(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
24
24
  `),i=n.split(`
25
25
  `),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=da(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}R(e,r?`${a.join(`
26
26
  `)}\n`:a.join(`
@@ -50,20 +50,20 @@ ws.addEventListener('error', () => process.exit(1));
50
50
  setTimeout(() => process.exit(2), ${t+1e4});
51
51
  `),r}async function xo(e,t,n,r,i){let a=bo(e,t,N(r,`cpu.cpuprofile`)),o=!1,s=A(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=go(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{Ut(N(a,`..`),{recursive:!0,force:!0})}catch{}return o}function So(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(`
52
52
  `)}async function Co(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??pt,s=t.inspect??mt,c=t.resolveCommand??ht,l=t.resolveUsage??ut,u=t.collectLsofFn??_o,d=t.getEndpoints??yo,f=t.profiler??xo,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(K.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let b=new Date().toISOString().replace(/[:.]/g,`-`),x=e.output?e.output:v?N(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):N(process.cwd(),`ok-diagnose-${n}-${b}`);try{I(x,{recursive:!0})}catch(e){a(K.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(K.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{R(N(x,e),t),a(` wrote ${e}`)},ee=c(n),te=l(n);S(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:ee,usage:te,lockInfo:y},null,2)),a(` sampling lsof`);let C=u(n);if(C&&S(`lsof.txt`,C),!i){let e=C?vo(C).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(K.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){S(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,x,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(K.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
53
- `)}\n`);try{S(`stacks.txt`,So(L(N(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(K.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(K.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(K.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: ${K.default.bold(x)}`)}async function wo(e){let t=dn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function To(e){let t=zt(N(Qt(),`ok-bundle-process-`));return await Co({pid:e,output:t}),t}function Eo(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 Do(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Oo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(K.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Eo(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 ko(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??wo,i=t.runProcessDiagnose??To,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=jt(o);if(!F(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=N(e.contentDir,`.ok`,`local`,`diagnostics`);I(n,{recursive:!0}),o=N(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(K.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await qa({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(K.default.yellow(` server not running — live state unavailable`)),Oo(n,c,o),e.yes!==!0&&!Do(await r(`Write bundle? [y/N]: `))?(n(K.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Ja({collected:c,outputPath:o}),n(K.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Ut(s,{recursive:!0,force:!0})}catch{}}}function Ao(){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(K.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(K.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Co({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ho()),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(K.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-F1SNlrhF.mjs`),{resolveContentDir:r}=await import(`./dist-jwEG_6T7.mjs`),i=process.cwd(),{config:a}=n(i);await ko({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(K.default.red(t)),process.exit(1)}}),e}const jo=[` 1. ${k(`Customize`)} (sidebar) → ${k(`Skills`)}`,` 2. Click the ${k(`+`)} button`,` 3. Click ${k(`Create skill`)}`,` 4. Click ${k(`Upload skill`)}`,` 5. Pick ${k(`openknowledge.skill`)} from Downloads`],Mo=T(` Open the Claude Desktop App, then: ${k(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function No(e){let t=[D(`Built ${e.outputPath}`),E(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(O(` Handoff failed: ${e.handoffError.message}`)),t.push(Mo),t.join(`
53
+ `)}\n`);try{S(`stacks.txt`,So(L(N(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(K.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(K.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(K.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: ${K.default.bold(x)}`)}async function wo(e){let t=dn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function To(e){let t=zt(N(Qt(),`ok-bundle-process-`));return await Co({pid:e,output:t}),t}function Eo(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 Do(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Oo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(K.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Eo(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 ko(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??wo,i=t.runProcessDiagnose??To,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=jt(o);if(!F(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=N(e.contentDir,`.ok`,`local`,`diagnostics`);I(n,{recursive:!0}),o=N(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(K.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await qa({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(K.default.yellow(` server not running — live state unavailable`)),Oo(n,c,o),e.yes!==!0&&!Do(await r(`Write bundle? [y/N]: `))?(n(K.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Ja({collected:c,outputPath:o}),n(K.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Ut(s,{recursive:!0,force:!0})}catch{}}}function Ao(){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(K.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(K.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Co({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(ho()),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(K.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-D6ZQW0bM.mjs`),{resolveContentDir:r}=await import(`./dist-Bj_IaFF5.mjs`),i=process.cwd(),{config:a}=n(i);await ko({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(K.default.red(t)),process.exit(1)}}),e}const jo=[` 1. ${k(`Customize`)} (sidebar) → ${k(`Skills`)}`,` 2. Click the ${k(`+`)} button`,` 3. Click ${k(`Create skill`)}`,` 4. Click ${k(`Upload skill`)}`,` 5. Pick ${k(`openknowledge.skill`)} from Downloads`],Mo=T(` Open the Claude Desktop App, then: ${k(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function No(e){let t=[D(`Built ${e.outputPath}`),E(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(O(` Handoff failed: ${e.handoffError.message}`)),t.push(Mo),t.join(`
54
54
  `)}function Po(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[T(`Open Knowledge skill ${k(`v${t}`)} already delivered to Claude Desktop.`),E(` Recorded at ${n} in ~/.ok/skill-state.yml`),E(` Use ${k(`--force`)} to rebuild and re-open the install dialog.`)].join(`
55
55
  `)}function Fo(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[D(`Built ${e.outputPath}`),E(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),T(` Claude Desktop App opened. Now upload the file manually:`),...jo,E(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
56
56
  `)}function Io(e){return`${Dt(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Lo(e={}){let t=await et(e);return t.status===`failed`?{...t,message:Io(t),exitCode:1}:t.status===`skip-current`?{...t,message:Po(t),exitCode:0}:t.status===`installed`?{...t,message:Fo(t),exitCode:0}:{...t,message:No(t),exitCode:0}}function Ro(){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 Lo({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}const zo=N(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),Bo=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Vo(e,t,n){return e===`darwin`?[N(t,`Applications`,`Open Knowledge.app`,zo),N(`/Applications`,`Open Knowledge.app`,zo)].find(e=>n.existsSync(e))??null:null}function Ho(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`&&Bo.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function Uo(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 Wo(e){Uo({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??A,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 Go(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 Ko=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
57
57
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),qo(t)}clear(){this._buffer=void 0}};function qo(e){return Oe.parse(JSON.parse(e))}function Jo(e){return JSON.stringify(e)+`
58
- `}var Yo=class{constructor(e=Kt.stdin,t=Kt.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Ko,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Jo(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function Xo(e){if(e.platform!==`darwin`)return{kind:`unchanged`};let t;try{t=e.realpath(e.bundleAnchorPath)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}let n;try{n=e.statInode(t)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}return n===e.currentInode?{kind:`unchanged`}:{kind:`replaced`,currentInode:e.currentInode,onDiskInode:n}}function Zo(e){let t=e.setInterval??setInterval,n=e.clearInterval??clearInterval,r=e.intervalMs??3e5,i=!0,a=!1,o=!1,s=t(()=>{if(!i)return;let t;try{t=e.detect()}catch(t){e.log(`bundle identity check threw unexpectedly (contract violation): ${t instanceof Error?t.message:String(t)}`);return}if(t.kind===`unreadable`){o||(o=!0,e.log(`bundle identity check unreadable${t.reason?`: ${t.reason}`:``} — will retry on next tick`));return}o&&(o=!1,e.log(`bundle identity check recovered from unreadable`)),t.kind!==`unchanged`&&(i=!1,e.onReplaced(t))},r);return typeof s.unref==`function`&&s.unref(),{stop:()=>{a||(a=!0,i=!1,n(s))}}}function Qo(e,t){let n;try{n=t.realpathSync(e)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (realpath failed): ${e instanceof Error?e.message:String(e)}`);return}let r;try{r=t.statInoSync(n)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (stat failed): ${e instanceof Error?e.message:String(e)}`);return}return{resolvedPath:n,inode:r}}function $o(e){let t=e.scheduler??{setInterval:(e,t)=>globalThis.setInterval(e,t),clearInterval:e=>globalThis.clearInterval(e)},n=e.getPpid();if(n<=1)return{stop:()=>{}};let r=!1,i=t.setInterval(()=>{if(r)return;let a=e.getPpid();a!==n&&(r=!0,t.clearInterval(i),e.onHostGone(`host process exited (ppid ${n} -> ${a})`))},e.intervalMs??1e3);return i.unref?.(),{stop:()=>t.clearInterval(i)}}function es(e){let t=t=>{try{e.log(t)}catch{}},n=e.transport.onclose;e.transport.onclose=()=>{t(`[mcp] stdio transport closed (internal shutdown)`),n?.()},e.stdin.once(`end`,()=>t(`[mcp] stdin EOF (host closed pipe)`)),e.stdin.once(`close`,()=>t(`[mcp] stdin closed`)),e.process.on(`exit`,e=>{t(`[mcp] exit code=${e}`)}),e.process.on(`uncaughtExceptionMonitor`,(e,n)=>{t(`[mcp] uncaughtException origin=${n}: ${e instanceof Error?e.stack??e.message:String(e)}`)})}function ts(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ns(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...ts(t.headers),...ts(r.headers)}:t.headers}):e}let rs;rs=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function is(e){return(await rs).getRandomValues(new Uint8Array(e))}async function as(e){let t=``;for(;t.length<e;){let n=await is(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function os(e){return await as(e)}async function ss(e){let t=await(await rs).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function cs(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await os(e);return{code_verifier:t,code_challenge:await ss(t)}}const J=c().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:An.custom,message:`URL must be parseable`,fatal:!0}),g}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ls=u({resource:f().url(),authorization_servers:o(J).optional(),jwks_uri:f().url().optional(),scopes_supported:o(f()).optional(),bearer_methods_supported:o(f()).optional(),resource_signing_alg_values_supported:o(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:l().optional(),authorization_details_types_supported:o(f()).optional(),dpop_signing_alg_values_supported:o(f()).optional(),dpop_bound_access_tokens_required:l().optional()}),us=u({issuer:f(),authorization_endpoint:J,token_endpoint:J,registration_endpoint:J.optional(),scopes_supported:o(f()).optional(),response_types_supported:o(f()),response_modes_supported:o(f()).optional(),grant_types_supported:o(f()).optional(),token_endpoint_auth_methods_supported:o(f()).optional(),token_endpoint_auth_signing_alg_values_supported:o(f()).optional(),service_documentation:J.optional(),revocation_endpoint:J.optional(),revocation_endpoint_auth_methods_supported:o(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:o(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:o(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:o(f()).optional(),code_challenge_methods_supported:o(f()).optional(),client_id_metadata_document_supported:l().optional()}),ds=r({...u({issuer:f(),authorization_endpoint:J,token_endpoint:J,userinfo_endpoint:J.optional(),jwks_uri:J,registration_endpoint:J.optional(),scopes_supported:o(f()).optional(),response_types_supported:o(f()),response_modes_supported:o(f()).optional(),grant_types_supported:o(f()).optional(),acr_values_supported:o(f()).optional(),subject_types_supported:o(f()),id_token_signing_alg_values_supported:o(f()),id_token_encryption_alg_values_supported:o(f()).optional(),id_token_encryption_enc_values_supported:o(f()).optional(),userinfo_signing_alg_values_supported:o(f()).optional(),userinfo_encryption_alg_values_supported:o(f()).optional(),userinfo_encryption_enc_values_supported:o(f()).optional(),request_object_signing_alg_values_supported:o(f()).optional(),request_object_encryption_alg_values_supported:o(f()).optional(),request_object_encryption_enc_values_supported:o(f()).optional(),token_endpoint_auth_methods_supported:o(f()).optional(),token_endpoint_auth_signing_alg_values_supported:o(f()).optional(),display_values_supported:o(f()).optional(),claim_types_supported:o(f()).optional(),claims_supported:o(f()).optional(),service_documentation:f().optional(),claims_locales_supported:o(f()).optional(),ui_locales_supported:o(f()).optional(),claims_parameter_supported:l().optional(),request_parameter_supported:l().optional(),request_uri_parameter_supported:l().optional(),require_request_uri_registration:l().optional(),op_policy_uri:J.optional(),op_tos_uri:J.optional(),client_id_metadata_document_supported:l().optional()}).shape,...us.pick({code_challenge_methods_supported:!0}).shape}),fs=r({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Mn().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),ps=r({error:f(),error_description:f().optional(),error_uri:f().optional()}),ms=J.optional().or(i(``).transform(()=>void 0)),hs=r({redirect_uris:o(J),token_endpoint_auth_method:f().optional(),grant_types:o(f()).optional(),response_types:o(f()).optional(),client_name:f().optional(),client_uri:J.optional(),logo_uri:ms,scope:f().optional(),contacts:o(f()).optional(),tos_uri:ms,policy_uri:f().optional(),jwks_uri:J.optional(),jwks:a().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),gs=r({client_id:f(),client_secret:f().optional(),client_id_issued_at:d().optional(),client_secret_expires_at:d().optional()}).strip(),_s=hs.merge(gs);r({error:f(),error_description:f().optional()}).strip(),r({token:f(),token_type_hint:f().optional()}).strip();function vs(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function ys({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Y=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},bs=class extends Y{};bs.errorCode=`invalid_request`;var xs=class extends Y{};xs.errorCode=`invalid_client`;var Ss=class extends Y{};Ss.errorCode=`invalid_grant`;var Cs=class extends Y{};Cs.errorCode=`unauthorized_client`;var ws=class extends Y{};ws.errorCode=`unsupported_grant_type`;var Ts=class extends Y{};Ts.errorCode=`invalid_scope`;var Es=class extends Y{};Es.errorCode=`access_denied`;var X=class extends Y{};X.errorCode=`server_error`;var Ds=class extends Y{};Ds.errorCode=`temporarily_unavailable`;var Os=class extends Y{};Os.errorCode=`unsupported_response_type`;var ks=class extends Y{};ks.errorCode=`unsupported_token_type`;var As=class extends Y{};As.errorCode=`invalid_token`;var js=class extends Y{};js.errorCode=`method_not_allowed`;var Ms=class extends Y{};Ms.errorCode=`too_many_requests`;var Ns=class extends Y{};Ns.errorCode=`invalid_client_metadata`;var Ps=class extends Y{};Ps.errorCode=`insufficient_scope`;var Fs=class extends Y{};Fs.errorCode=`invalid_target`;const Is={[bs.errorCode]:bs,[xs.errorCode]:xs,[Ss.errorCode]:Ss,[Cs.errorCode]:Cs,[ws.errorCode]:ws,[Ts.errorCode]:Ts,[Es.errorCode]:Es,[X.errorCode]:X,[Ds.errorCode]:Ds,[Os.errorCode]:Os,[ks.errorCode]:ks,[As.errorCode]:As,[js.errorCode]:js,[Ms.errorCode]:Ms,[Ns.errorCode]:Ns,[Ps.errorCode]:Ps,[Fs.errorCode]:Fs};var Ls=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Rs(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const zs=`code`,Bs=`S256`;function Vs(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Rs(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Hs(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Us(i,a,n);return;case`client_secret_post`:Ws(i,a,r);return;case`none`:Gs(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Us(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ws(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Gs(e,t){t.set(`client_id`,e)}async function Ks(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ps.parse(JSON.parse(n));return new(Is[e]||X)(t||``,r)}catch(e){return new X(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function qs(e,t){try{return await Js(e,t)}catch(n){if(n instanceof xs||n instanceof Cs)return await e.invalidateCredentials?.(`all`),await Js(e,t);if(n instanceof Ss)return await e.invalidateCredentials?.(`tokens`),await Js(e,t);throw n}}async function Js(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await oc(c,{fetchFn:a}),!s)try{s=await $s(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await sc(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await Xs(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!Ys(r))throw new Ns(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await pc(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await fc(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await dc(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof Y)||e instanceof X))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await cc(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function Ys(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Xs(e,t,n){let r=vs(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ys({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Zs(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Qs(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Qs(e,`scope`)||void 0,s=Qs(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Qs(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function $s(e,t,n=fetch){let r=await ic(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ls.parse(await r.json())}async function ec(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?ec(e,void 0,n):void 0;throw r}}function tc(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function nc(e,t,n=fetch){return await ec(e,{"MCP-Protocol-Version":t},n)}function rc(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ic(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=tc(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await nc(o,a,n);return!r?.metadataUrl&&rc(s,i.pathname)&&(s=await nc(new URL(`/.well-known/${t}`,i),a,n)),s}function ac(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function oc(e,{fetchFn:t=fetch,protocolVersion:n=at}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=ac(e);for(let{url:e,type:n}of i){let i=await ec(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?us.parse(await i.json()):ds.parse(await i.json())}}}async function sc(e,t){let n,r;try{n=await $s(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await oc(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function cc(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(zs))throw Error(`Incompatible auth server: does not support response type ${zs}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Bs))throw Error(`Incompatible auth server: does not support code challenge method ${Bs}`)}else s=new URL(`/authorize`,e);let c=await cs(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,zs),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Bs),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function lc(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function uc(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Hs(Vs(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Ks(l);return fs.parse(await l.json())}async function dc(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await uc(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function fc(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=lc(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return uc(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function pc(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await Ks(o);return _s.parse(await o.json())}var mc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function hc(e){}function gc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=hc,onError:n=hc,onRetry:r=hc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=_c(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
59
- `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new mc(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new mc(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
60
- `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function _c(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
58
+ `}var Yo=class{constructor(e=Kt.stdin,t=Kt.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Ko,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Jo(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function Xo(e){if(e.platform!==`darwin`)return{kind:`unchanged`};let t;try{t=e.realpath(e.bundleAnchorPath)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}let n;try{n=e.statInode(t)}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}return n===e.currentInode?{kind:`unchanged`}:{kind:`replaced`,currentInode:e.currentInode,onDiskInode:n}}function Zo(e){let t=e.setInterval??setInterval,n=e.clearInterval??clearInterval,r=e.intervalMs??3e5,i=!0,a=!1,o=!1,s=t(()=>{if(!i)return;let t;try{t=e.detect()}catch(t){e.log(`bundle identity check threw unexpectedly (contract violation): ${t instanceof Error?t.message:String(t)}`);return}if(t.kind===`unreadable`){o||(o=!0,e.log(`bundle identity check unreadable${t.reason?`: ${t.reason}`:``} — will retry on next tick`));return}o&&(o=!1,e.log(`bundle identity check recovered from unreadable`)),t.kind!==`unchanged`&&(i=!1,e.onReplaced(t))},r);return typeof s.unref==`function`&&s.unref(),{stop:()=>{a||(a=!0,i=!1,n(s))}}}function Qo(e,t){let n;try{n=t.realpathSync(e)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (realpath failed): ${e instanceof Error?e.message:String(e)}`);return}let r;try{r=t.statInoSync(n)}catch(e){t.log(`[mcp] bundle identity boot capture unreadable (stat failed): ${e instanceof Error?e.message:String(e)}`);return}return{resolvedPath:n,inode:r}}function $o(e){let t=e.scheduler??{setInterval:(e,t)=>globalThis.setInterval(e,t),clearInterval:e=>globalThis.clearInterval(e)},n=e.getPpid();if(n<=1)return{stop:()=>{}};let r=!1,i=t.setInterval(()=>{if(r)return;let a=e.getPpid();a!==n&&(r=!0,t.clearInterval(i),e.onHostGone(`host process exited (ppid ${n} -> ${a})`))},e.intervalMs??1e3);return i.unref?.(),{stop:()=>t.clearInterval(i)}}function es(e){let t=t=>{try{e.log(t)}catch{}},n=e.transport.onclose;e.transport.onclose=()=>{t(`[mcp] stdio transport closed (internal shutdown)`),n?.()},e.stdin.once(`end`,()=>t(`[mcp] stdin EOF (host closed pipe)`)),e.stdin.once(`close`,()=>t(`[mcp] stdin closed`)),e.process.on(`exit`,e=>{t(`[mcp] exit code=${e}`)}),e.process.on(`uncaughtExceptionMonitor`,(e,n)=>{t(`[mcp] uncaughtException origin=${n}: ${e instanceof Error?e.stack??e.message:String(e)}`)})}function ts(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ns(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...ts(t.headers),...ts(r.headers)}:t.headers}):e}let rs;rs=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function is(e){return(await rs).getRandomValues(new Uint8Array(e))}async function as(e){let t=``;for(;t.length<e;){let n=await is(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function os(e){return await as(e)}async function ss(e){let t=await(await rs).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function cs(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await os(e);return{code_verifier:t,code_challenge:await ss(t)}}const J=c().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:An.custom,message:`URL must be parseable`,fatal:!0}),_}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ls=u({resource:f().url(),authorization_servers:o(J).optional(),jwks_uri:f().url().optional(),scopes_supported:o(f()).optional(),bearer_methods_supported:o(f()).optional(),resource_signing_alg_values_supported:o(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:l().optional(),authorization_details_types_supported:o(f()).optional(),dpop_signing_alg_values_supported:o(f()).optional(),dpop_bound_access_tokens_required:l().optional()}),us=u({issuer:f(),authorization_endpoint:J,token_endpoint:J,registration_endpoint:J.optional(),scopes_supported:o(f()).optional(),response_types_supported:o(f()),response_modes_supported:o(f()).optional(),grant_types_supported:o(f()).optional(),token_endpoint_auth_methods_supported:o(f()).optional(),token_endpoint_auth_signing_alg_values_supported:o(f()).optional(),service_documentation:J.optional(),revocation_endpoint:J.optional(),revocation_endpoint_auth_methods_supported:o(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:o(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:o(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:o(f()).optional(),code_challenge_methods_supported:o(f()).optional(),client_id_metadata_document_supported:l().optional()}),ds=r({...u({issuer:f(),authorization_endpoint:J,token_endpoint:J,userinfo_endpoint:J.optional(),jwks_uri:J,registration_endpoint:J.optional(),scopes_supported:o(f()).optional(),response_types_supported:o(f()),response_modes_supported:o(f()).optional(),grant_types_supported:o(f()).optional(),acr_values_supported:o(f()).optional(),subject_types_supported:o(f()),id_token_signing_alg_values_supported:o(f()),id_token_encryption_alg_values_supported:o(f()).optional(),id_token_encryption_enc_values_supported:o(f()).optional(),userinfo_signing_alg_values_supported:o(f()).optional(),userinfo_encryption_alg_values_supported:o(f()).optional(),userinfo_encryption_enc_values_supported:o(f()).optional(),request_object_signing_alg_values_supported:o(f()).optional(),request_object_encryption_alg_values_supported:o(f()).optional(),request_object_encryption_enc_values_supported:o(f()).optional(),token_endpoint_auth_methods_supported:o(f()).optional(),token_endpoint_auth_signing_alg_values_supported:o(f()).optional(),display_values_supported:o(f()).optional(),claim_types_supported:o(f()).optional(),claims_supported:o(f()).optional(),service_documentation:f().optional(),claims_locales_supported:o(f()).optional(),ui_locales_supported:o(f()).optional(),claims_parameter_supported:l().optional(),request_parameter_supported:l().optional(),request_uri_parameter_supported:l().optional(),require_request_uri_registration:l().optional(),op_policy_uri:J.optional(),op_tos_uri:J.optional(),client_id_metadata_document_supported:l().optional()}).shape,...us.pick({code_challenge_methods_supported:!0}).shape}),fs=r({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Mn().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),ps=r({error:f(),error_description:f().optional(),error_uri:f().optional()}),ms=J.optional().or(i(``).transform(()=>void 0)),hs=r({redirect_uris:o(J),token_endpoint_auth_method:f().optional(),grant_types:o(f()).optional(),response_types:o(f()).optional(),client_name:f().optional(),client_uri:J.optional(),logo_uri:ms,scope:f().optional(),contacts:o(f()).optional(),tos_uri:ms,policy_uri:f().optional(),jwks_uri:J.optional(),jwks:a().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),gs=r({client_id:f(),client_secret:f().optional(),client_id_issued_at:d().optional(),client_secret_expires_at:d().optional()}).strip(),_s=hs.merge(gs);r({error:f(),error_description:f().optional()}).strip(),r({token:f(),token_type_hint:f().optional()}).strip();function vs(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function ys({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Y=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},bs=class extends Y{};bs.errorCode=`invalid_request`;var xs=class extends Y{};xs.errorCode=`invalid_client`;var Ss=class extends Y{};Ss.errorCode=`invalid_grant`;var Cs=class extends Y{};Cs.errorCode=`unauthorized_client`;var ws=class extends Y{};ws.errorCode=`unsupported_grant_type`;var Ts=class extends Y{};Ts.errorCode=`invalid_scope`;var Es=class extends Y{};Es.errorCode=`access_denied`;var X=class extends Y{};X.errorCode=`server_error`;var Ds=class extends Y{};Ds.errorCode=`temporarily_unavailable`;var Os=class extends Y{};Os.errorCode=`unsupported_response_type`;var ks=class extends Y{};ks.errorCode=`unsupported_token_type`;var As=class extends Y{};As.errorCode=`invalid_token`;var js=class extends Y{};js.errorCode=`method_not_allowed`;var Ms=class extends Y{};Ms.errorCode=`too_many_requests`;var Ns=class extends Y{};Ns.errorCode=`invalid_client_metadata`;var Ps=class extends Y{};Ps.errorCode=`insufficient_scope`;var Fs=class extends Y{};Fs.errorCode=`invalid_target`;const Is={[bs.errorCode]:bs,[xs.errorCode]:xs,[Ss.errorCode]:Ss,[Cs.errorCode]:Cs,[ws.errorCode]:ws,[Ts.errorCode]:Ts,[Es.errorCode]:Es,[X.errorCode]:X,[Ds.errorCode]:Ds,[Os.errorCode]:Os,[ks.errorCode]:ks,[As.errorCode]:As,[js.errorCode]:js,[Ms.errorCode]:Ms,[Ns.errorCode]:Ns,[Ps.errorCode]:Ps,[Fs.errorCode]:Fs};var Z=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Ls(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Rs=`code`,zs=`S256`;function Bs(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Ls(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Vs(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Hs(i,a,n);return;case`client_secret_post`:Us(i,a,r);return;case`none`:Ws(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Hs(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Us(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ws(e,t){t.set(`client_id`,e)}async function Gs(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ps.parse(JSON.parse(n));return new(Is[e]||X)(t||``,r)}catch(e){return new X(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function Ks(e,t){try{return await qs(e,t)}catch(n){if(n instanceof xs||n instanceof Cs)return await e.invalidateCredentials?.(`all`),await qs(e,t);if(n instanceof Ss)return await e.invalidateCredentials?.(`tokens`),await qs(e,t);throw n}}async function qs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await ac(c,{fetchFn:a}),!s)try{s=await Qs(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await oc(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await Ys(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!Js(r))throw new Ns(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await fc(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await dc(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await uc(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof Y)||e instanceof X))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await sc(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function Js(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Ys(e,t,n){let r=vs(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ys({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Xs(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Zs(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Zs(e,`scope`)||void 0,s=Zs(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Zs(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Qs(e,t,n=fetch){let r=await rc(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ls.parse(await r.json())}async function $s(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?$s(e,void 0,n):void 0;throw r}}function ec(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tc(e,t,n=fetch){return await $s(e,{"MCP-Protocol-Version":t},n)}function nc(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function rc(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ec(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await tc(o,a,n);return!r?.metadataUrl&&nc(s,i.pathname)&&(s=await tc(new URL(`/.well-known/${t}`,i),a,n)),s}function ic(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ac(e,{fetchFn:t=fetch,protocolVersion:n=at}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=ic(e);for(let{url:e,type:n}of i){let i=await $s(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?us.parse(await i.json()):ds.parse(await i.json())}}}async function oc(e,t){let n,r;try{n=await Qs(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await ac(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function sc(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Rs))throw Error(`Incompatible auth server: does not support response type ${Rs}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(zs))throw Error(`Incompatible auth server: does not support code challenge method ${zs}`)}else s=new URL(`/authorize`,e);let c=await cs(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Rs),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,zs),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function cc(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function lc(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Vs(Bs(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Gs(l);return fs.parse(await l.json())}async function uc(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await lc(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function dc(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=cc(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return lc(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function fc(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await Gs(o);return _s.parse(await o.json())}var pc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function mc(e){}function hc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=mc,onError:n=mc,onRetry:r=mc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=gc(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
59
+ `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new pc(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new pc(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
60
+ `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function gc(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
61
61
  `,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]===`
62
- `&&r++}}return[t,n]}var vc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=gc({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 yc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var bc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},xc=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=ns(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??yc}async _authThenStart(){if(!this._authProvider)throw new Ls(`No auth provider`);let e;try{e=await qs(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 Ls;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=ts(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 bc(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 vc({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=Oe.parse(JSON.parse(e.data));ke(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 Ls(`No auth provider`);if(await qs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Ls(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ae(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new bc(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Zs(o);if(this._resourceMetadataUrl=t,this._scope=n,await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Ls;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Zs(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new bc(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ls;return this.send(e)}}throw new bc(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ue(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=>Oe.parse(e)):[Oe.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new bc(-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 bc(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 Sc(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 Cc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function wc(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Tc(e,t){return`http://${wc(e)}:${t}/mcp`}function Ec(e,t){return`ws://${wc(e)}:${t}`}function Dc(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Oc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function kc(e){return F(e)?L(e,`utf-8`).trim():``}function Ac(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function jc(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Mc(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 Nc(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Pc(e){let t=e.readLock??(()=>m(e.lockDir)),n=e.isAlive??v,r=e.sleep??(e=>un(e)),i=e.spawn??A,a=e.readErrorLog??kc,o=e.openErrorLog??(e=>Bt(e,`w`)),s=e.closeFd??Ft,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return Tc(`localhost`,t)}let u=Oc(t(),n);if(u!==void 0)return Tc(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);F(e.lockDir)||I(e.lockDir,{recursive:!0});let d=N(e.lockDir,ee),f=o(d),p,h,g=bt();try{try{p=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),p.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}await r(l);let e=Oc(t(),n);if(e!==void 0)return Tc(`localhost`,e)}if(h){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}throw Error(Ac(c,a(d)))}function Fc(e,t){if(e.portOverride!==void 0)return Dc(t);let n=e.readLock??(()=>m(e.lockDir)),r=e.isAlive??v,i=Oc(n(),r);if(i!==void 0)return Ec(`localhost`,i)}async function Ic(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Yo(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new xc(new URL(e),{fetch:Sc(r),requestInit:{headers:{...b({kind:`mcp`,runtimeVersion:_}),...t.connectionId===void 0?{}:{[Ee]: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=jc(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(Nc(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=Mc(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 Lc(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Ic,r=await Pc(e),i=e.createConnectionId?.()??ln(),a=!1,o=(e.startKeepalive??Go)({connectionId:i,resolveWsUrl:async()=>Fc(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 Rc=nn(import.meta.url);function zc(e){let t=P(e);for(;;){if(Me(t))return t;let n=jt(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 \`${S}\`).`);t=n}}function Bc(e){try{let t=new URL(e);return t.protocol===`file:`?nn(t):void 0}catch{return}}async function Vc(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=Bc(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Hc(e,t){if(e!==void 0)return zc(e);let n=await t();if(n!==void 0)return zc(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 Uc(e){let t=process.stderr,n=e.spawnTimeoutMs??Cc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=yt({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new Be({name:$e,version:_},{instructions:Je({dir:`.`})});We(a);let o=ln(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=Xe(e),r=s.current,i=Go({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Fc({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Vc({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>Hc(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=zc(e)}else t=zc(e);let a=await i(t),o=await Pc({lockDir:Xe(t),contentDir:st(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Re(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},tt(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new Yo,m=!1,h,g,v=async()=>{if(m)return;m=!0,h?.stop(),g?.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)
62
+ `&&r++}}return[t,n]}var _c=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=hc({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 vc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var yc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},bc=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=ns(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??vc}async _authThenStart(){if(!this._authProvider)throw new Z(`No auth provider`);let e;try{e=await Ks(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=ts(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 yc(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 _c({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=Oe.parse(JSON.parse(e.data));ke(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 Ks(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:Ae(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new yc(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Xs(o);if(this._resourceMetadataUrl=t,this._scope=n,await Ks(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}=Xs(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new yc(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Z;return this.send(e)}}throw new yc(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ue(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=>Oe.parse(e)):[Oe.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new yc(-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 yc(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 xc(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 Sc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Cc(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function wc(e,t){return`http://${Cc(e)}:${t}/mcp`}function Tc(e,t){return`ws://${Cc(e)}:${t}`}function Ec(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Dc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Oc(e){return F(e)?L(e,`utf-8`).trim():``}function kc(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Ac(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function jc(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 Mc(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Nc(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??y,r=e.sleep??(e=>un(e)),i=e.spawn??A,a=e.readErrorLog??Oc,o=e.openErrorLog??(e=>Bt(e,`w`)),s=e.closeFd??Ft,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return wc(`localhost`,t)}let u=Dc(t(),n);if(u!==void 0)return wc(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);F(e.lockDir)||I(e.lockDir,{recursive:!0});let d=N(e.lockDir,m),f=o(d),p,g,_=bt();try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}await r(l);let e=Dc(t(),n);if(e!==void 0)return wc(`localhost`,e)}if(g){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}throw Error(kc(c,a(d)))}function Pc(e,t){if(e.portOverride!==void 0)return Ec(t);let n=e.readLock??(()=>h(e.lockDir)),r=e.isAlive??y,i=Dc(n(),r);if(i!==void 0)return Tc(`localhost`,i)}async function Fc(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Yo(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new bc(new URL(e),{fetch:xc(r),requestInit:{headers:{...x({kind:`mcp`,runtimeVersion:v}),...t.connectionId===void 0?{}:{[Ee]: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=Ac(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(Mc(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=jc(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 Ic(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Fc,r=await Nc(e),i=e.createConnectionId?.()??ln(),a=!1,o=(e.startKeepalive??Go)({connectionId:i,resolveWsUrl:async()=>Pc(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 Lc=nn(import.meta.url);function Rc(e){let t=P(e);for(;;){if(Me(t))return t;let n=jt(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 \`${ee}\`).`);t=n}}function zc(e){try{let t=new URL(e);return t.protocol===`file:`?nn(t):void 0}catch{return}}async function Bc(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=zc(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Vc(e,t){if(e!==void 0)return Rc(e);let n=await t();if(n!==void 0)return Rc(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 Hc(e){let t=process.stderr,n=e.spawnTimeoutMs??Sc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=yt({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new Be({name:$e,version:v},{instructions:Je({dir:`.`})});We(a);let o=ln(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=Xe(e),r=s.current,i=Go({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Pc({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Bc({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>Vc(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=Rc(e)}else t=Rc(e);let a=await i(t),o=await Nc({lockDir:Xe(t),contentDir:st(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Re(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},tt(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new Yo,m=!1,h,g,_=async()=>{if(m)return;m=!0,h?.stop(),g?.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)
63
63
  `);let y=!1,b=()=>{y||(y=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
64
- `),process.exit(1)},5e3).unref(),v().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,b),process.once(`SIGTERM`,b),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
65
- `),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),g=$o({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),es({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=Qo(Rc,{realpathSync:Ht,statInoSync:e=>Wt(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=Zo({detect:()=>Xo({bundleAnchorPath:Rc,currentInode:r,platform:process.platform,realpath:Ht,statInode:e=>Wt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${_} — exiting for host respawn\n`),b()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:v}}function Wc(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=Cc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Lc({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=Ho(process.env,i,process.platform);if(a.proxy){let e=Vo(process.platform,Yt(),{existsSync:F});if(e===null)Uo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Wo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Uo({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`;Uo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Uc({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 Gc(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Kc(e=()=>Tt(wt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>Ge({lockDir:He(e)}).baseUrl,openTarget:e=>{A(`open`,[e],{detached:!0,stdio:`ignore`,env:Gc(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function qc(e,t,n){let r=P(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Le(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Jc(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=qc(e,t,Kc())})}function Yc(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-BcqzxVzi.mjs`),r=e(),i=process.cwd(),a=st(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 Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Xc(e,t,n=process.cwd()){let r=e.op??`sync`,i=m(He(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}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=Te({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await a.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await a.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
66
- `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Zc(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 Xc({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 Qc(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xc({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 $c(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xc({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 el(e){return typeof e==`string`&&Ne.includes(e)}async function tl(e={}){let t=P(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!nt[n])return{status:`failed`,message:`${Dt(`Error:`)} Unknown pack "${n}". Available: ${Ne.join(`, `)}`,exitCode:1};let r;try{r=await Ze({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ke?{status:`prerequisite-missing`,message:`${Dt(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Dt(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=nt[n].name;return{status:`no-op`,message:`${D(`Your ${e} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${k(`Plan (dry-run — no changes made):`)}\n\n${rl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await il(`${k(`Plan:`)}\n\n${rl(r,t)}\n\n${k(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:r,exitCode:0};let i=await rt(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${Dt(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${O(`Applied`)} ${i.applied} entries, ${O(String(i.errors.length))} error(s):`,...e].join(`
64
+ `),process.exit(1)},5e3).unref(),_().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,b),process.once(`SIGTERM`,b),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
65
+ `),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),g=$o({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),es({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=Qo(Lc,{realpathSync:Ht,statInoSync:e=>Wt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${v}\n`);let{resolvedPath:n,inode:r}=e;h=Zo({detect:()=>Xo({bundleAnchorPath:Lc,currentInode:r,platform:process.platform,realpath:Ht,statInode:e=>Wt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${v} — exiting for host respawn\n`),b()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:_}}function Uc(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=Sc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Ic({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=Ho(process.env,i,process.platform);if(a.proxy){let e=Vo(process.platform,Yt(),{existsSync:F});if(e===null)Uo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Wo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Uo({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`;Uo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Hc({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 Wc(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Gc(e=()=>Tt(wt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>Ge({lockDir:He(e)}).baseUrl,openTarget:e=>{A(`open`,[e],{detached:!0,stdio:`ignore`,env:Wc(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Kc(e,t,n){let r=P(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Le(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function qc(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Kc(e,t,Gc())})}function Jc(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-DRATXrPN.mjs`),r=e(),i=process.cwd(),a=st(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 Yc(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Xc(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(He(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`,...x({kind:`cli`,runtimeVersion:v})},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}`)}Yc(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=Te({baseDir:n});if(r===`sync`||r===`pull`){Yc(e.json,{type:`step`,step:`pull`});let t=await a.pull();Yc(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Yc(e.json,{type:`step`,step:`push`}),await a.push(),Yc(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
66
+ `)),Yc(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Zc(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 Xc({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 Qc(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xc({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 $c(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xc({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 el(e){return typeof e==`string`&&Ne.includes(e)}async function tl(e={}){let t=P(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!nt[n])return{status:`failed`,message:`${Dt(`Error:`)} Unknown pack "${n}". Available: ${Ne.join(`, `)}`,exitCode:1};let r;try{r=await Ze({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ke?{status:`prerequisite-missing`,message:`${Dt(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Dt(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=nt[n].name;return{status:`no-op`,message:`${D(`Your ${e} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${k(`Plan (dry-run — no changes made):`)}\n\n${rl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await il(`${k(`Plan:`)}\n\n${rl(r,t)}\n\n${k(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:r,exitCode:0};let i=await rt(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${Dt(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${O(`Applied`)} ${i.applied} entries, ${O(String(i.errors.length))} error(s):`,...e].join(`
67
67
  `),plan:r,exitCode:1}}let a=nt[n].name,o=i.packSkillsInstalled.length>0?`\n${E(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${D(`✓ Seeded ${a}`)} ${E(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function nl(){let e=[k(`Available packs:`)];for(let t of Ne){let n=nt[t];e.push(` ${D(t)} ${E(`—`)} ${n.name}: ${n.description}`)}return e.join(`
68
68
  `)}function rl(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(k(`Folders to create:`));for(let e of r)n.push(` ${D(`+`)} ${T(Mt(t,P(t,e.path))||e.path)}${E(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(k(`Files to create:`));for(let e of i)n.push(` ${D(`+`)} ${T(Mt(t,P(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(E(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${E(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(O(`Warnings:`));for(let t of e.warnings)n.push(` ${O(`!`)} ${t}`)}return n.join(`
69
69
  `)}async function il(e,t){let n=dn({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function al(){return new t(`seed`).description(`Scaffold a starter pack into the project. Defaults to "${Qe}" — the Karpathy three-layer knowledge base. Use --pack to pick a different pack (run with --list-packs to see all). Use --root to place pack folders inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-p, --pack <id>`,`Starter pack to scaffold. One of: ${Ne.join(`, `)}. Defaults to "${Qe}".`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`--list-packs`,`List available starter packs and exit.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{if(t.listPacks){process.stdout.write(`${nl()}\n`);return}if(t.pack!==void 0&&!el(t.pack)){process.stderr.write(`${Dt(`Error:`)} Unknown pack "${t.pack}". Available: ${Ne.join(`, `)}\n`),process.exitCode=1;return}let n=await tl({cwd:e??process.cwd(),pack:t.pack,root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}async function ol(e,t,n){try{return await e.repos.get({owner:t,repo:n}),{kind:`ok`,available:!1}}catch(e){let t=e.status;return t===404?{kind:`ok`,available:!0}:t===401?{kind:`auth-required`}:{kind:`network`}}}async function sl(e,t){let{host:n,owner:r,name:i,json:a}=e;B(n);let o=await hi(n,t);if(o==null){if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let s=n===`github.com`?void 0:`https://${n}/api/v3`,c=await ol(new W({auth:o,...s?{baseUrl:s}:{}}),r,i);if(c.kind===`ok`){a?process.stdout.write(`${JSON.stringify({type:`name-check`,available:c.available})}\n`):process.stdout.write(c.available?`available
@@ -71,5 +71,5 @@ setTimeout(() => process.exit(2), ${t+1e4});
71
71
  `);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function cl(e){return new t(`name-check`).description(`Check if owner/name is available on GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await sl(t,await e())})}async function ll(e){try{let t=[],n=await e.users.getAuthenticated();t.push({login:n.data.login,kind:`user`,avatarUrl:n.data.avatar_url});for await(let n of e.paginate.iterator(e.orgs.listMembershipsForAuthenticatedUser,{state:`active`,per_page:100}))for(let e of n.data)(e.permissions?.can_create_repository===!0||e.role===`admin`)&&t.push({login:e.organization.login,kind:`org`,avatarUrl:e.organization.avatar_url??void 0});return{kind:`ok`,owners:t}}catch(e){return e.status===401?{kind:`auth-required`}:{kind:`network`}}}async function ul(e,t){let{host:n,json:r}=e;B(n);let i=await hi(n,t);if(i==null){if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=await ll(new W({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function dl(e){return new t(`owners`).description(`List GitHub owners eligible to host a new repository`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await ul(t,await e())})}function fl(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
72
72
  `)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function pl(e){let{octokit:t,ownerLogin:n,ownerKind:r,name:i,visibility:a,description:o}=e,s=a===`private`;if(r===`user`){let{data:e}=await t.repos.createForAuthenticatedUser({name:i,private:s,...o?{description:o}:{}});return{cloneUrl:e.clone_url,defaultBranch:e.default_branch??`main`}}let{data:c}=await t.repos.createInOrg({org:n,name:i,visibility:a,...o?{description:o}:{}});return{cloneUrl:c.clone_url,defaultBranch:c.default_branch??`main`}}async function ml(e,t,n){try{let{data:r}=await e.repos.get({owner:t,repo:n});return{cloneUrl:r.clone_url,defaultBranch:r.default_branch??`main`}}catch{return null}}async function hl(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function gl(e){return Te({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function _l(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const vl={ensureOkScaffold:e=>{Ve(e)},gitFactory:gl};async function yl(e){let t={...vl,...e.deps},n=P(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await hl(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:fl(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!F(N(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await pl({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(fl(t)===`name-conflict`){let t=await ml(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:fl(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=_l(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function bl(e,t){if(!e){t.kind===`ok`?process.stdout.write(`✓ Published ${t.value.cloneUrl}\n`):(process.stderr.write(`✗ share publish failed: ${t.code}\n`),process.exit(1));return}if(t.kind===`ok`){process.stdout.write(`${JSON.stringify({type:`publish`,...t.value})}\n`);return}process.stdout.write(`${JSON.stringify({type:`error`,code:t.code})}\n`)}async function xl(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;B(n);let l=await hi(n,t);if(l==null){bl(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new W({auth:l,...u?{baseUrl:u}:{}});try{kt(`git config user.email`,{cwd:s,stdio:`ignore`})}catch{process.env.GIT_AUTHOR_NAME??=`Open Knowledge`,process.env.GIT_AUTHOR_EMAIL??=`noreply@inkeep.com`,process.env.GIT_COMMITTER_NAME??=`Open Knowledge`,process.env.GIT_COMMITTER_EMAIL??=`noreply@inkeep.com`}bl(c,await yl({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function Sl(e){return new t(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
73
73
  `),process.exit(1)),await xl(t,await e())})}function Cl(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>ne();return e.addCommand(dl(n)),e.addCommand(cl(n)),e.addCommand(Sl(n)),e}function wl(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=P(e.project??process.cwd()),n=ve(t),r=ce(t,se(t));if(r.kind===`no-exclude`){Tl(e.json,t,r.reason);return}let i=ve(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${T(`Sharing mode is already`)} ${k(`shared`)} ${T(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${k(`Sharing mode set to`)} ${D(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${k(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function Tl(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${O({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function El(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=P(e.project??process.cwd()),n=ve(t),r=[..._e(t)],i=Ce(t,se(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`Open Knowledge sharing mode: ${Dl(n)}`),a.push(``),a.push(`Excluded from git via ${k(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${T(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
74
- `)}\n`)})}function Dl(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return O(`no-git (not a git repository)`)}}function Ol(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=P(e.project??process.cwd()),n=be(t,se(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){kl(e.json,t,n.reason);return}let r=ve(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${k(`Sharing mode is already`)} ${D(`local-only`)} ${k(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${k(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${k(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function kl(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${O({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Al(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(wl()),e.addCommand(Ol()),e.addCommand(El()),e}function jl(e,t){return{server:Ml(`server`,e),ui:Ml(`ui`,t)}}function Ml(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Nl(e){return`${Pl(e.server)}\n${Pl(e.ui)}`}function Pl(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Fl(e){let t=e.inspect??(t=>mt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=jl(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Nl(r)),r}function Il(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),Fl({lockDir:He(process.cwd()),json:t.json===!0})})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $,Ll;function Rl(){return Ll}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(gt).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;t!==void 0&&process.chdir(t);let{config:n}=vt(t);$=n;let r=e.args?.[0]??e.name()??`cli`;Ll=ze({name:`cli`,project:n.project?.name??void 0}),Ll.info({command:r,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Tt(wt()).available){xt({spawn:A});return}await St($,{})});const zl=Ct(()=>$);Q.addCommand(zl);const Bl=Wc(()=>$);Q.addCommand(Bl),Q.addCommand(xe()),Q.addCommand(al()),Q.addCommand(Ro()),Q.addCommand(Ot());const Vl=Yc(()=>$);Q.addCommand(Vl);const Hl=Se(()=>$);Q.addCommand(Hl),Q.addCommand(Jc()),Q.addCommand(ft(()=>$)),Q.addCommand(Ri(()=>$)),Q.addCommand(Il(()=>$)),Q.addCommand(lt()),Q.addCommand(Ao()),Q.addCommand(Fi()),Q.addCommand(ra()),Q.addCommand(Ci()),Q.addCommand(Yi(()=>$)),Q.addCommand(Zc(()=>$)),Q.addCommand($c(()=>$)),Q.addCommand(Qc(()=>$)),Q.addCommand(Cl()),Q.addCommand(Al()),await Q.parseAsync(process.argv,{from:`node`});export{Rl as getCliLogger};
74
+ `)}\n`)})}function Dl(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return O(`no-git (not a git repository)`)}}function Ol(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=P(e.project??process.cwd()),n=be(t,se(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){kl(e.json,t,n.reason);return}let r=ve(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${k(`Sharing mode is already`)} ${D(`local-only`)} ${k(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${k(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${k(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function kl(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${O({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Al(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(wl()),e.addCommand(Ol()),e.addCommand(El()),e}function jl(e,t){return{server:Ml(`server`,e),ui:Ml(`ui`,t)}}function Ml(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Nl(e){return`${Pl(e.server)}\n${Pl(e.ui)}`}function Pl(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Fl(e){let t=e.inspect??(t=>mt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=jl(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Nl(r)),r}function Il(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),Fl({lockDir:He(process.cwd()),json:t.json===!0})})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $,Ll;function Rl(){return Ll}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(gt).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;t!==void 0&&process.chdir(t);let{config:n}=vt(t);$=n;let r=e.args?.[0]??e.name()??`cli`;Ll=ze({name:`cli`,project:n.project?.name??void 0}),Ll.info({command:r,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Tt(wt()).available){xt({spawn:A});return}await St($,{})});const zl=Ct(()=>$);Q.addCommand(zl);const Bl=Uc(()=>$);Q.addCommand(Bl),Q.addCommand(xe()),Q.addCommand(al()),Q.addCommand(Ro()),Q.addCommand(Ot());const Vl=Jc(()=>$);Q.addCommand(Vl);const Hl=Se(()=>$);Q.addCommand(Hl),Q.addCommand(qc()),Q.addCommand(ft(()=>$)),Q.addCommand(Ri(()=>$)),Q.addCommand(Il(()=>$)),Q.addCommand(lt()),Q.addCommand(Ao()),Q.addCommand(Fi()),Q.addCommand(ra()),Q.addCommand(Ci()),Q.addCommand(Yi(()=>$)),Q.addCommand(Zc(()=>$)),Q.addCommand($c(()=>$)),Q.addCommand(Qc(()=>$)),Q.addCommand(Cl()),Q.addCommand(Al()),await Q.parseAsync(process.argv,{from:`node`});export{Rl as getCliLogger};
75
75
  //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./server-lock-BpjJj3OD-2pOoEhSP.mjs";var e=`0.9.2-beta.8`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-Dz5iTLUD.mjs.map
@@ -1 +1 @@
1
- import{Vr as e,_n as t,a as n,bn as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,nn as p,o as m,on as h,p as g,q as _,r as v,s as y,t as b,u as x,yr as S,zr as C}from"./server-lock-BpjJj3OD-DBIqFE7p.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,Ni as De,Nn as Oe,Nr as ke,Nt as Ae,O as je,On as Me,Or as Ne,Ot as Pe,P as Fe,Pi as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qn as Ve,Qr as He,Qt as Ue,R as We,Rn as Ge,Rr as Ke,Rt as qe,S as Je,Sn as Ye,Sr as Xe,St as Ze,T as Qe,Tn as $e,Tr as et,Tt as tt,U as nt,Un as rt,Ur as it,Ut as at,V as ot,Vn as st,Vr as ct,Vt as lt,W as ut,Wn as dt,Wr as ft,Wt as pt,X as mt,Xn as ht,Xr as gt,Xt as _t,Y as vt,Yn as yt,Yr as bt,Yt as xt,Z as St,Zn as Ct,Zr as wt,Zt as Tt,_ as Et,_i as Dt,_n as Ot,_r as kt,_t as At,a as jt,ai as Mt,an as Nt,ar as Pt,at as Ft,b as It,bi as Lt,bn as Rt,br as zt,bt as Bt,c as Vt,ci as Ht,cn as Ut,cr as Wt,ct as Gt,d as Kt,di as qt,dn as Jt,dr as Yt,dt as Xt,ei as Zt,en as Qt,er as $t,et as en,f as tn,fi as nn,fn as rn,fr as an,ft as on,g as sn,gi as cn,gn as ln,gr as un,gt as dn,h as fn,hi as pn,hn as mn,hr as hn,ht as gn,i as _n,ii as vn,in as yn,ir as bn,it as xn,j as Sn,jn as Cn,jr as wn,jt as Tn,k as En,kn as Dn,kr as On,kt as kn,l as An,li as jn,ln as Mn,lr as Nn,lt as Pn,m as Fn,mi as In,mn as Ln,mr as Rn,mt as zn,n as Bn,ni as Vn,nn as Hn,nr as Un,nt as Wn,o as Gn,oi as Kn,on as qn,or as Jn,ot as Yn,p as Xn,pi as Zn,pn as Qn,pr as $n,pt as er,q as tr,qn as nr,qr as rr,qt as ir,r as ar,ri as or,rn as sr,rr as cr,rt as lr,s as ur,si as dr,sn as fr,sr as pr,st as mr,t as hr,ti as gr,tn as _r,tr as vr,tt as yr,u as br,ui as xr,un as Sr,ur as Cr,ut as wr,v as Tr,vi as Er,vn as Dr,vr as Or,vt as kr,w as Ar,wn as jr,wr as Mr,wt as Nr,x as Pr,xi as Fr,xn as Ir,xr as Lr,xt as Rr,y as zr,yi as Br,yn as Vr,yr as Hr,yt as Ur,z as Wr,zn as Gr,zr as Kr,zt as qr}from"./dist-CILctbXr.mjs";export{hr as AGENT_ID_MAX_LEN,Bn as AGENT_ID_RE,ar as AGENT_WRITE_ORIGIN,_n as AgentFocusBroadcaster,jt as AgentPresenceBroadcaster,Gn as AgentSessionCapacityError,ur as AgentSessionManager,Vt as BacklinkIndex,An as CC1Broadcaster,_ as CC1_CONTRACT_VERSION,br as CONFIG_FILENAME,Kt as CONFLICT_MARKER_RE,tn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Xn as ConfigSchema,Fn as DEFAULT_CHECKPOINT_RETENTION,fn as DEFAULT_PACK_ID,sn as FILE_SYSTEM_WRITER,Et as FILE_WATCHER_ORIGIN,Tr as GIT_PREFLIGHT_FAIL_SPAN_NAME,zr as GIT_UPSTREAM_WRITER,De as GitDirAccessError,It as GitNotAvailableError,Pr as GitTooOldError,Je as HOCUSPOCUS_AUTH_REJECTION_REASONS,I as HocuspocusAuthRejection,Ar as HocuspocusAuthTokenSchema,Qe as INSTALLED_AGENTS_SCHEMES,W as LIVE_DERIVED_INDEX_DEBOUNCE_MS,B as LOG_MD_TEMPLATE,je as MANAGED_RENAME_ORIGIN,En as MAX_AGENT_SESSIONS,O as MCP_CONNECTION_ID_HEADER,Sn as MCP_SERVER_NAME,Se as MIN_GIT_VERSION,Ee as MISSING_OK_CONFIG_MESSAGE,Ie as MalformedGitPointerError,Fe as McpLogger,J as MissingOkConfigError,oe as OBSERVER_SYNC_ORIGIN,ve as OK_OKIGNORE_TEMPLATE,p as ORPHAN_MODES,We as PANE_TARGET_TTL_MS,h as PROTOCOL_VERSION,Wr as PinoLogger,b as ProcessLockCollisionError,M as ProjectGitInitError,ot as ROLLBACK_ORIGIN,ne as ROOT_GITIGNORE_TEMPLATE,f as RUNTIME_VERSION,nt as SERVICE_WRITER,ut as SKILL_INSTALL_EVENTS_FILE_REL,t as SKILL_STATE_TARGETS,Q as STARTER_FOLDERS,me as STARTER_FOLDER_FRONTMATTER_FILENAME,tr as STARTER_PACKS,ue as STARTER_PACK_IDS,vt as STARTER_TEMPLATES,mt as STATE_MANIFEST_FILENAME,v as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,St as SeedPrerequisiteError,Be as SeedRootDirError,l as ServerLockCollisionError,w as StateManifestError,en as TagIndex,yr as UiLockCollisionError,Wn as __getShowAllWalkStatsForTesting,lr as __resetShowAllWalkStatsForTesting,n as acquireProcessLock,m as acquireServerLock,xn as acquireUiLock,Ft as applyAgentMarkdownWrite,Yn as applyExternalChange,mr as applySeed,Gt as armPaneTarget,Pn as assertCompatibleStateManifest,wr as assertGitAvailable,Xt as assertNeverDiskEvent,on as attachIdleShutdown,er as bootServer,zn as buildAndOpenSkill,gn as buildConfigYmlContent,dn as buildExecResult,At as buildInstructions,kr as buildSkillZip,Ur as buildStarterFolderFrontmatterYaml,Bt as buildWipTree,Rr as classifyEvents,Ze as classifyFsPath,z as clearArmedPaneTarget,Nr as clearContributors,tt as coercePackId,S as colorFromSeed,q as commitUpstreamImport,U as commitWip,Pe as commitWipFromTree,kn as compareSemver,j as containsConflictMarkers,Tn as contentHash,Te as contributorCount,Ae as createApiExtension,ze as createAssetServeMiddleware,Z as createContentFilter,le as createContentFilterAsync,xe as createExternalChangeHandler,qe as createFileLogger,qr as createLiveDerivedIndexExtension,F as createMcpHttpHandler,lt as createOsProbe,ae as createPersistenceExtension,at as createServer,pt as createServerObserverExtension,te as createStreamingErrorWriter,_e as createTestLogger,ir as detectClaudeDesktopPresence,pe as detectGit,xt as detectProjectShape,_t as emitPreflightFailureSpan,Tt as encodeDocName,Ue as encodeFolderRoute,D as ensureProjectGit,Qt as errorResponse,_r as evictStaleTrackerEntries,Hn as extractWikiLinksFromMarkdown,sr as fallbackPaths,yn as findEnclosingGitRoot,Nt as findEnclosingProjectRoot,qn as formatAuthRejectionWire,fr as formatContributors,Ut as formatContributorsFrom,Mn as gcCheckpointRefs,Sr as getCurrentMcpLogger,Jt as getLocalDir,rn as getLogFilePath,Qn as getLogger,Ln as getLogsDir,mn as getMeter,ln as getMetrics,Ot as getTracer,Dr as handleCollabSocketError,Vr as handleSpawnCursor,C as iconFromClientName,Rt as incrementCollabSocketFilteredError,Ir as incrementServerObserverFire,Ye as initContent,L as initShadowRepo,jr as initTelemetry,$e as installPrettyZodErrors,G as installTestLoggers,V as installUserSkill,Me as isAllowedApiOrigin,Dn as isAllowedWorkspaceHostHeader,k as isConfigDoc,Cn as isHocuspocusAuthRejectionReason,Ce as isKnownPackId,Oe as isLoopbackAddress,e as isOrphanMode,Le as isPairedWriteOrigin,Y as isPathWithinDir,y as isProcessAlive,se as isProjectRoot,ye as isSelfWrite,Ge as isSystemDoc,i as isValidLockPid,Gr as lastKnownHash,N as listRescueCheckpoints,st as listStarterPacks,re as loadPrincipal,u as lockFilePath,rt as loggerFactory,dt as logsCurrentPath,$ as logsPreviousPath,he as mountMcpAndApi,nr as normalizeFsPath,de as packageVersionMajorMinor,yt as parseAuthRejectionWire,ht as parseGitVersion,Ct as parseHocuspocusAuthToken,Ve as parseKeepaliveConnectionId,T as pathToDocName,$t as planSeed,vr as readAllTargets,Un as readArmedPaneTarget,cr as readBranchFromHead,x as readProcessLock,a as readProcessLockDetailed,o as readServerLock,bn as readServerPackageVersion,Pt as readSkillInstallStateSnapshot,Jn as readStateManifest,pr as readTargetRecordedAt,Wt as readTargetVersion,Nn as readUiLock,Cr as reconcile,Yt as recordContributor,an as recordSkillInstallEvent,$n as registerAllTools,Rn as registerWrite,g as releaseProcessLock,d as releaseServerLock,hn as releaseUiLock,un as removeLastKnownHash,kt as resetMetrics,Or as resolveBundledSkillDir,Hr as resolveContentDir,zt as resolveCursorBinaryDefault,Lr as resolveCursorSpawnInvocation,Xe as resolveLockDir,R as resolvePack,Mr as resolvePackageVersion,et as resolveUiInfo,K as restoreContributors,H as restoreLifecycleFromConflictsJson,Ne as rewriteMarkdownLinksForDocumentRename,On as rewriteWikiLinksForDocumentRename,A as runAuthReposSubprocess,wn as runAuthStatusSubprocess,we as runCloneSubprocess,ke as runDeviceFlowSubprocess,Re as runWithMcpLogger,X as safeContentPath,ce as safeSubdir,be as safetyCheckpoint,Ke as sanitizeClientName,Kr as saveInMemoryCheckpoint,P as saveVersion,ct as seedBasenameIndex,ie as serializeError,it as setActiveSpanAttributes,ft as shadowGit,ee as shutdownTelemetry,ge as spansCurrentPath,rr as spansPreviousPath,fe as spawnDetached,bt as splitMarkdownBlocks,gt as startWatcher,wt as streamingProblemEvent,He as swapContributors,E as toBroadcasterKey,Zt as tracedAppendFileSync,gr as tracedLinkSync,Vn as tracedMkdir,or as tracedMkdirSync,vn as tracedRename,Mt as tracedRenameSync,Kn as tracedRmSync,dr as tracedRmdirSync,Ht as tracedUnlinkSync,jn as tracedWriteFile,xr as tracedWriteFileSync,qt as updateLastKnownHash,c as updateProcessLockPort,s as updateServerLockPort,nn as updateUiLockPort,Zn as validateAgentId,In as validateCloneInputs,pn as validateSkillZip,cn as withSpan,Dt as withSpanSync,Er as writeRootGitignoreForNewRepo,Br as writeStateManifest,Lt as writeTargetVersion,Fr as writeTracker};
1
+ import{Vr as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,q as p,r as m,rn as h,s as g,sn as _,t as v,u as y,vn as b,xn as x,yr as S,zr as C}from"./server-lock-BpjJj3OD-2pOoEhSP.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,Ni as De,Nn as Oe,Nr as ke,Nt as Ae,O as je,On as Me,Or as Ne,Ot as Pe,P as Fe,Pi as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qn as Ve,Qr as He,Qt as Ue,R as We,Rn as Ge,Rr as Ke,Rt as qe,S as Je,Sn as Ye,Sr as Xe,St as Ze,T as Qe,Tn as $e,Tr as et,Tt as tt,U as nt,Un as rt,Ur as it,Ut as at,V as ot,Vn as st,Vr as ct,Vt as lt,W as ut,Wn as dt,Wr as ft,Wt as pt,X as mt,Xn as ht,Xr as gt,Xt as _t,Y as vt,Yn as yt,Yr as bt,Yt as xt,Z as St,Zn as Ct,Zr as wt,Zt as Tt,_ as Et,_i as Dt,_n as Ot,_r as kt,_t as At,a as jt,ai as Mt,an as Nt,ar as Pt,at as Ft,b as It,bi as Lt,bn as Rt,br as zt,bt as Bt,c as Vt,ci as Ht,cn as Ut,cr as Wt,ct as Gt,d as Kt,di as qt,dn as Jt,dr as Yt,dt as Xt,ei as Zt,en as Qt,er as $t,et as en,f as tn,fi as nn,fn as rn,fr as an,ft as on,g as sn,gi as cn,gn as ln,gr as un,gt as dn,h as fn,hi as pn,hn as mn,hr as hn,ht as gn,i as _n,ii as vn,in as yn,ir as bn,it as xn,j as Sn,jn as Cn,jr as wn,jt as Tn,k as En,kn as Dn,kr as On,kt as kn,l as An,li as jn,ln as Mn,lr as Nn,lt as Pn,m as Fn,mi as In,mn as Ln,mr as Rn,mt as zn,n as Bn,ni as Vn,nn as Hn,nr as Un,nt as Wn,o as Gn,oi as Kn,on as qn,or as Jn,ot as Yn,p as Xn,pi as Zn,pn as Qn,pr as $n,pt as er,q as tr,qn as nr,qr as rr,qt as ir,r as ar,ri as or,rn as sr,rr as cr,rt as lr,s as ur,si as dr,sn as fr,sr as pr,st as mr,t as hr,ti as gr,tn as _r,tr as vr,tt as yr,u as br,ui as xr,un as Sr,ur as Cr,ut as wr,v as Tr,vi as Er,vn as Dr,vr as Or,vt as kr,w as Ar,wn as jr,wr as Mr,wt as Nr,x as Pr,xi as Fr,xn as Ir,xr as Lr,xt as Rr,y as zr,yi as Br,yn as Vr,yr as Hr,yt as Ur,z as Wr,zn as Gr,zr as Kr,zt as qr}from"./dist-sld-_d9T.mjs";export{hr as AGENT_ID_MAX_LEN,Bn as AGENT_ID_RE,ar as AGENT_WRITE_ORIGIN,_n as AgentFocusBroadcaster,jt as AgentPresenceBroadcaster,Gn as AgentSessionCapacityError,ur as AgentSessionManager,Vt as BacklinkIndex,An as CC1Broadcaster,p as CC1_CONTRACT_VERSION,br as CONFIG_FILENAME,Kt as CONFLICT_MARKER_RE,tn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Xn as ConfigSchema,Fn as DEFAULT_CHECKPOINT_RETENTION,fn as DEFAULT_PACK_ID,sn as FILE_SYSTEM_WRITER,Et as FILE_WATCHER_ORIGIN,Tr as GIT_PREFLIGHT_FAIL_SPAN_NAME,zr as GIT_UPSTREAM_WRITER,De as GitDirAccessError,It as GitNotAvailableError,Pr as GitTooOldError,Je as HOCUSPOCUS_AUTH_REJECTION_REASONS,I as HocuspocusAuthRejection,Ar as HocuspocusAuthTokenSchema,Qe as INSTALLED_AGENTS_SCHEMES,W as LIVE_DERIVED_INDEX_DEBOUNCE_MS,B as LOG_MD_TEMPLATE,je as MANAGED_RENAME_ORIGIN,En as MAX_AGENT_SESSIONS,O as MCP_CONNECTION_ID_HEADER,Sn as MCP_SERVER_NAME,Se as MIN_GIT_VERSION,Ee as MISSING_OK_CONFIG_MESSAGE,Ie as MalformedGitPointerError,Fe as McpLogger,J as MissingOkConfigError,oe as OBSERVER_SYNC_ORIGIN,ve as OK_OKIGNORE_TEMPLATE,h as ORPHAN_MODES,We as PANE_TARGET_TTL_MS,_ as PROTOCOL_VERSION,Wr as PinoLogger,v as ProcessLockCollisionError,M as ProjectGitInitError,ot as ROLLBACK_ORIGIN,ne as ROOT_GITIGNORE_TEMPLATE,u as RUNTIME_VERSION,nt as SERVICE_WRITER,ut as SKILL_INSTALL_EVENTS_FILE_REL,b as SKILL_STATE_TARGETS,Q as STARTER_FOLDERS,me as STARTER_FOLDER_FRONTMATTER_FILENAME,tr as STARTER_PACKS,ue as STARTER_PACK_IDS,vt as STARTER_TEMPLATES,mt as STATE_MANIFEST_FILENAME,m as STATE_SCHEMA_VERSION,x as SYSTEM_DOC_NAME,St as SeedPrerequisiteError,Be as SeedRootDirError,s as ServerLockCollisionError,w as StateManifestError,en as TagIndex,yr as UiLockCollisionError,Wn as __getShowAllWalkStatsForTesting,lr as __resetShowAllWalkStatsForTesting,t as acquireProcessLock,d as acquireServerLock,xn as acquireUiLock,Ft as applyAgentMarkdownWrite,Yn as applyExternalChange,mr as applySeed,Gt as armPaneTarget,Pn as assertCompatibleStateManifest,wr as assertGitAvailable,Xt as assertNeverDiskEvent,on as attachIdleShutdown,er as bootServer,zn as buildAndOpenSkill,gn as buildConfigYmlContent,dn as buildExecResult,At as buildInstructions,kr as buildSkillZip,Ur as buildStarterFolderFrontmatterYaml,Bt as buildWipTree,Rr as classifyEvents,Ze as classifyFsPath,z as clearArmedPaneTarget,Nr as clearContributors,tt as coercePackId,S as colorFromSeed,q as commitUpstreamImport,U as commitWip,Pe as commitWipFromTree,kn as compareSemver,j as containsConflictMarkers,Tn as contentHash,Te as contributorCount,Ae as createApiExtension,ze as createAssetServeMiddleware,Z as createContentFilter,le as createContentFilterAsync,xe as createExternalChangeHandler,qe as createFileLogger,qr as createLiveDerivedIndexExtension,F as createMcpHttpHandler,lt as createOsProbe,ae as createPersistenceExtension,at as createServer,pt as createServerObserverExtension,te as createStreamingErrorWriter,_e as createTestLogger,ir as detectClaudeDesktopPresence,pe as detectGit,xt as detectProjectShape,_t as emitPreflightFailureSpan,Tt as encodeDocName,Ue as encodeFolderRoute,D as ensureProjectGit,Qt as errorResponse,_r as evictStaleTrackerEntries,Hn as extractWikiLinksFromMarkdown,sr as fallbackPaths,yn as findEnclosingGitRoot,Nt as findEnclosingProjectRoot,qn as formatAuthRejectionWire,fr as formatContributors,Ut as formatContributorsFrom,Mn as gcCheckpointRefs,Sr as getCurrentMcpLogger,Jt as getLocalDir,rn as getLogFilePath,Qn as getLogger,Ln as getLogsDir,mn as getMeter,ln as getMetrics,Ot as getTracer,Dr as handleCollabSocketError,Vr as handleSpawnCursor,C as iconFromClientName,Rt as incrementCollabSocketFilteredError,Ir as incrementServerObserverFire,Ye as initContent,L as initShadowRepo,jr as initTelemetry,$e as installPrettyZodErrors,G as installTestLoggers,V as installUserSkill,Me as isAllowedApiOrigin,Dn as isAllowedWorkspaceHostHeader,k as isConfigDoc,Cn as isHocuspocusAuthRejectionReason,Ce as isKnownPackId,Oe as isLoopbackAddress,e as isOrphanMode,Le as isPairedWriteOrigin,Y as isPathWithinDir,g as isProcessAlive,se as isProjectRoot,ye as isSelfWrite,Ge as isSystemDoc,n as isValidLockPid,Gr as lastKnownHash,N as listRescueCheckpoints,st as listStarterPacks,re as loadPrincipal,c as lockFilePath,rt as loggerFactory,dt as logsCurrentPath,$ as logsPreviousPath,he as mountMcpAndApi,nr as normalizeFsPath,de as packageVersionMajorMinor,yt as parseAuthRejectionWire,ht as parseGitVersion,Ct as parseHocuspocusAuthToken,Ve as parseKeepaliveConnectionId,T as pathToDocName,$t as planSeed,vr as readAllTargets,Un as readArmedPaneTarget,cr as readBranchFromHead,y as readProcessLock,r as readProcessLockDetailed,i as readServerLock,bn as readServerPackageVersion,Pt as readSkillInstallStateSnapshot,Jn as readStateManifest,pr as readTargetRecordedAt,Wt as readTargetVersion,Nn as readUiLock,Cr as reconcile,Yt as recordContributor,an as recordSkillInstallEvent,$n as registerAllTools,Rn as registerWrite,f as releaseProcessLock,l as releaseServerLock,hn as releaseUiLock,un as removeLastKnownHash,kt as resetMetrics,Or as resolveBundledSkillDir,Hr as resolveContentDir,zt as resolveCursorBinaryDefault,Lr as resolveCursorSpawnInvocation,Xe as resolveLockDir,R as resolvePack,Mr as resolvePackageVersion,et as resolveUiInfo,K as restoreContributors,H as restoreLifecycleFromConflictsJson,Ne as rewriteMarkdownLinksForDocumentRename,On as rewriteWikiLinksForDocumentRename,A as runAuthReposSubprocess,wn as runAuthStatusSubprocess,we as runCloneSubprocess,ke as runDeviceFlowSubprocess,Re as runWithMcpLogger,X as safeContentPath,ce as safeSubdir,be as safetyCheckpoint,Ke as sanitizeClientName,Kr as saveInMemoryCheckpoint,P as saveVersion,ct as seedBasenameIndex,ie as serializeError,it as setActiveSpanAttributes,ft as shadowGit,ee as shutdownTelemetry,ge as spansCurrentPath,rr as spansPreviousPath,fe as spawnDetached,bt as splitMarkdownBlocks,gt as startWatcher,wt as streamingProblemEvent,He as swapContributors,E as toBroadcasterKey,Zt as tracedAppendFileSync,gr as tracedLinkSync,Vn as tracedMkdir,or as tracedMkdirSync,vn as tracedRename,Mt as tracedRenameSync,Kn as tracedRmSync,dr as tracedRmdirSync,Ht as tracedUnlinkSync,jn as tracedWriteFile,xr as tracedWriteFileSync,qt as updateLastKnownHash,o as updateProcessLockPort,a as updateServerLockPort,nn as updateUiLockPort,Zn as validateAgentId,In as validateCloneInputs,pn as validateSkillZip,cn as withSpan,Dt as withSpanSync,Er as writeRootGitignoreForNewRepo,Br as writeStateManifest,Lt as writeTargetVersion,Fr as writeTracker};