@inkeep/open-knowledge 0.11.1-beta.0 → 0.11.1-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +5 -0
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +9 -9
- package/dist/constants-DqRszxHb.mjs +2 -0
- package/dist/dist-C3GEAWC-.mjs +1 -0
- package/dist/{dist-Bms63Kbz.mjs → dist-DE6um5_s.mjs} +9 -9
- package/dist/{gh-detect-TiuAfW0N.mjs → gh-detect-kCqeGSBq.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/init-BhtmBkLG.mjs +1 -0
- package/dist/{init-ClLEt0k7.mjs → init-BudmYOFP.mjs} +4 -4
- package/dist/loader-C7BqYdV-.mjs +1 -0
- package/dist/{loader-x4Hpo3YH.mjs → loader-DlhVX5cM.mjs} +3 -3
- package/dist/{preview-slpAYVBO.mjs → preview-CZ4ZFSmM.mjs} +2 -2
- package/dist/preview-DaXp5otx.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-Dv5Y8bcN.js → ActivityModeContent-BIWS6D87.js} +1 -1
- package/dist/public/assets/{ConsentDialogBody-CM1Lm4n9.js → ConsentDialogBody-Bd3NDbzN.js} +1 -1
- package/dist/public/assets/{DocumentContext-CGZbRc-L.js → DocumentContext-DH9Tlc8u.js} +1 -1
- package/dist/public/assets/{GraphPanel-DLvT2Kzo.js → GraphPanel-nBQ8tQHf.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-sOEyFULC.js → McpConsentDialogBody-pUjQ4lzI.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-Vak-yX1q.js → SettingsDialogBody-BoO7h5RZ.js} +1 -1
- package/dist/public/assets/{SourceEditor-BhyrFsfA.js → SourceEditor-B0dTob-N.js} +1 -1
- package/dist/public/assets/{agent-presence-B9GoWq0r.js → agent-presence-B_GJzt87.js} +1 -1
- package/dist/public/assets/button-B_6r-4tt.js +1 -0
- package/dist/public/assets/{checkbox-Co7Tjlri.js → checkbox-qnHi6HI6.js} +1 -1
- package/dist/public/assets/{collapsible-BhpeB6tu.js → collapsible-DC_eQWsn.js} +1 -1
- package/dist/public/assets/{config-validation-events-BmFSWND9.js → config-validation-events-BqtSkxST.js} +1 -1
- package/dist/public/assets/{dialog-B1es0EvU.js → dialog-uNuZn7gJ.js} +1 -1
- package/dist/public/assets/{dist-P7DYrfOB.js → dist-D6g7y0kn.js} +1 -1
- package/dist/public/assets/{dist-DicqJavT.js → dist-q8_YTqei.js} +1 -1
- package/dist/public/assets/{index-Cq-7omOp.js → index-0Hsxk-Zd.js} +5 -5
- package/dist/public/assets/{keyboard-shortcuts-BgxXrRkA.js → keyboard-shortcuts-BV763lpz.js} +1 -1
- package/dist/public/assets/{label-DwEePOBC.js → label-DLO_wxY0.js} +1 -1
- package/dist/public/assets/{panel-BNBODYwB.js → panel-DDVLqW48.js} +1 -1
- package/dist/public/assets/{prop-types-CKBOLBuy.js → prop-types-BuRZDjx3.js} +145 -145
- package/dist/public/assets/{target-navigation-intent-J4G_G74p.js → target-navigation-intent-BTVLkcR4.js} +1 -1
- package/dist/public/assets/{textarea-luaT-nOK.js → textarea-CaVb3JmO.js} +1 -1
- package/dist/public/assets/{toggle-group-Cs-1L92l.js → toggle-group-sKkFFfhD.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-DTgHmtHd.js → typing-burst-detector-IfqAoCWO.js} +1 -1
- package/dist/public/index.html +18 -18
- package/dist/{repair-launch-json-BKtGkB0B.mjs → repair-launch-json-NMX_dMpz.mjs} +2 -2
- package/dist/{repair-mcp-configs-Hd_Owqnp.mjs → repair-mcp-configs-CqXsMWrb.mjs} +2 -2
- package/dist/repair-skills-C0UVnWkd.mjs +1 -0
- package/dist/{repair-skills-B9dEoHjt.mjs → repair-skills-PPm3Ear1.mjs} +2 -2
- package/dist/{server-lock-BpjJj3OD-CfUjMF3O.mjs → server-lock-BpjJj3OD-Dw5FXP_d.mjs} +27 -25
- package/dist/server-lock-CyhBidkz-CgCFFLF6.mjs +1 -0
- package/dist/{src-Lw06Pp2P.mjs → src-CL8sz3m_.mjs} +2 -2
- package/dist/{start-BOWAtuDV.mjs → start-CxJVcRBA.mjs} +2 -2
- package/dist/start-DqcllJQs.mjs +1 -0
- package/dist/{write-project-skill-CoFl-uBP.mjs → write-project-skill-BCASHlPk.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BLJc6MOZ.mjs +0 -2
- package/dist/dist-B2QcMC3d.mjs +0 -1
- package/dist/init-YGnAcdfz.mjs +0 -1
- package/dist/loader-DvqvLN6q.mjs +0 -1
- package/dist/preview-DUXc51R-.mjs +0 -1
- package/dist/public/assets/button-DenIdY-r.js +0 -1
- package/dist/repair-skills-BsQTjR1m.mjs +0 -1
- package/dist/server-lock-CyhBidkz-D9A193jJ.mjs +0 -1
- package/dist/start-Clj6qMIe.mjs +0 -1
|
@@ -5251,6 +5251,11 @@ Homepage: https://github.com/sindresorhus/tagged-tag
|
|
|
5251
5251
|
|
|
5252
5252
|
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
|
5253
5253
|
|
|
5254
|
+
### `tailwind-merge@3.6.0`
|
|
5255
|
+
Homepage: https://github.com/dcastil/tailwind-merge
|
|
5256
|
+
|
|
5257
|
+
Copyright (c) 2021 Dany Castillo
|
|
5258
|
+
|
|
5254
5259
|
### `tailwind-merge@3.5.0`
|
|
5255
5260
|
Homepage: https://github.com/dcastil/tailwind-merge
|
|
5256
5261
|
|
|
@@ -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.11.1-beta.
|
|
6
|
+
version: "0.11.1-beta.2"
|
|
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`, `edit`, 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.11.1-beta.
|
|
6
|
+
version: "0.11.1-beta.2"
|
|
7
7
|
author: "Inkeep"
|
|
8
8
|
repository: "https://github.com/inkeep/open-knowledge"
|
|
9
9
|
---
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{
|
|
2
|
+
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$i as n,Bi as r,Hi as i,Ii as a,Ji as o,Ki as s,Ti as c,Ur as l,Vi as u,Yi as d,aa as f,ba as p,f as m,ki as h,n as g,na as _,qi as v,s as y,wi as b,xr as x,ya as S,yn as ee}from"./server-lock-BpjJj3OD-Dw5FXP_d.mjs";import{a as te,n as C,r as ne,t as re}from"./gh-detect-kCqeGSBq.mjs";import{r as ie}from"./git-handle-Cd7K54Co-D4vPl00M.mjs";import{Bi as ae,C as oe,Ct as se,Dr as ce,Ii as le,In as ue,Ir as w,Ji as de,Ki as fe,Li as pe,N as me,Nn as he,Nr as ge,P as _e,Qr as ve,Ri as ye,Sn as be,Vi as xe,Wi as Se,Wt as Ce,X as we,Xi as Te,Z as Ee,_ as De,_r as Oe,bt as ke,cn as Ae,et as je,fr as Me,g as Ne,gn as Pe,gt as Fe,it as Ie,jt as Le,nn as Re,nt as ze,pr as Be,pt as Ve,qi as He,qn as Ue,qt as We,rt as Ge,sn as Ke,w as qe,zi as Je,zr as Ye}from"./dist-DE6um5_s.mjs";import{t as Xe}from"./yazl-CB0sfSbo.mjs";import{n as Ze,r as Qe,t as T}from"./dist-bundle-B3l-HkEL.mjs";import{B as $e,C as et,E as tt,F as nt,H as rt,I as it,L as at,M as ot,N as st,P as ct,R as lt,S as ut,T as dt,V as ft,b as pt,u as mt,v as ht,w as gt,z as _t}from"./init-BudmYOFP.mjs";import{a as vt,c as yt,h as bt,i as xt,l as St,m as Ct,o as wt,s as Tt,u as Et}from"./src-CL8sz3m_.mjs";import{n as Dt,t as Ot}from"./constants-DqRszxHb.mjs";import{n as kt,t as At}from"./loader-DlhVX5cM.mjs";import{S as jt,_ as Mt,b as Nt,m as Pt,x as Ft,y as It}from"./start-CxJVcRBA.mjs";import{c as Lt,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-BtKMHmBX.mjs";import{n as Rt}from"./repair-skills-PPm3Ear1.mjs";import{execSync as zt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as Bt,closeSync as Vt,constants as Ht,cpSync as Ut,createWriteStream as Wt,existsSync as P,mkdirSync as F,mkdtempSync as Gt,openSync as Kt,readFileSync as I,readdirSync as qt,realpathSync as Jt,rmSync as Yt,statSync as Xt,unlinkSync as Zt,writeFileSync as L}from"node:fs";import Qt,{basename as R,dirname as $t,join as z,relative as en,resolve as B,sep as tn}from"node:path";import nn from"node:process";import{arch as rn,freemem as an,homedir as on,platform as sn,release as cn,tmpdir as ln,totalmem as un,type as dn,uptime as fn}from"node:os";import{fileURLToPath as pn}from"node:url";import{rm as mn}from"node:fs/promises";import{createHash as hn,randomUUID as gn}from"node:crypto";import{setTimeout as _n}from"node:timers/promises";import{stripVTControlCharacters as vn,styleText as V}from"node:util";import{AsyncLocalStorage as yn,AsyncResource as bn}from"node:async_hooks";import*as xn from"node:readline";import{createInterface as Sn}from"node:readline/promises";const Cn={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 wn;(function(e){})(wn||={});function Tn(e){return f(a,e)}async function En(e,t,n,r){let i=Dn(await On(e)).host??``;if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let a=await n.get(i),o=r?.getDiag?.(),s=a==null?o?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:s,backend:n.backend,...o?.error?{keychainError:o.error}:{}};s===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}if(a==null)return 1;let c=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${c(a.login)}\npassword=${c(a.token)}\n`),0}function Dn(e){let t={};for(let n of e.split(`
|
|
3
3
|
`)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function On(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function kn(e,n){let r=new t(`git-credential`);return r.description(`Git credential helper (git credential-helper protocol)`),r.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=n?.();try{let n,r=await e({onKeychainRead:e=>{n=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&t?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await En(process.stdin,process.stdout,r,{log:t,getDiag:()=>n});await Pe(t),process.exit(i)}catch(e){t?.error({error:e instanceof Error?e.message:String(e)},`[auth] git-credential get: unexpected error`),await Pe(t),process.exit(1)}}),r}function An(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function jn(e,t,n){let r={baseUrl:An(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new Ze(`${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 Mn(e){let t=e.request||T,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),jn(t,`POST /login/device/code`,n)}async function Nn(e){let t=await jn(e.request||T,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Pn(e,t.data.expires_in),n.refreshTokenExpiresAt=Pn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Pn(e,t){return new Date(e+t*1e3).toISOString()}async function Fn(e,t){let n=In(e,t.auth);if(n)return n;let{data:r}=await Mn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Rn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function In(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 Ln(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Rn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Nn({...i,clientType:`oauth-app`}):await Nn({...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 Ln(r.interval),Rn(e,t,n,r);if(a===`slow_down`)return await Ln(r.interval+7),Rn(e,t,n,r);throw i}}async function zn(e,t){return Fn(e,{auth:t})}async function Bn(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 Fn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Vn=`0.0.0-development`;function Hn(e){let t=e.request||T.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Vn} ${Qe()}`}}),{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(zn.bind(null,i),{hook:Bn.bind(null,i)})}async function Un(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=Hn({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-XlngXUNr.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Wn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Gn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function H(e){let t=e.toLowerCase().replace(/:\d+$/,``);Gn.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 Kn(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function qn(e,t,n=Un){let r=Wn(),{host:i,json:a}=e;H(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?Kn(!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?Kn(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function Jn(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 qn(t,await e())})}const Yn=e=>e.name===`enter`||e.name===`return`;var Xn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Zn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Qn=class extends Error{name=`ExitPromptError`},$n=class extends Error{name=`HookError`},er=class extends Error{name=`ValidationError`};const tr=new yn;function nr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function rr(e,t){let n=nr(e);return tr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function U(){let e=tr.getStore();if(!e)throw new $n(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function ir(){return U().rl}function ar(e){return bn.bind((...t)=>{let n=U(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function or(e){let t=U(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function sr(){U().handleChange()}const cr={queue(e){let t=U(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(ir());if(r!=null&&typeof r!=`function`)throw new er(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=U();ar(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=U();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function lr(e){return typeof e==`function`}function W(e){return or(t=>{let n=bn.bind(function(e){t.get()!==e&&(t.set(e),sr())});if(t.initialized)return[t.get(),n];let r=lr(e)?e():e;return t.set(r),[r,n]})}function ur(e,t){or(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&cr.queue(e),n.set(t)})}const dr={prefix:{idle:V(`blue`,`?`),done:V(`green`,rt.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>V(`yellow`,e))},style:{answer:e=>V(`cyan`,e),message:e=>V(`bold`,e),error:e=>V(`red`,`> ${e}`),defaultAnswer:e=>V(`dim`,`(${e})`),help:e=>V(`dim`,e),highlight:e=>V(`cyan`,e),key:e=>V(`cyan`,V(`bold`,`<${e}>`))}};function fr(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 pr(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=fr(n)&&fr(r)?pr(n,r):r}return t}function mr(...e){return pr(dr,...e.filter(e=>e!=null))}function hr({status:e=`idle`,theme:t}){let[n,r]=W(!1),[i,a]=W(0),{prefix:o,spinner:s}=mr(t);return ur(()=>{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 gr(e){return W({current:e})[0]}function _r(e){let t=gr(e);t.current=e,ur(e=>{let n=!1,r=ar((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var vr=e(ft(),1);function yr(e,t){return e.split(`
|
|
4
4
|
`).flatMap(e=>$e(e,t,{trim:!1,hard:!0}).split(`
|
|
5
5
|
`).map(e=>e.trimEnd())).join(`
|
|
@@ -17,9 +17,9 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
|
|
|
17
17
|
`)}function Ai(){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async e=>{await ki(e)})}async function ji(e,t,n=re){let r=n(e);if(r.available&&r.token)return{tier:`A`,token:r.token};let i=await t.get(e);return i==null?{tier:`none`}:{tier:i.gitProtocol===`ssh`?`C`:`B`,token:i.token}}function Mi(e,t,n){return{type:`status`,host:e,backend:t,...n}}async function Ni(e,t){let{host:n,json:r}=e;H(n);let i=t.backend,a=await ji(n,t);a.tier===`none`&&(r?process.stdout.write(`${JSON.stringify(Mi(n,i,{authenticated:!1}))}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let o=n===`github.com`?void 0:`https://${n}/api/v3`,s=new K({auth:a.token,...o?{baseUrl:o}:{}});try{let{data:e}=await s.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify(Mi(n,i,{authenticated:!0,tier:a.tier,login:e.login,name:e.name,email:e.email}))}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(`${JSON.stringify(Mi(n,i,{authenticated:!1,error:`token invalid`}))}\n`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Pi(e){return new t(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Ni(t,await e())})}function Fi(e){let n=new t(`auth`);n.description(`GitHub authentication management`);let r=e=>ne(void 0,e);return n.addCommand(Jn(r)),n.addCommand(Pi(r)),n.addCommand(Oi(r)),n.addCommand(Ai()),n.addCommand(Ti(r)),n.addCommand(kn(r,e)),n}const Ii=[{name:`macos-home-path`,regex:/\/Users\/[^/]+\//g,replacement:`~/`},{name:`linux-home-path`,regex:/\/home\/[^/]+\//g,replacement:`~/`},{name:`github-pat`,regex:/\b(ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}\b/g,replacement:`[REDACTED-GH-PAT]`},{name:`aws-access-key`,regex:/\b(AKIA|ASIA|ABIA)[A-Z2-7]{16}\b/g,replacement:`[REDACTED-AWS-KEY]`},{name:`anthropic-key`,regex:/\bsk-ant-api03-[A-Za-z0-9_-]{20,}\b/g,replacement:`[REDACTED-ANTHROPIC]`},{name:`openai-key`,regex:/\bsk-[A-Za-z0-9]{20,}\b/g,replacement:`[REDACTED-OPENAI]`},{name:`bearer-token`,regex:/([Aa]uthorization:\s*[Bb]earer\s+)\S+/g,replacement:`$1[REDACTED]`},{name:`jwt`,regex:/eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,replacement:`[REDACTED-JWT]`},{name:`url-credentials`,regex:/:\/\/[^/\s:@]+:[^/\s:@]+@/g,replacement:`://[REDACTED]@`}],Li=Ii.map(e=>e.name);function Ri(e){let t=new Set,n=0;return{redacted:e.split(`
|
|
18
18
|
`).map(e=>{let r=e;for(let{name:e,regex:i,replacement:a}of Ii)i.lastIndex=0,i.test(r)&&(t.add(e),n++,i.lastIndex=0,r=r.replace(i,a));return r}).join(`
|
|
19
19
|
`),patterns:[...t],lineCount:n}}const zi=z(on(),`.ok`,`logs`),Bi=z(on(),`.ok`,`bug-reports`);function Vi(e){let t=z(e,`.ok`,`config.yml`);if(P(t))try{let e=I(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return P(z(e,`.ok`))?hn(`sha256`).update(B(e)).digest(`hex`).slice(0,12):null}function Hi(){let e={timestamp:new Date().toISOString(),platform:sn(),osType:dn(),osRelease:cn(),hostname:`[redacted]`,uptime:fn(),freeMem:an(),totalMem:un(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=zt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=z(__dirname,`..`,`..`,`package.json`);P(t)&&(e.okVersion=JSON.parse(I(t,`utf8`)).version)}catch{}return e}function Ui(e){if(!P(zi))return{files:[],dir:zi};let t=qt(zi).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>z(zi,e));if(e&&t.length>0){let n=t.filter(t=>{try{return I(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:zi}}function Wi(e){let t=z(e,`.ok`,`local`);return P(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}function Gi(e){let t=z(e,`.ok`,`local`,`logs`);return P(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}async function Ki(t){let n=_u();F(Bi,{recursive:!0});let r=z(Bi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Hi(),{files:a}=Ui(t.projectSlug),{files:o}=Wi(t.cwd),{files:s}=Gi(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-Dqnhfxk7.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Ri(I(e,`utf8`)),i=`logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of o)try{let{redacted:t,patterns:n,lineCount:r}=Ri(I(e,`utf8`)),i=`lockdir/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of s)try{let{redacted:t,patterns:n,lineCount:r}=Ri(I(e,`utf8`)),i=`local-logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}let f=JSON.stringify(i,null,2);d.addBuffer(Buffer.from(f,`utf8`),`sysinfo.json`),l.push(`sysinfo.json`);let p={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:t.projectSlug,files:l,redactions:c,sysinfo:i};d.addBuffer(Buffer.from(JSON.stringify(p,null,2),`utf8`),`MANIFEST.json`);let m=c.reduce((e,t)=>e+t.lineCount,0),h=[`# Bug Report Bundle`,``,`Generated: ${p.generatedAt}`,`Project: ${t.projectSlug??`(unscoped)`}`,`Discipline version: ${p.disciplineVersion}`,``,`## Contents`,``,...l.map(e=>`- ${e}`),``,`## Privacy`,``,`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Li.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
|
|
20
|
-
`);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Wt(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&&sn()===`darwin`)try{M(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function qi(){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=Vi(t);try{await Ki({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 Ji(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 Yi(e){let t=e.inspect??(t=>bt(e.lockDir,t)),n=e.unlink??(e=>Zt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ji(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 Xi(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Yi({lockDir:w(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 Qi(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 $i=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function ea(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 $i)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function ta(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const na=
|
|
20
|
+
`);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Wt(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&&sn()===`darwin`)try{M(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function qi(){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=Vi(t);try{await Ki({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 Ji(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 Yi(e){let t=e.inspect??(t=>bt(e.lockDir,t)),n=e.unlink??(e=>Zt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ji(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 Xi(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Yi({lockDir:w(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 Qi(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 $i=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function ea(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 $i)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function ta(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const na=l;async function ra(e){try{return await e.clone(ta(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&na(t))return e.onFallback(e.branch),await e.clone(ta(null)),{fellBack:!0};throw t}}function ia(e,t,n){return e===`https`&&t===`github.com`&&n}async function aa(e,t,n,r=process.cwd()){let i=Ct(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?B(r,t.dir):B(r,i.name);if(P(a)&&qt(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=te(),s=i.protocol===`https`&&i.hostname===`github.com`?await Qi(i.owner,i.name):!1,c=ia(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await Zi(i.hostname,o,{}),l=ie({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(`
|
|
21
21
|
`)){let n=ea(e);n&&n.pct!==u&&(u=n.pct,q(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await ra({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>l.clone(e,a,t),onFallback:e=>{q(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
|
|
22
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
22
|
+
`);try{let{runInit:e}=await import(`./init-BhtmBkLG.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{oa(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function oa(e){let t=pt(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function sa(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 aa(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DqcllJQs.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?q(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var ca=p();const la=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...c.map(e=>e.path)];function ua(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??kt;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 da(e){let t=(0,ca.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of la)t.hasIn(e)&&n.push(e.join(`.`));return n}function fa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pa(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=fa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ma(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??fe,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:Se(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:Se(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!P(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=da(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:pa(la.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:h(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 ha(){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(()=>{ua({}).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 ma({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var ga=e(Xe(),1),J=e(Lt(),1);const _a=new Set([`doc.name`]);function va(e){return`doc:${hn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function ya(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 ba(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=va(e);return t.originalToHashed.set(e,r),ya(t,e,r),r}function xa(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function Sa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ca(e,t){if(typeof e==`string`)return xa(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Ca(e,t));if(!Sa(e))return e;let n=typeof e.key==`string`&&_a.has(e.key)&&Sa(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`&&Sa(a)){let e=ba(n,t);r[i]={...a,stringValue:e}}else _a.has(i)&&typeof a==`string`?r[i]=ba(a,t):r[i]=Ca(a,t);return r}function wa(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 Ta(e,t){let n=I(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
23
23
|
`),i=n.split(`
|
|
24
24
|
`),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=Ca(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}L(e,r?`${a.join(`
|
|
25
25
|
`)}\n`:a.join(`
|
|
@@ -49,26 +49,26 @@ ws.addEventListener('error', () => process.exit(1));
|
|
|
49
49
|
setTimeout(() => process.exit(2), ${t+1e4});
|
|
50
50
|
`),r}async function No(e,t,n,r,i){let a=Mo(e,t,z(r,`cpu.cpuprofile`)),o=!1,s=M(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=Oo(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{Yt(z(a,`..`),{recursive:!0,force:!0})}catch{}return o}function Po(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(`
|
|
51
51
|
`)}async function Fo(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??yt,s=t.inspect??bt,c=t.resolveCommand??St,l=t.resolveUsage??Et,u=t.collectLsofFn??ko,d=t.getEndpoints??jo,f=t.profiler??No,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(J.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let b=new Date().toISOString().replace(/[:.]/g,`-`),x=e.output?e.output:v?z(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):z(process.cwd(),`ok-diagnose-${n}-${b}`);try{F(x,{recursive:!0})}catch(e){a(J.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(J.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{L(z(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?Ao(C).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(J.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){S(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,x,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(J.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
|
|
52
|
-
`)}\n`);try{S(`stacks.txt`,Po(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Io(e){let t=Sn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Lo(e){let t=Gt(z(ln(),`ok-bundle-process-`));return await Fo({pid:e,output:t}),t}function Ro(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 zo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Bo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ro(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 Vo(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Io,i=t.runProcessDiagnose??Lo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=$t(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await ao({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),Bo(n,c,o),e.yes!==!0&&!zo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await oo({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Yt(s,{recursive:!0,force:!0})}catch{}}}function Ho(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Fo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Do()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-
|
|
52
|
+
`)}\n`);try{S(`stacks.txt`,Po(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Io(e){let t=Sn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Lo(e){let t=Gt(z(ln(),`ok-bundle-process-`));return await Fo({pid:e,output:t}),t}function Ro(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 zo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Bo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ro(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 Vo(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Io,i=t.runProcessDiagnose??Lo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=$t(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await ao({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),Bo(n,c,o),e.yes!==!0&&!zo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await oo({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Yt(s,{recursive:!0,force:!0})}catch{}}}function Ho(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Fo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Do()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-C7BqYdV-.mjs`),{resolveContentDir:r}=await import(`./dist-C3GEAWC-.mjs`),i=process.cwd(),{config:a}=n(i);await Vo({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function Uo(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Ar({message:`Enter OpenAI embeddings API key:`})).trim()}function Wo(e){return Oe(e)}async function Go(){return(await Re()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function Ko(e){try{let t=m(w(e));if(!t||t.port<=0||!y(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function qo(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await Uo();if(!e){process.stderr.write(`No key provided.
|
|
53
53
|
`),process.exitCode=1;return}await Ce().set(e),process.stderr.write(`✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).
|
|
54
54
|
Now enable it per project — the easiest path is OK Desktop → Settings → This
|
|
55
55
|
project → Search (a toggle with an egress-confirmation prompt), or run
|
|
56
56
|
\`ok embeddings enable\` in the project folder.
|
|
57
57
|
`)})}function Jo(){return new t(`clear-key`).description(`Remove your stored OpenAI embeddings API key`).action(async()=>{let{touched:e}=await Le();if(e.length===0){process.stderr.write(`No stored OpenAI embeddings key found.
|
|
58
|
-
`);return}process.stderr.write(`✓ OpenAI embeddings API key cleared (${e.join(`, `)}).\n`)})}function Yo(e,n){return new t(e).description(`Turn semantic search ${n?`on`:`off`} for this project (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async t=>{let r=B(t.cwd??process.cwd()),i=await fe({cwd:r,scope:`project-local`,patch:{search:{semantic:{enabled:n}}}});if(!i.ok){process.stderr.write(`Failed to ${e} semantic search — ${
|
|
58
|
+
`);return}process.stderr.write(`✓ OpenAI embeddings API key cleared (${e.join(`, `)}).\n`)})}function Yo(e,n){return new t(e).description(`Turn semantic search ${n?`on`:`off`} for this project (project-local)`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).action(async t=>{let r=B(t.cwd??process.cwd()),i=await fe({cwd:r,scope:`project-local`,patch:{search:{semantic:{enabled:n}}}});if(!i.ok){process.stderr.write(`Failed to ${e} semantic search — ${h(i.error)}\n`),process.exitCode=1;return}if(process.stderr.write(`✓ Semantic search ${n?`enabled`:`disabled`} for ${r}\n`),n){let{present:e}=await Go();e||process.stderr.write(" Note: no API key set yet — run `ok embeddings set-key`. Until then, search stays lexical.\n")}})}function Xo(){return new t(`status`).description(`Show semantic-search capability: key presence, enabled, coverage, provider`).option(`--cwd <path>`,`Project directory (defaults to the current directory)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.cwd??process.cwd()),n=Wo(t),{present:r,source:i}=await Go(),a=n.enabled&&r,o=a?await Ko(t):null;if(e.json){process.stdout.write(`${JSON.stringify({project:t,machine:{keyPresent:r,keySource:i},project_config:{enabled:n.enabled,capable:a,coverage:o?{embedded:o.embedded,total:o.total}:null,provider:{baseUrl:n.baseUrl,model:n.model,dimensions:n.dimensions??null}}})}\n`);return}let s=r?`set — ${i===`env`?`environment (${De})`:`~/.ok/secrets.yml`}`:`not set`,c=a?o?`${o.embedded} / ${o.total} pages embedded`:`server not running — start it to index (or it has not embedded yet)`:null,l=[`Semantic search`,` project: ${t}`,``,` This machine (all projects):`,` API key: ${s}`,``,` This project:`,` enabled: ${n.enabled?`yes`:`no`}`,` capability: ${a?`AVAILABLE`:`unavailable (search stays lexical)`}`,...c?[` coverage: ${c}`]:[],` provider: ${n.baseUrl}`,` model: ${n.model}`,` dimensions: ${n.dimensions??`native (1536)`}`],u=[];r||u.push(`Set a key: ok embeddings set-key (or export ${De})`),n.enabled||u.push(`Enable it: ok embeddings enable (in this project folder)`),u.length>0&&l.push(``,...u.map(e=>` ${e}`)),process.stdout.write(`${l.join(`
|
|
59
59
|
`)}\n`)})}function Zo(){return new t(`embeddings`).description(`Manage the semantic-search embeddings provider key + status`).addCommand(qo()).addCommand(Jo()).addCommand(Yo(`enable`,!0)).addCommand(Yo(`disable`,!1)).addCommand(Xo())}const Qo=[` 1. ${j(`Customize`)} (sidebar) → ${j(`Skills`)}`,` 2. Click the ${j(`+`)} button`,` 3. Click ${j(`Create skill`)}`,` 4. Click ${j(`Upload skill`)}`,` 5. Pick ${j(`openknowledge.skill`)} from Downloads`],$o=E(` Open the Claude Desktop App, then: ${j(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function es(e){let t=[O(`Built ${e.outputPath}`),D(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(A(` Handoff failed: ${e.handoffError.message}`)),t.push($o),t.join(`
|
|
60
60
|
`)}function ts(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[E(`Open Knowledge skill ${j(`v${t}`)} already delivered to Claude Desktop.`),D(` Recorded at ${n} in ~/.ok/skill-state.yml`),D(` Use ${j(`--force`)} to rebuild and re-open the install dialog.`)].join(`
|
|
61
61
|
`)}function ns(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[O(`Built ${e.outputPath}`),D(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),E(` Claude Desktop App opened. Now upload the file manually:`),...Qo,D(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
|
|
62
62
|
`)}function rs(e){return`${k(`Error:`)} ${e.buildError??`unknown build failure`}`}async function is(e={}){let t=await ke(e);return t.status===`failed`?{...t,message:rs(t),exitCode:1}:t.status===`skip-current`?{...t,message:ts(t),exitCode:0}:t.status===`installed`?{...t,message:ns(t),exitCode:0}:{...t,message:es(t),exitCode:0}}function as(){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 is({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}const os=z(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),ss=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function cs(e,t,n){return e===`darwin`?[z(t,`Applications`,`Open Knowledge.app`,os),z(`/Applications`,`Open Knowledge.app`,os)].find(e=>n.existsSync(e))??null:null}function ls(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`&&ss.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function us(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 ds(e){us({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??M,n=e.exitProcess??(e=>process.exit(e)),r=e.now??(()=>Date.now()),i=r(),a=e.startupFailureWindowMs??1e3;return new Promise((o,s)=>{let c=t(e.bundlePath,e.argv.filter(e=>e!==`--no-bundle-proxy`),{env:{...e.env,OK_BUNDLE_PROXY:`0`},stdio:`inherit`}),l=e=>{c.kill(e)},u=()=>{process.off(`SIGTERM`,l),process.off(`SIGINT`,l)};process.on(`SIGTERM`,l),process.on(`SIGINT`,l),c.once(`error`,e=>{u(),s(e)}),c.once(`exit`,(e,t)=>{if(u(),t){s(Error(`bundle process exited by signal ${t}`));return}let o=e??0,c=r()-i;if(o!==0&&c<=a){s(Error(`bundle process exited during startup with code ${o}`));return}n(o)})})}function fs(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 ps=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
63
63
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),ms(t)}clear(){this._buffer=void 0}};function ms(e){return pe.parse(JSON.parse(e))}function hs(e){return JSON.stringify(e)+`
|
|
64
|
-
`}var gs=class{constructor(e=nn.stdin,t=nn.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ps,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=hs(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function _s(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 vs(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 ys(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 bs(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 xs(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 Ss(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Cs(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Ss(t.headers),...Ss(r.headers)}:t.headers}):e}let ws;ws=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Ts(e){return(await ws).getRandomValues(new Uint8Array(e))}async function Es(e){let t=``;for(;t.length<e;){let n=await Ts(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Ds(e){return await Es(e)}async function Os(e){let t=await(await ws).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ks(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ds(e);return{code_verifier:t,code_challenge:await Os(t)}}const X=v().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Cn.custom,message:`URL must be parseable`,fatal:!0}),y}).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`}),As=c({resource:u().url(),authorization_servers:n(X).optional(),jwks_uri:u().url().optional(),scopes_supported:n(u()).optional(),bearer_methods_supported:n(u()).optional(),resource_signing_alg_values_supported:n(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:d().optional(),authorization_details_types_supported:n(u()).optional(),dpop_signing_alg_values_supported:n(u()).optional(),dpop_bound_access_tokens_required:d().optional()}),js=c({issuer:u(),authorization_endpoint:X,token_endpoint:X,registration_endpoint:X.optional(),scopes_supported:n(u()).optional(),response_types_supported:n(u()),response_modes_supported:n(u()).optional(),grant_types_supported:n(u()).optional(),token_endpoint_auth_methods_supported:n(u()).optional(),token_endpoint_auth_signing_alg_values_supported:n(u()).optional(),service_documentation:X.optional(),revocation_endpoint:X.optional(),revocation_endpoint_auth_methods_supported:n(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:n(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:n(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:n(u()).optional(),code_challenge_methods_supported:n(u()).optional(),client_id_metadata_document_supported:d().optional()}),Ms=s({...c({issuer:u(),authorization_endpoint:X,token_endpoint:X,userinfo_endpoint:X.optional(),jwks_uri:X,registration_endpoint:X.optional(),scopes_supported:n(u()).optional(),response_types_supported:n(u()),response_modes_supported:n(u()).optional(),grant_types_supported:n(u()).optional(),acr_values_supported:n(u()).optional(),subject_types_supported:n(u()),id_token_signing_alg_values_supported:n(u()),id_token_encryption_alg_values_supported:n(u()).optional(),id_token_encryption_enc_values_supported:n(u()).optional(),userinfo_signing_alg_values_supported:n(u()).optional(),userinfo_encryption_alg_values_supported:n(u()).optional(),userinfo_encryption_enc_values_supported:n(u()).optional(),request_object_signing_alg_values_supported:n(u()).optional(),request_object_encryption_alg_values_supported:n(u()).optional(),request_object_encryption_enc_values_supported:n(u()).optional(),token_endpoint_auth_methods_supported:n(u()).optional(),token_endpoint_auth_signing_alg_values_supported:n(u()).optional(),display_values_supported:n(u()).optional(),claim_types_supported:n(u()).optional(),claims_supported:n(u()).optional(),service_documentation:u().optional(),claims_locales_supported:n(u()).optional(),ui_locales_supported:n(u()).optional(),claims_parameter_supported:d().optional(),request_parameter_supported:d().optional(),request_uri_parameter_supported:d().optional(),require_request_uri_registration:d().optional(),op_policy_uri:X.optional(),op_tos_uri:X.optional(),client_id_metadata_document_supported:d().optional()}).shape,...js.pick({code_challenge_methods_supported:!0}).shape}),Ns=s({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:Tn().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),Ps=s({error:u(),error_description:u().optional(),error_uri:u().optional()}),Fs=X.optional().or(a(``).transform(()=>void 0)),Is=s({redirect_uris:n(X),token_endpoint_auth_method:u().optional(),grant_types:n(u()).optional(),response_types:n(u()).optional(),client_name:u().optional(),client_uri:X.optional(),logo_uri:Fs,scope:u().optional(),contacts:n(u()).optional(),tos_uri:Fs,policy_uri:u().optional(),jwks_uri:X.optional(),jwks:ee().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Ls=s({client_id:u(),client_secret:u().optional(),client_id_issued_at:g().optional(),client_secret_expires_at:g().optional()}).strip(),Rs=Is.merge(Ls);s({error:u(),error_description:u().optional()}).strip(),s({token:u(),token_type_hint:u().optional()}).strip();function zs(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Bs({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Z=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Vs=class extends Z{};Vs.errorCode=`invalid_request`;var Hs=class extends Z{};Hs.errorCode=`invalid_client`;var Us=class extends Z{};Us.errorCode=`invalid_grant`;var Ws=class extends Z{};Ws.errorCode=`unauthorized_client`;var Gs=class extends Z{};Gs.errorCode=`unsupported_grant_type`;var Ks=class extends Z{};Ks.errorCode=`invalid_scope`;var qs=class extends Z{};qs.errorCode=`access_denied`;var Js=class extends Z{};Js.errorCode=`server_error`;var Ys=class extends Z{};Ys.errorCode=`temporarily_unavailable`;var Xs=class extends Z{};Xs.errorCode=`unsupported_response_type`;var Zs=class extends Z{};Zs.errorCode=`unsupported_token_type`;var Qs=class extends Z{};Qs.errorCode=`invalid_token`;var $s=class extends Z{};$s.errorCode=`method_not_allowed`;var ec=class extends Z{};ec.errorCode=`too_many_requests`;var tc=class extends Z{};tc.errorCode=`invalid_client_metadata`;var nc=class extends Z{};nc.errorCode=`insufficient_scope`;var rc=class extends Z{};rc.errorCode=`invalid_target`;const ic={[Vs.errorCode]:Vs,[Hs.errorCode]:Hs,[Us.errorCode]:Us,[Ws.errorCode]:Ws,[Gs.errorCode]:Gs,[Ks.errorCode]:Ks,[qs.errorCode]:qs,[Js.errorCode]:Js,[Ys.errorCode]:Ys,[Xs.errorCode]:Xs,[Zs.errorCode]:Zs,[Qs.errorCode]:Qs,[$s.errorCode]:$s,[ec.errorCode]:ec,[tc.errorCode]:tc,[nc.errorCode]:nc,[rc.errorCode]:rc};var ac=class extends Error{constructor(e){super(e??`Unauthorized`)}};function oc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const sc=`code`,cc=`S256`;function lc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&oc(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 uc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:dc(i,a,n);return;case`client_secret_post`:fc(i,a,r);return;case`none`:pc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function dc(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 fc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function pc(e,t){t.set(`client_id`,e)}async function mc(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(ic[e]||Js)(t||``,r)}catch(e){return new Js(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function hc(e,t){try{return await gc(e,t)}catch(n){if(n instanceof Hs||n instanceof Ws)return await e.invalidateCredentials?.(`all`),await gc(e,t);if(n instanceof Us)return await e.invalidateCredentials?.(`tokens`),await gc(e,t);throw n}}async function gc(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 xc(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 kc(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 vc(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&&!_c(r))throw new tc(`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 Pc(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 Nc(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof Z)||e instanceof Js))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await Ac(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function _c(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function vc(e,t,n){let r=zs(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Bs({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function yc(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=bc(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=bc(e,`scope`)||void 0,s=bc(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function bc(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 xc(e,t,n=fetch){let r=await Ec(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 As.parse(await r.json())}async function Sc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Sc(e,void 0,n):void 0;throw r}}function Cc(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function wc(e,t,n=fetch){return await Sc(e,{"MCP-Protocol-Version":t},n)}function Tc(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Ec(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=Cc(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await wc(o,a,n);return!r?.metadataUrl&&Tc(s,i.pathname)&&(s=await wc(new URL(`/.well-known/${t}`,i),a,n)),s}function Dc(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=ye}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=Dc(e);for(let{url:e,type:n}of i){let i=await Sc(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`?js.parse(await i.json()):Ms.parse(await i.json())}}}async function kc(e,t){let n,r;try{n=await xc(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 Ac(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(sc))throw Error(`Incompatible auth server: does not support response type ${sc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cc))throw Error(`Incompatible auth server: does not support code challenge method ${cc}`)}else s=new URL(`/authorize`,e);let c=await ks(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,sc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,cc),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 jc(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Mc(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&&uc(lc(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 mc(l);return Ns.parse(await l.json())}async function Nc(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Mc(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function Pc(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=jc(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return Mc(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 mc(o);return Rs.parse(await o.json())}var Ic=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 Lc(e){}function Rc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Lc,onError:n=Lc,onRetry:r=Lc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=zc(`${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}
|
|
64
|
+
`}var gs=class{constructor(e=nn.stdin,t=nn.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ps,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=hs(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function _s(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 vs(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 ys(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 bs(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 xs(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 Ss(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Cs(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Ss(t.headers),...Ss(r.headers)}:t.headers}):e}let ws;ws=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Ts(e){return(await ws).getRandomValues(new Uint8Array(e))}async function Es(e){let t=``;for(;t.length<e;){let n=await Ts(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Ds(e){return await Es(e)}async function Os(e){let t=await(await ws).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ks(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ds(e);return{code_verifier:t,code_challenge:await Os(t)}}const X=_().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Cn.custom,message:`URL must be parseable`,fatal:!0}),S}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),As=v({resource:n().url(),authorization_servers:u(X).optional(),jwks_uri:n().url().optional(),scopes_supported:u(n()).optional(),bearer_methods_supported:u(n()).optional(),resource_signing_alg_values_supported:u(n()).optional(),resource_name:n().optional(),resource_documentation:n().optional(),resource_policy_uri:n().url().optional(),resource_tos_uri:n().url().optional(),tls_client_certificate_bound_access_tokens:i().optional(),authorization_details_types_supported:u(n()).optional(),dpop_signing_alg_values_supported:u(n()).optional(),dpop_bound_access_tokens_required:i().optional()}),js=v({issuer:n(),authorization_endpoint:X,token_endpoint:X,registration_endpoint:X.optional(),scopes_supported:u(n()).optional(),response_types_supported:u(n()),response_modes_supported:u(n()).optional(),grant_types_supported:u(n()).optional(),token_endpoint_auth_methods_supported:u(n()).optional(),token_endpoint_auth_signing_alg_values_supported:u(n()).optional(),service_documentation:X.optional(),revocation_endpoint:X.optional(),revocation_endpoint_auth_methods_supported:u(n()).optional(),revocation_endpoint_auth_signing_alg_values_supported:u(n()).optional(),introspection_endpoint:n().optional(),introspection_endpoint_auth_methods_supported:u(n()).optional(),introspection_endpoint_auth_signing_alg_values_supported:u(n()).optional(),code_challenge_methods_supported:u(n()).optional(),client_id_metadata_document_supported:i().optional()}),Ms=d({...v({issuer:n(),authorization_endpoint:X,token_endpoint:X,userinfo_endpoint:X.optional(),jwks_uri:X,registration_endpoint:X.optional(),scopes_supported:u(n()).optional(),response_types_supported:u(n()),response_modes_supported:u(n()).optional(),grant_types_supported:u(n()).optional(),acr_values_supported:u(n()).optional(),subject_types_supported:u(n()),id_token_signing_alg_values_supported:u(n()),id_token_encryption_alg_values_supported:u(n()).optional(),id_token_encryption_enc_values_supported:u(n()).optional(),userinfo_signing_alg_values_supported:u(n()).optional(),userinfo_encryption_alg_values_supported:u(n()).optional(),userinfo_encryption_enc_values_supported:u(n()).optional(),request_object_signing_alg_values_supported:u(n()).optional(),request_object_encryption_alg_values_supported:u(n()).optional(),request_object_encryption_enc_values_supported:u(n()).optional(),token_endpoint_auth_methods_supported:u(n()).optional(),token_endpoint_auth_signing_alg_values_supported:u(n()).optional(),display_values_supported:u(n()).optional(),claim_types_supported:u(n()).optional(),claims_supported:u(n()).optional(),service_documentation:n().optional(),claims_locales_supported:u(n()).optional(),ui_locales_supported:u(n()).optional(),claims_parameter_supported:i().optional(),request_parameter_supported:i().optional(),request_uri_parameter_supported:i().optional(),require_request_uri_registration:i().optional(),op_policy_uri:X.optional(),op_tos_uri:X.optional(),client_id_metadata_document_supported:i().optional()}).shape,...js.pick({code_challenge_methods_supported:!0}).shape}),Ns=d({access_token:n(),id_token:n().optional(),token_type:n(),expires_in:Tn().optional(),scope:n().optional(),refresh_token:n().optional()}).strip(),Ps=d({error:n(),error_description:n().optional(),error_uri:n().optional()}),Fs=X.optional().or(s(``).transform(()=>void 0)),Is=d({redirect_uris:u(X),token_endpoint_auth_method:n().optional(),grant_types:u(n()).optional(),response_types:u(n()).optional(),client_name:n().optional(),client_uri:X.optional(),logo_uri:Fs,scope:n().optional(),contacts:u(n()).optional(),tos_uri:Fs,policy_uri:n().optional(),jwks_uri:X.optional(),jwks:r().optional(),software_id:n().optional(),software_version:n().optional(),software_statement:n().optional()}).strip(),Ls=d({client_id:n(),client_secret:n().optional(),client_id_issued_at:o().optional(),client_secret_expires_at:o().optional()}).strip(),Rs=Is.merge(Ls);d({error:n(),error_description:n().optional()}).strip(),d({token:n(),token_type_hint:n().optional()}).strip();function zs(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Bs({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Z=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Vs=class extends Z{};Vs.errorCode=`invalid_request`;var Hs=class extends Z{};Hs.errorCode=`invalid_client`;var Us=class extends Z{};Us.errorCode=`invalid_grant`;var Ws=class extends Z{};Ws.errorCode=`unauthorized_client`;var Gs=class extends Z{};Gs.errorCode=`unsupported_grant_type`;var Ks=class extends Z{};Ks.errorCode=`invalid_scope`;var qs=class extends Z{};qs.errorCode=`access_denied`;var Js=class extends Z{};Js.errorCode=`server_error`;var Ys=class extends Z{};Ys.errorCode=`temporarily_unavailable`;var Xs=class extends Z{};Xs.errorCode=`unsupported_response_type`;var Zs=class extends Z{};Zs.errorCode=`unsupported_token_type`;var Qs=class extends Z{};Qs.errorCode=`invalid_token`;var $s=class extends Z{};$s.errorCode=`method_not_allowed`;var ec=class extends Z{};ec.errorCode=`too_many_requests`;var tc=class extends Z{};tc.errorCode=`invalid_client_metadata`;var nc=class extends Z{};nc.errorCode=`insufficient_scope`;var rc=class extends Z{};rc.errorCode=`invalid_target`;const ic={[Vs.errorCode]:Vs,[Hs.errorCode]:Hs,[Us.errorCode]:Us,[Ws.errorCode]:Ws,[Gs.errorCode]:Gs,[Ks.errorCode]:Ks,[qs.errorCode]:qs,[Js.errorCode]:Js,[Ys.errorCode]:Ys,[Xs.errorCode]:Xs,[Zs.errorCode]:Zs,[Qs.errorCode]:Qs,[$s.errorCode]:$s,[ec.errorCode]:ec,[tc.errorCode]:tc,[nc.errorCode]:nc,[rc.errorCode]:rc};var ac=class extends Error{constructor(e){super(e??`Unauthorized`)}};function oc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const sc=`code`,cc=`S256`;function lc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&oc(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 uc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:dc(i,a,n);return;case`client_secret_post`:fc(i,a,r);return;case`none`:pc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function dc(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 fc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function pc(e,t){t.set(`client_id`,e)}async function mc(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(ic[e]||Js)(t||``,r)}catch(e){return new Js(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function hc(e,t){try{return await gc(e,t)}catch(n){if(n instanceof Hs||n instanceof Ws)return await e.invalidateCredentials?.(`all`),await gc(e,t);if(n instanceof Us)return await e.invalidateCredentials?.(`tokens`),await gc(e,t);throw n}}async function gc(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 xc(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 kc(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 vc(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&&!_c(r))throw new tc(`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 Pc(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 Nc(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof Z)||e instanceof Js))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await Ac(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function _c(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function vc(e,t,n){let r=zs(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Bs({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function yc(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=bc(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=bc(e,`scope`)||void 0,s=bc(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function bc(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 xc(e,t,n=fetch){let r=await Ec(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 As.parse(await r.json())}async function Sc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Sc(e,void 0,n):void 0;throw r}}function Cc(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function wc(e,t,n=fetch){return await Sc(e,{"MCP-Protocol-Version":t},n)}function Tc(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Ec(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=Cc(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await wc(o,a,n);return!r?.metadataUrl&&Tc(s,i.pathname)&&(s=await wc(new URL(`/.well-known/${t}`,i),a,n)),s}function Dc(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=ye}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=Dc(e);for(let{url:e,type:n}of i){let i=await Sc(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`?js.parse(await i.json()):Ms.parse(await i.json())}}}async function kc(e,t){let n,r;try{n=await xc(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 Ac(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(sc))throw Error(`Incompatible auth server: does not support response type ${sc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cc))throw Error(`Incompatible auth server: does not support code challenge method ${cc}`)}else s=new URL(`/authorize`,e);let c=await ks(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,sc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,cc),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 jc(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Mc(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&&uc(lc(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 mc(l);return Ns.parse(await l.json())}async function Nc(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Mc(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function Pc(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=jc(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return Mc(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 mc(o);return Rs.parse(await o.json())}var Ic=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 Lc(e){}function Rc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Lc,onError:n=Lc,onRetry:r=Lc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=zc(`${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}
|
|
65
65
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ic(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Ic(`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(`
|
|
66
66
|
`)?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 zc(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
67
67
|
`,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]===`
|
|
68
|
-
`&&r++}}return[t,n]}var Bc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Rc({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 Hc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Uc=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=Cs(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Vc}async _authThenStart(){if(!this._authProvider)throw new ac(`No auth provider`);let e;try{e=await hc(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 ac;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=Ss(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 Hc(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 Bc({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=pe.parse(JSON.parse(e.data));xe(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 ac(`No auth provider`);if(await hc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new ac(`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 Hc(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=yc(o);if(this._resourceMetadataUrl=t,this._scope=n,await hc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new ac;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=yc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Hc(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await hc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new ac;return this.send(e)}}throw new Hc(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Je(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=>pe.parse(e)):[pe.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Hc(-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 Hc(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 Wc(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 Gc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Kc(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function qc(e,t){return`http://${Kc(e)}:${t}/mcp`}function Jc(e,t){return`ws://${Kc(e)}:${t}`}function Yc(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Xc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Zc(e){return P(e)?I(e,`utf-8`).trim():``}function Qc(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function $c(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function el(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function tl(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function nl(e){let t=e.readLock??(()=>p(e.lockDir)),n=e.isAlive??_,r=e.sleep??(e=>_n(e)),i=e.spawn??M,a=e.readErrorLog??Zc,o=e.openErrorLog??(e=>Kt(e,`w`)),s=e.closeFd??Vt,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 qc(`localhost`,t)}let u=Xc(t(),n);if(u!==void 0)return qc(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||F(e.lockDir,{recursive:!0});let d=z(e.lockDir,S),f=o(d),m,h,g=It();try{try{m=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`}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(h){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}await r(l);let e=Xc(t(),n);if(e!==void 0)return qc(`localhost`,e)}if(h){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}throw Error(Qc(c,a(d)))}function rl(e,t){if(e.portOverride!==void 0)return Yc(t);let n=e.readLock??(()=>p(e.lockDir)),r=e.isAlive??_,i=Xc(n(),r);if(i!==void 0)return Jc(`localhost`,i)}async function il(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new gs(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new Uc(new URL(e),{fetch:Wc(r),requestInit:{headers:{...f({kind:`mcp`,runtimeVersion:h}),...t.connectionId===void 0?{}:{[me]: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=$c(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(tl(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=el(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function al(e){let t=e.stderr??process.stderr,n=e.bridgeFn??il,r=await nl(e),i=e.createConnectionId?.()??gn(),a=!1,o=(e.startKeepalive??fs)({connectionId:i,resolveWsUrl:async()=>rl(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 ol=pn(import.meta.url);function sl(e){let t=B(e);for(;;){if(Ue(t))return t;let n=$t(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 \`${r}\`).`);t=n}}function cl(e){try{let t=new URL(e);return t.protocol===`file:`?pn(t):void 0}catch{return}}async function ll(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=cl(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function ul(e,t){if(e!==void 0)return sl(e);let n=await t();if(n!==void 0)return sl(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 dl(e){let t=process.stderr,n=e.spawnTimeoutMs??Gc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=At({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new le({name:_e,version:h},{instructions:se({dir:`.`})});ue(a);let o=gn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=be(e),r=s.current,i=fs({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>rl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>ll({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>ul(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=sl(e)}else t=sl(e);let a=await i(t),o=await nl({lockDir:be(t),contentDir:ge(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=ve(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},ce(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new gs,m=!1,g,_,v=async()=>{if(m)return;m=!0,g?.stop(),_?.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)
|
|
68
|
+
`&&r++}}return[t,n]}var Bc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Rc({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 Hc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Uc=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=Cs(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Vc}async _authThenStart(){if(!this._authProvider)throw new ac(`No auth provider`);let e;try{e=await hc(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 ac;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=Ss(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 Hc(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 Bc({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=pe.parse(JSON.parse(e.data));xe(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 ac(`No auth provider`);if(await hc(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new ac(`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 Hc(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=yc(o);if(this._resourceMetadataUrl=t,this._scope=n,await hc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new ac;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=yc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Hc(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await hc(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new ac;return this.send(e)}}throw new Hc(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Je(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=>pe.parse(e)):[pe.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Hc(-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 Hc(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 Wc(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 Gc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Kc(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function qc(e,t){return`http://${Kc(e)}:${t}/mcp`}function Jc(e,t){return`ws://${Kc(e)}:${t}`}function Yc(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Xc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Zc(e){return P(e)?I(e,`utf-8`).trim():``}function Qc(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function $c(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function el(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function tl(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function nl(e){let t=e.readLock??(()=>m(e.lockDir)),n=e.isAlive??y,r=e.sleep??(e=>_n(e)),i=e.spawn??M,a=e.readErrorLog??Zc,o=e.openErrorLog??(e=>Kt(e,`w`)),s=e.closeFd??Vt,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 qc(`localhost`,t)}let u=Xc(t(),n);if(u!==void 0)return qc(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||F(e.lockDir,{recursive:!0});let d=z(e.lockDir,ee),f=o(d),p,h,g=It();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=Xc(t(),n);if(e!==void 0)return qc(`localhost`,e)}if(h){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${h}${t}`)}throw Error(Qc(c,a(d)))}function rl(e,t){if(e.portOverride!==void 0)return Yc(t);let n=e.readLock??(()=>m(e.lockDir)),r=e.isAlive??y,i=Xc(n(),r);if(i!==void 0)return Jc(`localhost`,i)}async function il(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new gs(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new Uc(new URL(e),{fetch:Wc(r),requestInit:{headers:{...x({kind:`mcp`,runtimeVersion:g}),...t.connectionId===void 0?{}:{[me]: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=$c(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(tl(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=el(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function al(e){let t=e.stderr??process.stderr,n=e.bridgeFn??il,r=await nl(e),i=e.createConnectionId?.()??gn(),a=!1,o=(e.startKeepalive??fs)({connectionId:i,resolveWsUrl:async()=>rl(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 ol=pn(import.meta.url);function sl(e){let t=B(e);for(;;){if(Ue(t))return t;let n=$t(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 \`${b}\`).`);t=n}}function cl(e){try{let t=new URL(e);return t.protocol===`file:`?pn(t):void 0}catch{return}}async function ll(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=cl(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function ul(e,t){if(e!==void 0)return sl(e);let n=await t();if(n!==void 0)return sl(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 dl(e){let t=process.stderr,n=e.spawnTimeoutMs??Gc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=At({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new le({name:_e,version:g},{instructions:se({dir:`.`})});ue(a);let o=gn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=be(e),r=s.current,i=fs({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>rl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>ll({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>ul(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=sl(e)}else t=sl(e);let a=await i(t),o=await nl({lockDir:be(t),contentDir:ge(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=ve(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},ce(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new gs,m=!1,h,_,v=async()=>{if(m)return;m=!0,h?.stop(),_?.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)
|
|
69
69
|
`);let y=!1,b=()=>{y||(y=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
70
70
|
`),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
|
|
71
|
-
`),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),_=bs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),xs({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=ys(ol,{realpathSync:Jt,statInoSync:e=>Xt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${
|
|
71
|
+
`),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),_=bs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),xs({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=ys(ol,{realpathSync:Jt,statInoSync:e=>Xt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${g}\n`);let{resolvedPath:n,inode:r}=e;h=vs({detect:()=>_s({bundleAnchorPath:ol,currentInode:r,platform:process.platform,realpath:Jt,statInode:e=>Xt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${g} — exiting for host respawn\n`),b()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:v}}function fl(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=Gc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await al({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=ls(process.env,i,process.platform);if(a.proxy){let e=cs(process.platform,on(),{existsSync:P});if(e===null)us({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await ds({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){us({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`;us({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await dl({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 pl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function ml(e=()=>Ft(Nt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>Ye({lockDir:w(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:pl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function hl(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Ae(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}/#/${Ke(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 gl(){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=hl(e,t,ml())})}function _l(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-DaXp5otx.mjs`),r=e(),i=process.cwd(),a=ge(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 vl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function yl(e,t,n=process.cwd()){let r=e.op??`sync`,i=m(w(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...x({kind:`cli`,runtimeVersion:g})},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}`)}vl(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=ie({baseDir:n});if(r===`sync`||r===`pull`){vl(e.json,{type:`step`,step:`pull`});let t=await a.pull();vl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(vl(e.json,{type:`step`,step:`push`}),await a.push(),vl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
72
72
|
`)),vl(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function bl(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 yl({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 xl(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await yl({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 Sl(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await yl({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 Cl(e){return typeof e==`string`&&Ee.includes(e)}async function wl(e={}){let t=B(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!we[n])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${n}". Available: ${Ee.join(`, `)}`,exitCode:1};let r;try{r=await Me({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof je?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=we[n].name;return{status:`no-op`,message:`${O(`Your ${e} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${j(`Plan (dry-run — no changes made):`)}\n\n${El(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await Dl(`${j(`Plan:`)}\n\n${El(r,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:r,exitCode:0};let i=await Ve(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${i.applied} entries, ${A(String(i.errors.length))} error(s):`,...e].join(`
|
|
73
73
|
`),plan:r,exitCode:1}}let a=we[n].name,o=i.packSkillsInstalled.length>0?`\n${D(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${O(`✓ Seeded ${a}`)} ${D(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function Tl(){let e=[j(`Available packs:`)];for(let t of Ee){let n=we[t];e.push(` ${O(t)} ${D(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
|
74
74
|
`)}function El(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(j(`Folders to create:`));for(let e of r)n.push(` ${O(`+`)} ${E(en(t,B(t,e.path))||e.path)}${D(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(j(`Files to create:`));for(let e of i)n.push(` ${O(`+`)} ${E(en(t,B(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(D(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${D(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(A(`Warnings:`));for(let t of e.warnings)n.push(` ${A(`!`)} ${t}`)}return n.join(`
|
|
@@ -77,7 +77,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
|
|
|
77
77
|
`);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 jl(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 Al(t,await e())})}async function Ml(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 Nl(e,t){let{host:n,json:r}=e;H(n);let i=await Ei(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 Ml(new K({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function Pl(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 Nl(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(`
|
|
78
78
|
`)??``}\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 Il(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 Ll(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 Rl(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function zl(e){return ie({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function Bl(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=>{he(e)},gitFactory:zl};async function Hl(e){let t={...Vl,...e.deps},n=B(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await Rl(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(!P(z(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await Il({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 Ll(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=Bl(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 Ul(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 Wl(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;H(n);let l=await Ei(n,t);if(l==null){Ul(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new K({auth:l,...u?{baseUrl:u}:{}});try{zt(`git config user.email`,{cwd:s,stdio:`ignore`})}catch{process.env.GIT_AUTHOR_NAME??=`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`}Ul(c,await Hl({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function Gl(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'
|
|
79
79
|
`),process.exit(1)),await Wl(t,await e())})}function Kl(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>ne();return e.addCommand(Pl(n)),e.addCommand(jl(n)),e.addCommand(Gl(n)),e}function ql(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=dt(t),r=tt(t,et(t));if(r.kind===`no-exclude`){Jl(e.json,t,r.reason);return}let i=dt(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${E(`Sharing mode is already`)} ${j(`shared`)} ${E(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${j(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function Jl(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Yl(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=dt(t),r=[...ut(t)],i=gt(t,et(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: ${Xl(n)}`),a.push(``),a.push(`Excluded from git via ${j(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${E(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
|
|
80
|
-
`)}\n`)})}function Xl(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function Zl(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=pt(t,et(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`){Ql(e.json,t,n.reason);return}let r=dt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Ql(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function $l(){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(ql()),e.addCommand(Zl()),e.addCommand(Yl()),e}const eu=new Set([`--cwd`,`--log-level`]);function tu(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){eu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function nu(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ru(e){return/\.(md|mdx)$/i.test(e)}function iu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function au(e=()=>Ft(Nt())){return{prepare:Be,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:iu(process.env)}).unref()},runProjectOpen:(e,t)=>hl(e,{project:t},ml()),runBrowserOpen:e=>cu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function ou(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ge||e instanceof ze||e instanceof Ie)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function su(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function cu(e){let{createEphemeralProjectDir:t}=await import(`./dist-
|
|
80
|
+
`)}\n`)})}function Xl(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function Zl(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=pt(t,et(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`){Ql(e.json,t,n.reason);return}let r=dt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Ql(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function $l(){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(ql()),e.addCommand(Zl()),e.addCommand(Yl()),e}const eu=new Set([`--cwd`,`--log-level`]);function tu(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){eu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function nu(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ru(e){return/\.(md|mdx)$/i.test(e)}function iu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function au(e=()=>Ft(Nt())){return{prepare:Be,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:iu(process.env)}).unref()},runProjectOpen:(e,t)=>hl(e,{project:t},ml()),runBrowserOpen:e=>cu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function ou(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ge||e instanceof ze||e instanceof Ie)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function su(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function cu(e){let{createEphemeralProjectDir:t}=await import(`./dist-C3GEAWC-.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-DqcllJQs.mjs`),{openBrowser:a}=await import(`./open-browser-C6LU_1mt.mjs`),o=su();o||(process.stderr.write("Open Knowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await mn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Ke(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
|
|
81
81
|
`),a(m),await new Promise(()=>{})}function lu(e,t){return{server:uu(`server`,e),ui:uu(`ui`,t)}}function uu(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 du(e){return`${fu(e.server)}\n${fu(e.ui)}`}function fu(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 pu(e){let t=e.inspect??(t=>bt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=lu(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(du(r)),r}function mu(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(),pu({lockDir:w(process.cwd()),json:t.json===!0})})}function hu(e){return[e,`Copyright (C) 2026 Inkeep, Inc.`,`License GPL-3.0-or-later: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.`,`This is free software: you are free to change and redistribute it.`,`There is NO WARRANTY, to the extent permitted by law.`].join(`
|
|
82
82
|
`)}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $,gu;function _u(){return gu}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(hu(Dt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=wt(n,process.cwd());r!==null&&(vt(process.cwd()),process.chdir(r),console.error(`[ok] Using Open Knowledge project at ${r}`));let{config:i}=kt(r??t);$=i;let a=e.args?.[0]??e.name()??`cli`;gu=We({name:`cli`,project:i.project?.name??void 0}),gu.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Ft(Nt()).available){jt({spawn:M});return}await Pt($,{})});const vu=Mt(()=>$);Q.addCommand(vu);const yu=fl(()=>$);Q.addCommand(yu),Q.addCommand(mt()),Q.addCommand(Ol()),Q.addCommand(as()),Q.addCommand(Rt());const bu=_l(()=>$);Q.addCommand(bu);const xu=ht(()=>$);Q.addCommand(xu),Q.addCommand(gl()),Q.addCommand(xt(()=>$)),Q.addCommand(Xi(()=>$)),Q.addCommand(mu(()=>$)),Q.addCommand(Tt()),Q.addCommand(Ho()),Q.addCommand(qi()),Q.addCommand(ha()),Q.addCommand(Fi(_u)),Q.addCommand(Zo()),Q.addCommand(sa(()=>$)),Q.addCommand(bl(()=>$)),Q.addCommand(Sl(()=>$)),Q.addCommand(xl(()=>$)),Q.addCommand(Kl()),Q.addCommand($l()),Q.addHelpText(`after`,`
|
|
83
83
|
Examples:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hr as e,Kr as t,Rt as n,Sr as r,_n as i,a,bn as o,c as s,d as c,en as l,f as u,g as d,h as f,i as p,in as m,l as h,m as g,n as _,o as v,p as y,q as b,r as x,s as S,t as C,u as w}from"./server-lock-BpjJj3OD-Dw5FXP_d.mjs";import{$ as T,$n as E,$r as D,$t as O,A as k,Ai as A,An as j,Ar as M,At as N,B as P,Bn as F,Br as I,Bt as L,C as R,Ci as z,Cn as B,Cr as V,Ct as H,D as U,Di as W,Dn as G,Dr as K,Dt as q,E as J,Ei as Y,En as X,Er as Z,Et as Q,F as $,Fi as ee,Fn as te,Fr as ne,Ft as re,G as ie,Gn as ae,Gr as oe,Gt as se,H as ce,Hn as le,Hr as ue,Ht as de,I as fe,In as pe,Ir as me,It as he,J as ge,Ji as _e,Jn as ve,Jr as ye,Jt as be,K as xe,Kn as Se,Kr as Ce,Kt as we,L as Te,Ln as Ee,Lr as De,Lt as Oe,M as ke,Mi as Ae,Mn as je,Mr as Me,Mt as Ne,N as Pe,Ni as Fe,Nn as Ie,Nr as Le,Nt as Re,O as ze,Oi as Be,On as Ve,Or as He,Ot as Ue,P as We,Pi as Ge,Pn as Ke,Pr as qe,Pt as Je,Q as Ye,Qn as Xe,Qr as Ze,Qt as Qe,R as $e,Rn as et,Rr as tt,Rt as nt,S as rt,Si as it,Sn as at,Sr as ot,St as st,T as ct,Ti as lt,Tn as ut,Tr as dt,Tt as ft,U as pt,Un as mt,Ur as ht,Ut as gt,V as _t,Vn as vt,Vr as yt,Vt as bt,W as xt,Wn as St,Wr as Ct,Wt as wt,X as Tt,Xn as Et,Xr as Dt,Xt as Ot,Y as kt,Yn as At,Yr as jt,Yt as Mt,Z as Nt,Zn as Pt,Zr as Ft,Zt as It,_ as Lt,_i as Rt,_n as zt,_r as Bt,_t as Vt,a as Ht,ai as Ut,an as Wt,ar as Gt,at as Kt,b as qt,bi as Jt,bn as Yt,br as Xt,bt as Zt,c as Qt,ci as $t,cn as en,cr as tn,ct as nn,d as rn,di as an,dn as on,dr as sn,dt as cn,ei as ln,en as un,er as dn,et as fn,f as pn,fi as mn,fn as hn,fr as gn,ft as _n,g as vn,gi as yn,gn as bn,gr as xn,gt as Sn,h as Cn,hi as wn,hn as Tn,hr as En,ht as Dn,i as On,ii as kn,in as An,ir as jn,it as Mn,j as Nn,ji as Pn,jn as Fn,jr as In,jt as Ln,k as Rn,ki as zn,kn as Bn,kr as Vn,kt as Hn,l as Un,li as Wn,ln as Gn,lr as Kn,lt as qn,m as Jn,mi as Yn,mn as Xn,mr as Zn,mt as Qn,n as $n,ni as er,nn as tr,nr,nt as rr,o as ir,oi as ar,on as or,or as sr,ot as cr,p as lr,pi as ur,pn as dr,pr as fr,pt as pr,q as mr,qi as hr,qn as gr,qr as _r,qt as vr,r as yr,ri as br,rn as xr,rr as Sr,rt as Cr,s as wr,si as Tr,sn as Er,sr as Dr,st as Or,t as kr,ti as Ar,tn as jr,tr as Mr,tt as Nr,u as Pr,ui as Fr,un as Ir,ur as Lr,ut as Rr,v as zr,vi as Br,vn as Vr,vr as Hr,vt as Ur,w as Wr,wi as Gr,wn as Kr,wr as qr,wt as Jr,x as Yr,xi as Xr,xn as Zr,xr as Qr,xt as $r,y as ei,yi as ti,yn as ni,yr as ri,yt as ii,z as ai,zn as oi,zr as si,zt as ci}from"./dist-DE6um5_s.mjs";export{kr as AGENT_ID_MAX_LEN,$n as AGENT_ID_RE,yr as AGENT_WRITE_ORIGIN,On as AgentFocusBroadcaster,Ht as AgentPresenceBroadcaster,ir as AgentSessionCapacityError,wr as AgentSessionManager,Qt as BacklinkIndex,Un as CC1Broadcaster,b as CC1_CONTRACT_VERSION,Pr as CONFIG_FILENAME,rn as CONFLICT_MARKER_RE,pn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,lr as ConfigSchema,Jn as DEFAULT_CHECKPOINT_RETENTION,Cn as DEFAULT_EMBEDDINGS_DIMENSIONS,vn as DEFAULT_PACK_ID,Lt as EMBEDDINGS_API_KEY_ENV,zr as FILE_SYSTEM_WRITER,ei as FILE_WATCHER_ORIGIN,qt as FileEmbeddingsBackend,Yr as GIT_PREFLIGHT_FAIL_SPAN_NAME,rt as GIT_UPSTREAM_WRITER,hr as GitDirAccessError,R as GitNotAvailableError,Wr as GitTooOldError,ct as HOCUSPOCUS_AUTH_REJECTION_REASONS,J as HocuspocusAuthRejection,U as HocuspocusAuthTokenSchema,ze as INSTALLED_AGENTS_SCHEMES,n as LINEAGE_EPOCH_KEY,Rn as LIVE_DERIVED_INDEX_DEBOUNCE_MS,k as LOG_MD_TEMPLATE,Nn as MANAGED_RENAME_ORIGIN,ke as MAX_AGENT_SESSIONS,Pe as MCP_CONNECTION_ID_HEADER,We as MCP_SERVER_NAME,$ as MIN_GIT_VERSION,fe as MISSING_OK_CONFIG_MESSAGE,_e as MalformedGitPointerError,Te as McpLogger,$e as MissingOkConfigError,ai as OBSERVER_SYNC_ORIGIN,P as OK_OKIGNORE_TEMPLATE,l as ORPHAN_MODES,_t as PANE_TARGET_TTL_MS,m as PROTOCOL_VERSION,ce as PinoLogger,C as ProcessLockCollisionError,pt as ProjectGitInitError,xt as ROLLBACK_ORIGIN,ie as ROOT_GITIGNORE_TEMPLATE,_ as RUNTIME_VERSION,xe as SERVICE_WRITER,mr as SKILL_INSTALL_EVENTS_FILE_REL,i as SKILL_STATE_TARGETS,ge as STARTER_FOLDERS,kt as STARTER_FOLDER_FRONTMATTER_FILENAME,Tt as STARTER_PACKS,Nt as STARTER_PACK_IDS,Ye as STARTER_TEMPLATES,T as STATE_MANIFEST_FILENAME,x as STATE_SCHEMA_VERSION,o as SYSTEM_DOC_NAME,fn as SeedPrerequisiteError,Nr as SeedRootDirError,p as ServerLockCollisionError,rr as SingleFileNotAFileError,Cr as SingleFileNotFoundError,Mn as SingleFileNotMarkdownError,Kt as StateManifestError,cr as TagIndex,Or as UiLockCollisionError,nn as __getShowAllWalkStatsForTesting,qn as __resetShowAllWalkStatsForTesting,a as acquireProcessLock,v as acquireServerLock,Rr as acquireUiLock,cn as applyAgentMarkdownWrite,_n as applyExternalChange,pr as applySeed,Qn as armPaneTarget,Dn as assertCompatibleStateManifest,Sn as assertGitAvailable,Vt as assertNeverDiskEvent,Ur as attachIdleShutdown,ii as bootServer,Zt as buildAndOpenSkill,$r as buildConfigYmlContent,st as buildExecResult,H as buildInstructions,Jr as buildSkillZip,ft as buildStarterFolderFrontmatterYaml,Q as buildWipTree,q as classifyEvents,Ue as classifyFsPath,Hn as clearArmedPaneTarget,N as clearContributors,Ln as clearEmbeddingsKeyFromAllBackends,Ne as coercePackId,r as colorFromSeed,Re as commitUpstreamImport,Je as commitWip,re as commitWipFromTree,he as compareSemver,Oe as containsConflictMarkers,nt as contentHash,ci as contributorCount,L as createApiExtension,bt as createAssetServeMiddleware,de as createContentFilter,gt as createContentFilterAsync,wt as createEmbeddingsSecretStore,se as createEphemeralProjectDir,we as createExternalChangeHandler,vr as createFileLogger,be as createLiveDerivedIndexExtension,Mt as createMcpHttpHandler,Ot as createOsProbe,It as createPersistenceExtension,Qe as createServer,O as createServerObserverExtension,un as createStreamingErrorWriter,jr as createTestLogger,tr as describeStoredEmbeddingsKey,xr as detectClaudeDesktopPresence,An as detectGit,Wt as detectProjectShape,or as emitPreflightFailureSpan,Er as encodeDocName,en as encodeFolderRoute,Gn as ensureProjectGit,Ir as errorResponse,on as evictStaleTrackerEntries,hn as extractWikiLinksFromMarkdown,dr as fallbackPaths,Xn as findEnclosingGitRoot,Tn as findEnclosingProjectRoot,bn as flushFileLogger,zt as formatAuthRejectionWire,Vr as formatContributors,ni as formatContributorsFrom,Yt as gcCheckpointRefs,Zr as getCurrentMcpLogger,at as getLocalDir,B as getLogFilePath,Kr as getLogger,ut as getLogsDir,X as getMeter,G as getMetrics,Ve as getTracer,Bn as handleCollabSocketError,j as handleSpawnCursor,e as iconFromClientName,Fn as incrementCollabSocketFilteredError,je as incrementServerObserverFire,Ie as initContent,Ke as initShadowRepo,te as initTelemetry,pe as installPrettyZodErrors,Ee as installTestLoggers,et as installUserSkill,oi as isAllowedApiOrigin,F as isAllowedWorkspaceHostHeader,vt as isConfigDoc,le as isHocuspocusAuthRejectionReason,mt as isKnownPackId,St as isLoopbackAddress,t as isOrphanMode,ae as isPairedWriteOrigin,Se as isPathWithinDir,S as isProcessAlive,gr as isProjectRoot,ve as isSelfWrite,At as isSystemDoc,s as isValidLockPid,Et as lastKnownHash,Pt as listRescueCheckpoints,Xe as listStarterPacks,E as loadPrincipal,h as lockFilePath,dn as loggerFactory,Mr as logsCurrentPath,nr as logsPreviousPath,Sr as makeLazyEmbeddingsKeyStore,jn as mountMcpAndApi,Gt as normalizeFsPath,sr as packageVersionMajorMinor,Dr as parseAuthRejectionWire,tn as parseGitVersion,Kn as parseHocuspocusAuthToken,Lr as parseKeepaliveConnectionId,sn as pathToDocName,gn as planSeed,fr as prepareSingleFileOpen,Zn as readAllTargets,En as readArmedPaneTarget,xn as readBranchFromHead,w as readProcessLock,c as readProcessLockDetailed,Bt as readProjectLocalSemanticConfig,u as readServerLock,Hr as readServerPackageVersion,ri as readSkillInstallStateSnapshot,Xt as readStateManifest,Qr as readTargetRecordedAt,ot as readTargetVersion,V as readUiLock,qr as reconcile,dt as recordContributor,Z as recordSkillInstallEvent,K as registerAllTools,He as registerWrite,y as releaseProcessLock,g as releaseServerLock,Vn as releaseUiLock,M as removeLastKnownHash,In as resetMetrics,Me as resolveBundledSkillDir,Le as resolveContentDir,qe as resolveCursorBinaryDefault,ne as resolveCursorSpawnInvocation,me as resolveLockDir,De as resolvePack,tt as resolvePackageVersion,si as resolveUiInfo,I as restoreContributors,yt as restoreLifecycleFromConflictsJson,ue as rewriteMarkdownLinksForDocumentRename,ht as rewriteWikiLinksForDocumentRename,Ct as runAuthReposSubprocess,oe as runAuthStatusSubprocess,Ce as runCloneSubprocess,_r as runDeviceFlowSubprocess,ye as runWithMcpLogger,jt as safeContentPath,Dt as safeSubdir,Ft as safetyCheckpoint,Ze as sanitizeClientName,D as saveInMemoryCheckpoint,ln as saveVersion,Ar as seedBasenameIndex,er as serializeError,br as setActiveSpanAttributes,kn as shadowGit,Ut as shutdownTelemetry,ar as spansCurrentPath,Tr as spansPreviousPath,$t as spawnDetached,Wn as splitMarkdownBlocks,Fr as startWatcher,an as streamingProblemEvent,mn as swapContributors,ur as toBroadcasterKey,Yn as tracedAppendFileSync,wn as tracedLinkSync,yn as tracedMkdir,Rt as tracedMkdirSync,Br as tracedRename,ti as tracedRenameSync,Jt as tracedRmSync,Xr as tracedRmdirSync,it as tracedUnlinkSync,z as tracedWriteFile,Gr as tracedWriteFileSync,lt as updateLastKnownHash,f as updateProcessLockPort,d as updateServerLockPort,Y as updateUiLockPort,W as validateAgentId,Be as validateCloneInputs,zn as validateSkillZip,A as withSpan,Pn as withSpanSync,Ae as writeRootGitignoreForNewRepo,Fe as writeStateManifest,Ge as writeTargetVersion,ee as writeTracker};
|