@inkeep/open-knowledge 0.10.0-beta.10 → 0.10.0-beta.11
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/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +5 -5
- package/dist/constants-D2G_Eavq.mjs +2 -0
- package/dist/{dist-Dvjp8LvP.mjs → dist-B8NhyNC8.mjs} +1 -1
- package/dist/{dist-2T4GwdDL.mjs → dist-Brl9qSX0.mjs} +3 -3
- package/dist/index.mjs +1 -1
- package/dist/{init-DlaoEXBr.mjs → init-0N2lo0hi.mjs} +4 -4
- package/dist/init-D8vPZw0o.mjs +1 -0
- package/dist/{loader-C4VPi9d_.mjs → loader--s6S-YxQ.mjs} +2 -2
- package/dist/loader-7gwzhh4P.mjs +1 -0
- package/dist/{preview-zRqBPqrO.mjs → preview-CDnEY-5-.mjs} +2 -2
- package/dist/preview-DBrgAN_w.mjs +1 -0
- package/dist/{repair-launch-json-CDDb3KUo.mjs → repair-launch-json-CX_MC3Em.mjs} +2 -2
- package/dist/{repair-mcp-configs-BRGcJS3C.mjs → repair-mcp-configs-AiD49bhk.mjs} +2 -2
- package/dist/{repair-skills-D6H2pCdZ.mjs → repair-skills-B0pnRk21.mjs} +2 -2
- package/dist/repair-skills-DE_jE4cd.mjs +1 -0
- package/dist/{src-Daa-0xy9.mjs → src-XiyRbsJ3.mjs} +2 -2
- package/dist/start-CfCut49X.mjs +1 -0
- package/dist/{start-B_7A6Tzo.mjs → start-IJJCSahA.mjs} +2 -2
- package/dist/{write-project-skill-ClsrSTUT.mjs → write-project-skill-BA-FwLDS.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BvbCi0i6.mjs +0 -2
- package/dist/init-CVlHYzW5.mjs +0 -1
- package/dist/loader-DbmtQhQv.mjs +0 -1
- package/dist/preview-Dt8CrVXL.mjs +0 -1
- package/dist/repair-skills-DFYi31tf.mjs +0 -1
- package/dist/start-DBND1J40.mjs +0 -1
|
@@ -3,7 +3,7 @@ name: open-knowledge-discovery
|
|
|
3
3
|
description: "Read when the user asks what Open Knowledge is, wants to install it on a repository, wants to share an Open Knowledge project with collaborators, or asks how `ok init` / `ok install-skill` / OK Desktop set up a project. Do NOT load to perform Open Knowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs. If the user appears to be editing markdown inside a `.ok/` project and this is the only OK skill loaded, advise them to re-run `ok init` to install the project-local skill."
|
|
4
4
|
compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
|
|
5
5
|
metadata:
|
|
6
|
-
version: "0.10.0-beta.
|
|
6
|
+
version: "0.10.0-beta.11"
|
|
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.10.0-beta.
|
|
6
|
+
version: "0.10.0-beta.11"
|
|
7
7
|
author: "Inkeep"
|
|
8
8
|
repository: "https://github.com/inkeep/open-knowledge"
|
|
9
9
|
---
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Bi as n,Ci as r,Cr as i,Fi as a,Gi as o,Gr as s,Ji as c,Ki as l,Oi as u,Qi as d,Sn as f,Vi as p,f as m,ia as h,n as g,qi as _,s as v,ta as y,va as b,wi as x,ya as S,zi as ee}from"./server-lock-BpjJj3OD-ATm9AAM0.mjs";import{a as te,n as C,r as ne,t as re}from"./gh-detect-D4VxJyjK.mjs";import{n as ie,r as ae,t as w}from"./dist-bundle-BK4P1EQn.mjs";import{B as oe,C as se,E as ce,F as le,H as ue,I as de,L as fe,M as pe,N as me,P as he,R as ge,S as _e,T as ve,V as ye,b as be,u as xe,v as Se,w as Ce,z as we}from"./init-
|
|
2
|
+
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Bi as n,Ci as r,Cr as i,Fi as a,Gi as o,Gr as s,Ji as c,Ki as l,Oi as u,Qi as d,Sn as f,Vi as p,f as m,ia as h,n as g,qi as _,s as v,ta as y,va as b,wi as x,ya as S,zi as ee}from"./server-lock-BpjJj3OD-ATm9AAM0.mjs";import{a as te,n as C,r as ne,t as re}from"./gh-detect-D4VxJyjK.mjs";import{n as ie,r as ae,t as w}from"./dist-bundle-BK4P1EQn.mjs";import{B as oe,C as se,E as ce,F as le,H as ue,I as de,L as fe,M as pe,N as me,P as he,R as ge,S as _e,T as ve,V as ye,b as be,u as xe,v as Se,w as Ce,z as we}from"./init-0N2lo0hi.mjs";import{r as Te}from"./git-handle-BSAUg1L_-Bn2h-fYS.mjs";import{$ as Ee,A as De,Ai as Oe,Ar as ke,Bn as Ae,Di as je,Dr as Me,En as Ne,Fi as Pe,Ht as Fe,J as Ie,Li as Le,Mi as Re,Oi as ze,Ri as Be,Ur as Ve,Vi as He,Z as Ue,_t as We,ar as Ge,b as Ke,bt as qe,et as Je,h as Ye,hn as Xe,ir as Ze,j as Qe,ji as $e,ki as et,kn as tt,nn as nt,pt as rt,q as it,tn as at,tt as ot,ut as st,vr as ct,wr as lt,x as ut,zi as dt}from"./dist-Brl9qSX0.mjs";import{t as ft}from"./yazl-DjRp4wSy.mjs";import{a as pt,c as mt,f as ht,i as gt,o as _t,p as vt,s as yt}from"./src-XiyRbsJ3.mjs";import{n as bt,t as xt}from"./constants-D2G_Eavq.mjs";import{n as St,t as Ct}from"./loader--s6S-YxQ.mjs";import{_ as wt,b as Tt,f as Et,h as Dt,v as Ot,y as kt}from"./start-IJJCSahA.mjs";import{c as At,i as T,n as E,o as D,r as O,s as k,t as A}from"./colors-BtKMHmBX.mjs";import{n as jt}from"./repair-skills-B0pnRk21.mjs";import{execSync as Mt,spawn as j,spawnSync as M}from"node:child_process";import{accessSync as Nt,closeSync as Pt,constants as Ft,cpSync as It,createWriteStream as Lt,existsSync as N,mkdirSync as P,mkdtempSync as Rt,openSync as zt,readFileSync as F,readdirSync as Bt,realpathSync as Vt,rmSync as Ht,statSync as Ut,unlinkSync as Wt,writeFileSync as I}from"node:fs";import Gt,{basename as L,dirname as Kt,join as R,relative as qt,resolve as z,sep as Jt}from"node:path";import Yt from"node:process";import{arch as Xt,freemem as Zt,homedir as Qt,platform as $t,release as en,tmpdir as tn,totalmem as nn,type as rn,uptime as an}from"node:os";import{fileURLToPath as on}from"node:url";import{AsyncLocalStorage as sn,AsyncResource as cn}from"node:async_hooks";import{stripVTControlCharacters as ln,styleText as B}from"node:util";import*as un from"node:readline";import{createHash as dn,randomUUID as fn}from"node:crypto";import{rm as pn}from"node:fs/promises";import{setTimeout as mn}from"node:timers/promises";import{createInterface as hn}from"node:readline/promises";async function gn(e,t,n){let r=_n(await vn(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function _n(e){let t={};for(let n of e.split(`
|
|
3
3
|
`)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function vn(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function yn(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await gn(process.stdin,process.stdout,t);process.exit(n)}),n}function bn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function xn(e,t,n){let r={baseUrl:bn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ie(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Sn(e){let t=e.request||w,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),xn(t,`POST /login/device/code`,n)}async function Cn(e){let t=await xn(e.request||w,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=wn(e,t.data.expires_in),n.refreshTokenExpiresAt=wn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function wn(e,t){return new Date(e+t*1e3).toISOString()}async function Tn(e,t){let n=En(e,t.auth);if(n)return n;let{data:r}=await Sn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await On(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function En(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 Dn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function On(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Cn({...i,clientType:`oauth-app`}):await Cn({...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 Dn(r.interval),On(e,t,n,r);if(a===`slow_down`)return await Dn(r.interval+7),On(e,t,n,r);throw i}}async function kn(e,t){return Tn(e,{auth:t})}async function An(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 Tn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var jn=`0.0.0-development`;function Mn(e){let t=e.request||w.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${jn} ${ae()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(kn.bind(null,i),{hook:An.bind(null,i)})}async function Nn(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=Mn({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-CjV1Pdeo.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}const Pn={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 Fn;(function(e){})(Fn||={});function In(e){return h(a,e)}function Ln(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Rn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function V(e){let t=e.toLowerCase().replace(/:\d+$/,``);Rn.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 zn(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Bn(e,t,n=Nn){let r=Ln(),{host:i,json:a}=e;V(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?zn(!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?zn(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function Vn(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 Bn(t,await e())})}const Hn=e=>e.name===`enter`||e.name===`return`;var Un=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Wn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Gn=class extends Error{name=`ExitPromptError`},Kn=class extends Error{name=`HookError`},qn=class extends Error{name=`ValidationError`};const Jn=new sn;function Yn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Xn(e,t){let n=Yn(e);return Jn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function H(){let e=Jn.getStore();if(!e)throw new Kn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Zn(){return H().rl}function Qn(e){return cn.bind((...t)=>{let n=H(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function $n(e){let t=H(),{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 er(){H().handleChange()}const tr={queue(e){let t=H(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Zn());if(r!=null&&typeof r!=`function`)throw new qn(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=H();Qn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=H();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function nr(e){return typeof e==`function`}function U(e){return $n(t=>{let n=cn.bind(function(e){t.get()!==e&&(t.set(e),er())});if(t.initialized)return[t.get(),n];let r=nr(e)?e():e;return t.set(r),[r,n]})}function rr(e,t){$n(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&tr.queue(e),n.set(t)})}const ir={prefix:{idle:B(`blue`,`?`),done:B(`green`,ue.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>B(`yellow`,e))},style:{answer:e=>B(`cyan`,e),message:e=>B(`bold`,e),error:e=>B(`red`,`> ${e}`),defaultAnswer:e=>B(`dim`,`(${e})`),help:e=>B(`dim`,e),highlight:e=>B(`cyan`,e),key:e=>B(`cyan`,B(`bold`,`<${e}>`))}};function ar(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 or(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ar(n)&&ar(r)?or(n,r):r}return t}function sr(...e){return or(ir,...e.filter(e=>e!=null))}function cr({status:e=`idle`,theme:t}){let[n,r]=U(!1),[i,a]=U(0),{prefix:o,spinner:s}=sr(t);return rr(()=>{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 lr(e){return U({current:e})[0]}function ur(e){let t=lr(e);t.current=e,rr(e=>{let n=!1,r=Qn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var dr=e(ye(),1);function fr(e,t){return e.split(`
|
|
4
4
|
`).flatMap(e=>oe(e,t,{trim:!1,hard:!0}).split(`
|
|
5
5
|
`).map(e=>e.trimEnd())).join(`
|
|
@@ -20,7 +20,7 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
|
|
|
20
20
|
`),patterns:[...t],lineCount:n}}const ji=R(Qt(),`.ok`,`logs`),Mi=R(Qt(),`.ok`,`bug-reports`);function Ni(e){let t=R(e,`.ok`,`config.yml`);if(N(t))try{let e=F(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return N(R(e,`.ok`))?dn(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function Pi(){let e={timestamp:new Date().toISOString(),platform:$t(),osType:rn(),osRelease:en(),hostname:`[redacted]`,uptime:an(),freeMem:Zt(),totalMem:nn(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Mt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);N(t)&&(e.okVersion=JSON.parse(F(t,`utf8`)).version)}catch{}return e}function Fi(e){if(!N(ji))return{files:[],dir:ji};let t=Bt(ji).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(ji,e));if(e&&t.length>0){let n=t.filter(t=>{try{return F(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:ji}}function Ii(e){let t=R(e,`.ok`,`local`);return N(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>R(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}function Li(e){let t=R(e,`.ok`,`local`,`logs`);return N(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}async function Ri(t){let n=$l();P(Mi,{recursive:!0});let r=R(Mi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Pi(),{files:a}=Fi(t.projectSlug),{files:o}=Ii(t.cwd),{files:s}=Li(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CJayzk0b.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Ai(F(e,`utf8`)),i=`logs/${L(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}=Ai(F(e,`utf8`)),i=`lockdir/${L(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}=Ai(F(e,`utf8`)),i=`local-logs/${L(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: ${ki.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
|
|
21
21
|
`);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Lt(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&&$t()===`darwin`)try{j(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function zi(){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=Ni(t);try{await Ri({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 Bi(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 Vi(e){let t=e.inspect??(t=>vt(e.lockDir,t)),n=e.unlink??(e=>Wt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Bi(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 Hi(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Vi({lockDir:Me(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function Ui(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 Wi(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 Gi=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ki(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 Gi)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function K(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function qi(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const Ji=s;async function Yi(e){try{return await e.clone(qi(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&Ji(t))return e.onFallback(e.branch),await e.clone(qi(null)),{fellBack:!0};throw t}}function Xi(e,t,n){return e===`https`&&t===`github.com`&&n}async function Zi(e,t,n,r=process.cwd()){let i=ht(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?z(r,t.dir):z(r,i.name);if(N(a)&&Bt(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=te(),s=i.protocol===`https`&&i.hostname===`github.com`?await Wi(i.owner,i.name):!1,c=Xi(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await Ui(i.hostname,o,{}),l=Te({baseDir:r,config:c.credentialArgs.length>=2?[c.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),u=-1;l.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
22
22
|
`)){let n=Ki(e);n&&n.pct!==u&&(u=n.pct,K(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await Yi({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>l.clone(e,a,t),onFallback:e=>{K(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
|
|
23
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
23
|
+
`);try{let{runInit:e}=await import(`./init-D8vPZw0o.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?K(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Qi(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Qi(e){let t=be(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function $i(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await Zi(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)K(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CfCut49X.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?K(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var ea=S();const ta=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...x.map(e=>e.path)];function na(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??St;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 ra(e){let t=(0,ea.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of ta)t.hasIn(e)&&n.push(e.join(`.`));return n}function ia(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aa(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=ia(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function oa(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??Le,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:Pe(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:Pe(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!N(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ra(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:aa(ta.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:u(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 d=c.some(e=>e.error!==void 0),f=c.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of 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 sa(){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(()=>{na({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await oa({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var ca=e(ft(),1),q=e(At(),1);const la=new Set([`doc.name`]);function ua(e){return`doc:${dn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function da(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 fa(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=ua(e);return t.originalToHashed.set(e,r),da(t,e,r),r}function pa(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ha(e,t){if(typeof e==`string`)return pa(e,t.contentDir);if(Array.isArray(e))return e.map(e=>ha(e,t));if(!ma(e))return e;let n=typeof e.key==`string`&&la.has(e.key)&&ma(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`&&ma(a)){let e=fa(n,t);r[i]={...a,stringValue:e}}else la.has(i)&&typeof a==`string`?r[i]=fa(a,t):r[i]=ha(a,t);return r}function ga(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 _a(e,t){let n=F(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
24
24
|
`),i=n.split(`
|
|
25
25
|
`),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=ha(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}I(e,r?`${a.join(`
|
|
26
26
|
`)}\n`:a.join(`
|
|
@@ -50,7 +50,7 @@ ws.addEventListener('error', () => process.exit(1));
|
|
|
50
50
|
setTimeout(() => process.exit(2), ${t+1e4});
|
|
51
51
|
`),r}async function To(e,t,n,r,i){let a=wo(e,t,R(r,`cpu.cpuprofile`)),o=!1,s=j(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=bo(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{Ht(R(a,`..`),{recursive:!0,force:!0})}catch{}return o}function Eo(e){let t;try{t=JSON.parse(e)}catch{return`(could not parse profile)`}let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map;for(let e of t.nodes)for(let t of e.children??[])r.set(t,e.id);let i=new Map;for(let e of t.samples??[])i.set(e,(i.get(e)??0)+1);let a=t.samples?.length??0,o=t.endTime!=null&&t.startTime!=null?((t.endTime-t.startTime)/1e3).toFixed(2):`?`,s=[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10),c=[`samples ${a} duration_ms ${o}`,``,`Top leaf nodes`];for(let[e,t]of s){let r=n.get(e);if(!r)continue;let i=a>0?(t/a*100).toFixed(1):`0.0`,{functionName:o,url:s,lineNumber:l,columnNumber:u}=r.callFrame;c.push(` ${t} ${i}% id=${e} ${o||`(anonymous)`} ${s}:${l}:${u} hit=${r.hitCount??0}`)}c.push(``,`Top stacks`);let l=e=>{let t=[],i=e;for(;i!=null;){let e=n.get(i);if(!e)break;let{functionName:a,url:o,lineNumber:s,columnNumber:c}=e.callFrame;t.unshift(` ${a||`(anonymous)`} ${o} ${s} ${c}`),i=r.get(i)}return t};for(let[e,t]of s.slice(0,5)){let n=a>0?(t/a*100).toFixed(1):`0.0`;c.push(``,`--- ${t} ${n}%`,...l(e))}return c.join(`
|
|
52
52
|
`)}async function Do(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??_t,s=t.inspect??vt,c=t.resolveCommand??yt,l=t.resolveUsage??mt,u=t.collectLsofFn??xo,d=t.getEndpoints??Co,f=t.profiler??To,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(q.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?R(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):R(process.cwd(),`ok-diagnose-${n}-${b}`);try{P(x,{recursive:!0})}catch(e){a(q.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(q.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{I(R(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?So(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(q.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(q.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
|
|
53
|
-
`)}\n`);try{S(`stacks.txt`,Eo(F(R(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(q.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(q.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(q.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: ${q.default.bold(x)}`)}async function Oo(e){let t=hn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function ko(e){let t=Rt(R(tn(),`ok-bundle-process-`));return await Do({pid:e,output:t}),t}function Ao(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 jo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Mo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(q.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ao(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 No(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Oo,i=t.runProcessDiagnose??ko,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=Kt(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=R(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=R(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(q.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Za({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(q.default.yellow(` server not running — live state unavailable`)),Mo(n,c,o),e.yes!==!0&&!jo(await r(`Write bundle? [y/N]: `))?(n(q.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Qa({collected:c,outputPath:o}),n(q.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Ht(s,{recursive:!0,force:!0})}catch{}}}function Po(){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(q.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(q.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Do({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(yo()),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(q.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-
|
|
53
|
+
`)}\n`);try{S(`stacks.txt`,Eo(F(R(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(q.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(q.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(q.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: ${q.default.bold(x)}`)}async function Oo(e){let t=hn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function ko(e){let t=Rt(R(tn(),`ok-bundle-process-`));return await Do({pid:e,output:t}),t}function Ao(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 jo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Mo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(q.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Ao(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 No(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Oo,i=t.runProcessDiagnose??ko,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=Kt(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=R(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=R(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(q.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Za({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(q.default.yellow(` server not running — live state unavailable`)),Mo(n,c,o),e.yes!==!0&&!jo(await r(`Write bundle? [y/N]: `))?(n(q.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await Qa({collected:c,outputPath:o}),n(q.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{Ht(s,{recursive:!0,force:!0})}catch{}}}function Po(){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(q.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(q.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Do({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(yo()),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(q.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-7gwzhh4P.mjs`),{resolveContentDir:r}=await import(`./dist-B8NhyNC8.mjs`),i=process.cwd(),{config:a}=n(i);await No({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(q.default.red(t)),process.exit(1)}}),e}const Fo=[` 1. ${A(`Customize`)} (sidebar) → ${A(`Skills`)}`,` 2. Click the ${A(`+`)} button`,` 3. Click ${A(`Create skill`)}`,` 4. Click ${A(`Upload skill`)}`,` 5. Pick ${A(`openknowledge.skill`)} from Downloads`],Io=T(` Open the Claude Desktop App, then: ${A(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Lo(e){let t=[D(`Built ${e.outputPath}`),E(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(k(` Handoff failed: ${e.handoffError.message}`)),t.push(Io),t.join(`
|
|
54
54
|
`)}function Ro(e){let t=e.skillVersion??`unknown`,n=e.recordedAt??`unknown`;return[T(`Open Knowledge skill ${A(`v${t}`)} already delivered to Claude Desktop.`),E(` Recorded at ${n} in ~/.ok/skill-state.yml`),E(` Use ${A(`--force`)} to rebuild and re-open the install dialog.`)].join(`
|
|
55
55
|
`)}function zo(e){let t=e.skillVersion?` • Skill v${e.skillVersion}`:``;return[D(`Built ${e.outputPath}`),E(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…${t}`),T(` Claude Desktop App opened. Now upload the file manually:`),...Fo,E(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
|
|
56
56
|
`)}function Bo(e){return`${O(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Vo(e={}){let t=await We(e);return t.status===`failed`?{...t,message:Bo(t),exitCode:1}:t.status===`skip-current`?{...t,message:Ro(t),exitCode:0}:t.status===`installed`?{...t,message:zo(t),exitCode:0}:{...t,message:Lo(t),exitCode:0}}function Ho(){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 Vo({out:e.out,noOpen:!e.open,force:e.force??!1});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}const Uo=R(`Contents`,`Resources`,`cli`,`bin`,`ok.sh`),Wo=/Contents\/Resources\/cli\/dist\/cli\.mjs$/;function Go(e,t,n){return e===`darwin`?[R(t,`Applications`,`Open Knowledge.app`,Uo),R(`/Applications`,`Open Knowledge.app`,Uo)].find(e=>n.existsSync(e))??null:null}function Ko(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`&&Wo.test(t[1])?{proxy:!1,suppressedBy:`self`}:{proxy:!0,suppressedBy:null}}function qo(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 Jo(e){qo({stderr:e.stderr,mode:`bundled`,bundlePath:e.bundlePath,reason:null});let t=e.spawnImpl??j,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 Yo(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 Xo=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
@@ -62,7 +62,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
|
|
|
62
62
|
`&&r++}}return[t,n]}var Sc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=bc({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 Cc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var wc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Tc=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=os(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Cc}async _authThenStart(){if(!this._authProvider)throw new Z(`No auth provider`);let e;try{e=await Zs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Z;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=as(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 wc(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 Sc({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=ze.parse(JSON.parse(e.data));Re(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Z(`No auth provider`);if(await Zs(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:$e(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 wc(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=tc(o);if(this._resourceMetadataUrl=t,this._scope=n,await Zs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Z;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=tc(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new wc(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Zs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Z;return this.send(e)}}throw new wc(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Oe(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=>ze.parse(e)):[ze.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new wc(-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 wc(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 Ec(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 Dc(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Oc(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function kc(e,t){return`http://${Oc(e)}:${t}/mcp`}function Ac(e,t){return`ws://${Oc(e)}:${t}`}function jc(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Mc(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function Nc(e){return N(e)?F(e,`utf-8`).trim():``}function Pc(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Fc(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Ic(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 Lc(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function Rc(e){let t=e.readLock??(()=>m(e.lockDir)),n=e.isAlive??v,r=e.sleep??(e=>mn(e)),i=e.spawn??j,a=e.readErrorLog??Nc,o=e.openErrorLog??(e=>zt(e,`w`)),s=e.closeFd??Pt,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 kc(`localhost`,t)}let u=Mc(t(),n);if(u!==void 0)return kc(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);N(e.lockDir)||P(e.lockDir,{recursive:!0});let d=R(e.lockDir,f),p=o(d),h,g,_=wt();try{try{h=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,ELECTRON_RUN_AS_NODE:`1`}}),h.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),h.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let y=Date.now()+c;for(;Date.now()<y;){if(g){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}await r(l);let e=Mc(t(),n);if(e!==void 0)return kc(`localhost`,e)}if(g){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${g}${t}`)}throw Error(Pc(c,a(d)))}function zc(e,t){if(e.portOverride!==void 0)return jc(t);let n=e.readLock??(()=>m(e.lockDir)),r=e.isAlive??v,i=Mc(n(),r);if(i!==void 0)return Ac(`localhost`,i)}async function Bc(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,a=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new $o(t.stdin,t.stdout),o=t.createHttpTransport?t.createHttpTransport(new URL(e)):new Tc(new URL(e),{fetch:Ec(r),requestInit:{headers:{...i({kind:`mcp`,runtimeVersion:g}),...t.connectionId===void 0?{}:{[De]:t.connectionId}}}}),s=!1,c=async()=>{s||(s=!0,t.onclose?.(),await Promise.allSettled([a.close(),o.close()]))};a.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},o.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},a.onclose=()=>{c()},o.onclose=()=>{c()};let l=Promise.resolve();a.onmessage=e=>{l=l.then(async()=>{try{await o.send(e)}catch(t){let r=Fc(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await a.send(Lc(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`)})},o.onmessage=e=>{let t=Ic(e);t&&o.setProtocolVersion?.(t),a.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await o.start(),await a.start()}catch(e){throw await c(),e}return{close:c}}async function Vc(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Bc,r=await Rc(e),i=e.createConnectionId?.()??fn(),a=!1,o=(e.startKeepalive??Yo)({connectionId:i,resolveWsUrl:async()=>zc(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 Hc=on(import.meta.url);function Uc(e){let t=z(e);for(;;){if(Ae(t))return t;let n=Kt(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 Wc(e){try{let t=new URL(e);return t.protocol===`file:`?on(t):void 0}catch{return}}async function Gc(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=Wc(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Kc(e,t){if(e!==void 0)return Uc(e);let n=await t();if(n!==void 0)return Uc(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 qc(e){let t=process.stderr,n=e.spawnTimeoutMs??Dc(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Ct({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new je({name:Qe,version:g},{instructions:qe({dir:`.`})});tt(a);let o=fn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=Xe(e),r=s.current,i=Yo({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>zc({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Gc({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>Kc(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=Uc(e)}else t=Uc(e);let a=await i(t),o=await Rc({lockDir:Xe(t),contentDir:lt(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}},ct(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new $o,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)
|
|
63
63
|
`);let y=!1,b=()=>{y||(y=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
64
64
|
`),process.exit(1)},5e3).unref(),v().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,b),process.once(`SIGTERM`,b),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
|
|
65
|
-
`),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),_=rs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),is({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=ns(Hc,{realpathSync:Vt,statInoSync:e=>Ut(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=ts({detect:()=>es({bundleAnchorPath:Hc,currentInode:r,platform:process.platform,realpath:Vt,statInode:e=>Ut(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 Jc(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=Dc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Vc({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=Ko(process.env,i,process.platform);if(a.proxy){let e=Go(process.platform,Qt(),{existsSync:N});if(e===null)qo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Jo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){qo({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`;qo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await qc({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 Yc(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Xc(e=()=>kt(Ot())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ke({lockDir:Me(e)}).baseUrl,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Yc(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Zc(e,t,n){let r=z(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}/#/${nt(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}/#/${at(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Qc(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Zc(e,t,Xc())})}function $c(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-
|
|
65
|
+
`),b()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),b()}),_=rs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),b()}}),is({log:e=>t.write(`${e}\n`),transport:p,process,stdin:process.stdin}),process.platform===`darwin`){let e=ns(Hc,{realpathSync:Vt,statInoSync:e=>Ut(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=ts({detect:()=>es({bundleAnchorPath:Hc,currentInode:r,platform:process.platform,realpath:Vt,statInode:e=>Ut(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 Jc(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=Dc(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Vc({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=Ko(process.env,i,process.platform);if(a.proxy){let e=Go(process.platform,Qt(),{existsSync:N});if(e===null)qo({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Jo({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){qo({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`;qo({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await qc({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 Yc(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Xc(e=()=>kt(Ot())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ke({lockDir:Me(e)}).baseUrl,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Yc(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Zc(e,t,n){let r=z(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}/#/${nt(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}/#/${at(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Qc(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Zc(e,t,Xc())})}function $c(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-DBrgAN_w.mjs`),r=e(),i=process.cwd(),a=lt(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 el(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function tl(e,t,n=process.cwd()){let r=e.op??`sync`,a=m(Me(n));if(a&&a.port>0){let t=`http://127.0.0.1:${a.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${a.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...i({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}`)}el(e.json,{type:`triggered`,op:r,port:a.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 o=Te({baseDir:n});if(r===`sync`||r===`pull`){el(e.json,{type:`step`,step:`pull`});let t=await o.pull();el(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(el(e.json,{type:`step`,step:`push`}),await o.push(),el(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
66
66
|
`)),el(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function nl(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 tl({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 rl(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await tl({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 il(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await tl({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 al(e){return typeof e==`string`&&Ie.includes(e)}async function ol(e={}){let t=z(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!it[n])return{status:`failed`,message:`${O(`Error:`)} Unknown pack "${n}". Available: ${Ie.join(`, `)}`,exitCode:1};let r;try{r=await Ze({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ue?{status:`prerequisite-missing`,message:`${O(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${O(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=it[n].name;return{status:`no-op`,message:`${D(`Your ${e} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${A(`Plan (dry-run — no changes made):`)}\n\n${cl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await ll(`${A(`Plan:`)}\n\n${cl(r,t)}\n\n${A(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:r,exitCode:0};let i=await st(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${O(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${k(`Applied`)} ${i.applied} entries, ${k(String(i.errors.length))} error(s):`,...e].join(`
|
|
67
67
|
`),plan:r,exitCode:1}}let a=it[n].name,o=i.packSkillsInstalled.length>0?`\n${E(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${D(`✓ Seeded ${a}`)} ${E(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function sl(){let e=[A(`Available packs:`)];for(let t of Ie){let n=it[t];e.push(` ${D(t)} ${E(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
|
68
68
|
`)}function cl(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(A(`Folders to create:`));for(let e of r)n.push(` ${D(`+`)} ${T(qt(t,z(t,e.path))||e.path)}${E(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(A(`Files to create:`));for(let e of i)n.push(` ${D(`+`)} ${T(qt(t,z(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(E(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${E(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(k(`Warnings:`));for(let t of e.warnings)n.push(` ${k(`!`)} ${t}`)}return n.join(`
|
|
@@ -71,7 +71,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
|
|
|
71
71
|
`);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function pl(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 fl(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 hl(e,t){let{host:n,json:r}=e;V(n);let i=await yi(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 G({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 gl(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 hl(t,await e())})}function _l(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
|
|
72
72
|
`)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function vl(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 yl(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 bl(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function xl(e){return Te({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function Sl(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 Cl={ensureOkScaffold:e=>{Ne(e)},gitFactory:xl};async function wl(e){let t={...Cl,...e.deps},n=z(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await bl(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:_l(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!N(R(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await vl({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(_l(t)===`name-conflict`){let t=await yl(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:_l(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=Sl(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 Tl(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 El(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;V(n);let l=await yi(n,t);if(l==null){Tl(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new G({auth:l,...u?{baseUrl:u}:{}});try{Mt(`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`}Tl(c,await wl({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function Dl(e){return new t(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
|
|
73
73
|
`),process.exit(1)),await El(t,await e())})}function Ol(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>ne();return e.addCommand(gl(n)),e.addCommand(pl(n)),e.addCommand(Dl(n)),e}function kl(){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=z(e.project??process.cwd()),n=ve(t),r=ce(t,se(t));if(r.kind===`no-exclude`){Al(e.json,t,r.reason);return}let i=ve(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${T(`Sharing mode is already`)} ${A(`shared`)} ${T(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${A(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function Al(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(`${k({"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 jl(){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=z(e.project??process.cwd()),n=ve(t),r=[..._e(t)],i=Ce(t,se(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`Open Knowledge sharing mode: ${Ml(n)}`),a.push(``),a.push(`Excluded from git via ${A(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${T(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
|
|
74
|
-
`)}\n`)})}function Ml(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return k(`no-git (not a git repository)`)}}function Nl(){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=z(e.project??process.cwd()),n=be(t,se(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){Pl(e.json,t,n.reason);return}let r=ve(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${A(`Sharing mode is already`)} ${D(`local-only`)} ${A(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${A(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Pl(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(`${k({"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 Fl(){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(kl()),e.addCommand(Nl()),e.addCommand(jl()),e}const Il=new Set([`--cwd`,`--log-level`]);function Ll(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(`-`)){Il.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Rl(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 zl(e){return/\.(md|mdx)$/i.test(e)}function Bl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Vl(e=()=>kt(Ot())){return{prepare:Ge,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Bl(process.env)}).unref()},runProjectOpen:(e,t)=>Zc(e,{project:t},Xc()),runBrowserOpen:e=>Wl(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Hl(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Je||e instanceof Ee||e instanceof ot)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 Ul(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[z(e,`public`),z(e,`../../app/dist`),z(e,`../../../app/dist`)].find(e=>N(e))}async function Wl(e){let{createEphemeralProjectDir:t}=await import(`./dist-
|
|
74
|
+
`)}\n`)})}function Ml(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return k(`no-git (not a git repository)`)}}function Nl(){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=z(e.project??process.cwd()),n=be(t,se(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){Pl(e.json,t,n.reason);return}let r=ve(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${A(`Sharing mode is already`)} ${D(`local-only`)} ${A(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${A(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function Pl(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(`${k({"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 Fl(){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(kl()),e.addCommand(Nl()),e.addCommand(jl()),e}const Il=new Set([`--cwd`,`--log-level`]);function Ll(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(`-`)){Il.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Rl(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 zl(e){return/\.(md|mdx)$/i.test(e)}function Bl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Vl(e=()=>kt(Ot())){return{prepare:Ge,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Bl(process.env)}).unref()},runProjectOpen:(e,t)=>Zc(e,{project:t},Xc()),runBrowserOpen:e=>Wl(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Hl(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Je||e instanceof Ee||e instanceof ot)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 Ul(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[z(e,`public`),z(e,`../../app/dist`),z(e,`../../../app/dist`)].find(e=>N(e))}async function Wl(e){let{createEphemeralProjectDir:t}=await import(`./dist-B8NhyNC8.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-CfCut49X.mjs`),{openBrowser:a}=await import(`./open-browser-C6LU_1mt.mjs`),o=Ul();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 pn(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}/#/${at(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
|
|
75
75
|
`),a(m),await new Promise(()=>{})}function Gl(e,t){return{server:Kl(`server`,e),ui:Kl(`ui`,t)}}function Kl(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 ql(e){return`${Jl(e.server)}\n${Jl(e.ui)}`}function Jl(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 Yl(e){let t=e.inspect??(t=>vt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Gl(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(ql(r)),r}function Xl(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(),Yl({lockDir:Me(process.cwd()),json:t.json===!0})})}function Zl(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(`
|
|
76
76
|
`)}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 $,Ql;function $l(){return Ql}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Zl(bt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;t!==void 0&&process.chdir(t);let{config:n}=St(t);$=n;let r=e.args?.[0]??e.name()??`cli`;Ql=Fe({name:`cli`,project:n.project?.name??void 0}),Ql.info({command:r,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(kt(Ot()).available){Tt({spawn:j});return}await Et($,{})});const eu=Dt(()=>$);Q.addCommand(eu);const tu=Jc(()=>$);Q.addCommand(tu),Q.addCommand(xe()),Q.addCommand(ul()),Q.addCommand(Ho()),Q.addCommand(jt());const nu=$c(()=>$);Q.addCommand(nu);const ru=Se(()=>$);Q.addCommand(ru),Q.addCommand(Qc()),Q.addCommand(gt(()=>$)),Q.addCommand(Hi(()=>$)),Q.addCommand(Xl(()=>$)),Q.addCommand(pt()),Q.addCommand(Po()),Q.addCommand(zi()),Q.addCommand(sa()),Q.addCommand(Di()),Q.addCommand($i(()=>$)),Q.addCommand(nl(()=>$)),Q.addCommand(il(()=>$)),Q.addCommand(rl(()=>$)),Q.addCommand(Ol()),Q.addCommand(Fl()),Q.addHelpText(`after`,`
|
|
77
77
|
Examples:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Cn as e,Wr as t,a as n,bn as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,q as h,qr as g,r as _,rn as v,s as y,sn as b,t as x,u as S,wr as C}from"./server-lock-BpjJj3OD-ATm9AAM0.mjs";import{$ as w,$n as T,$r as E,$t as D,A as O,An as k,Ar as A,At as j,B as M,Bn as N,Br as P,Bt as F,C as I,Ci as L,Cn as R,Cr as z,Ct as B,D as V,Dn as H,Dr as U,Dt as W,E as G,Ei as K,En as q,Er as J,Et as Y,F as X,Fn as Z,Fr as Q,Ft as $,G as ee,Gn as te,Gr as ne,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as se,I as ce,In as le,Ir as ue,It as de,J as fe,Jn as pe,Jr as me,Jt as he,K as ge,Kn as _e,Kr as ve,Kt as ye,L as be,Ln as xe,Lr as Se,Lt as Ce,M as we,Mn as Te,Mr as Ee,Mt as De,N as Oe,Nn as ke,Nr as Ae,Nt as je,O as Me,On as Ne,Or as Pe,Ot as Fe,P as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qn as Ve,Qr as He,Qt as Ue,R as We,Ri as Ge,Rn as Ke,Rr as qe,Rt as Je,S as Ye,Si as Xe,Sn as Ze,Sr as Qe,St as $e,T as et,Ti as tt,Tn as nt,Tr as rt,Tt as it,U as at,Un as ot,Ur as st,Ut as ct,V as lt,Vn as ut,Vr as dt,Vt as ft,W as pt,Wn as mt,Wr as ht,Wt as gt,X as _t,Xn as vt,Xr as yt,Xt as bt,Y as xt,Yn as St,Yr as Ct,Yt as wt,Z as Tt,Zn as Et,Zr as Dt,Zt as Ot,_ as kt,_i as At,_n as jt,_r as Mt,_t as Nt,a as Pt,ai as Ft,an as It,ar as Lt,at as Rt,b as zt,bi as Bt,bn as Vt,br as Ht,bt as Ut,c as Wt,ci as Gt,cn as Kt,cr as qt,ct as Jt,d as Yt,di as Xt,dn as Zt,dr as Qt,dt as $t,ei as en,en as tn,er as nn,et as rn,f as an,fi as on,fn as sn,fr as cn,ft as ln,g as un,gi as dn,gn as fn,gr as pn,gt as mn,h as hn,hi as gn,hn as _n,hr as vn,ht as yn,i as bn,ii as xn,in as Sn,ir as Cn,it as wn,j as Tn,jn as En,jr as Dn,jt as On,k as kn,kn as An,kr as jn,kt as Mn,l as Nn,li as Pn,ln as Fn,lr as In,lt as Ln,m as Rn,mi as zn,mn as Bn,mr as Vn,mt as Hn,n as Un,ni as Wn,nn as Gn,nr as Kn,nt as qn,o as Jn,oi as Yn,on as Xn,or as Zn,ot as Qn,p as $n,pi as er,pn as tr,pr as nr,pt as rr,q as ir,qn as ar,qr as or,qt as sr,r as cr,ri as lr,rn as ur,rr as dr,rt as fr,s as pr,si as mr,sn as hr,sr as gr,st as _r,t as vr,ti as yr,tn as br,tr as xr,tt as Sr,u as Cr,ui as wr,un as Tr,ur as Er,ut as Dr,v as Or,vi as kr,vn as Ar,vr as jr,vt as Mr,w as Nr,wi as Pr,wn as Fr,wr as Ir,wt as Lr,x as Rr,xi as zr,xn as Br,xr as Vr,xt as Hr,y as Ur,yi as Wr,yn as Gr,yr as Kr,yt as qr,z as Jr,zi as Yr,zn as Xr,zr as Zr,zt as Qr}from"./dist-
|
|
1
|
+
import{Cn as e,Wr as t,a as n,bn as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,q as h,qr as g,r as _,rn as v,s as y,sn as b,t as x,u as S,wr as C}from"./server-lock-BpjJj3OD-ATm9AAM0.mjs";import{$ as w,$n as T,$r as E,$t as D,A as O,An as k,Ar as A,At as j,B as M,Bn as N,Br as P,Bt as F,C as I,Ci as L,Cn as R,Cr as z,Ct as B,D as V,Dn as H,Dr as U,Dt as W,E as G,Ei as K,En as q,Er as J,Et as Y,F as X,Fn as Z,Fr as Q,Ft as $,G as ee,Gn as te,Gr as ne,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as se,I as ce,In as le,Ir as ue,It as de,J as fe,Jn as pe,Jr as me,Jt as he,K as ge,Kn as _e,Kr as ve,Kt as ye,L as be,Ln as xe,Lr as Se,Lt as Ce,M as we,Mn as Te,Mr as Ee,Mt as De,N as Oe,Nn as ke,Nr as Ae,Nt as je,O as Me,On as Ne,Or as Pe,Ot as Fe,P as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qn as Ve,Qr as He,Qt as Ue,R as We,Ri as Ge,Rn as Ke,Rr as qe,Rt as Je,S as Ye,Si as Xe,Sn as Ze,Sr as Qe,St as $e,T as et,Ti as tt,Tn as nt,Tr as rt,Tt as it,U as at,Un as ot,Ur as st,Ut as ct,V as lt,Vn as ut,Vr as dt,Vt as ft,W as pt,Wn as mt,Wr as ht,Wt as gt,X as _t,Xn as vt,Xr as yt,Xt as bt,Y as xt,Yn as St,Yr as Ct,Yt as wt,Z as Tt,Zn as Et,Zr as Dt,Zt as Ot,_ as kt,_i as At,_n as jt,_r as Mt,_t as Nt,a as Pt,ai as Ft,an as It,ar as Lt,at as Rt,b as zt,bi as Bt,bn as Vt,br as Ht,bt as Ut,c as Wt,ci as Gt,cn as Kt,cr as qt,ct as Jt,d as Yt,di as Xt,dn as Zt,dr as Qt,dt as $t,ei as en,en as tn,er as nn,et as rn,f as an,fi as on,fn as sn,fr as cn,ft as ln,g as un,gi as dn,gn as fn,gr as pn,gt as mn,h as hn,hi as gn,hn as _n,hr as vn,ht as yn,i as bn,ii as xn,in as Sn,ir as Cn,it as wn,j as Tn,jn as En,jr as Dn,jt as On,k as kn,kn as An,kr as jn,kt as Mn,l as Nn,li as Pn,ln as Fn,lr as In,lt as Ln,m as Rn,mi as zn,mn as Bn,mr as Vn,mt as Hn,n as Un,ni as Wn,nn as Gn,nr as Kn,nt as qn,o as Jn,oi as Yn,on as Xn,or as Zn,ot as Qn,p as $n,pi as er,pn as tr,pr as nr,pt as rr,q as ir,qn as ar,qr as or,qt as sr,r as cr,ri as lr,rn as ur,rr as dr,rt as fr,s as pr,si as mr,sn as hr,sr as gr,st as _r,t as vr,ti as yr,tn as br,tr as xr,tt as Sr,u as Cr,ui as wr,un as Tr,ur as Er,ut as Dr,v as Or,vi as kr,vn as Ar,vr as jr,vt as Mr,w as Nr,wi as Pr,wn as Fr,wr as Ir,wt as Lr,x as Rr,xi as zr,xn as Br,xr as Vr,xt as Hr,y as Ur,yi as Wr,yn as Gr,yr as Kr,yt as qr,z as Jr,zi as Yr,zn as Xr,zr as Zr,zt as Qr}from"./dist-Brl9qSX0.mjs";export{vr as AGENT_ID_MAX_LEN,Un as AGENT_ID_RE,cr as AGENT_WRITE_ORIGIN,bn as AgentFocusBroadcaster,Pt as AgentPresenceBroadcaster,Jn as AgentSessionCapacityError,pr as AgentSessionManager,Wt as BacklinkIndex,Nn as CC1Broadcaster,h as CC1_CONTRACT_VERSION,Cr as CONFIG_FILENAME,Yt as CONFLICT_MARKER_RE,an as CURSOR_BUNDLE_PATHS_BY_PLATFORM,$n as ConfigSchema,Rn as DEFAULT_CHECKPOINT_RETENTION,hn as DEFAULT_PACK_ID,un as FILE_SYSTEM_WRITER,kt as FILE_WATCHER_ORIGIN,Or as GIT_PREFLIGHT_FAIL_SPAN_NAME,Ur as GIT_UPSTREAM_WRITER,Ge as GitDirAccessError,zt as GitNotAvailableError,Rr as GitTooOldError,Ye as HOCUSPOCUS_AUTH_REJECTION_REASONS,I as HocuspocusAuthRejection,Nr as HocuspocusAuthTokenSchema,et as INSTALLED_AGENTS_SCHEMES,G as LIVE_DERIVED_INDEX_DEBOUNCE_MS,V as LOG_MD_TEMPLATE,Me as MANAGED_RENAME_ORIGIN,kn as MAX_AGENT_SESSIONS,O as MCP_CONNECTION_ID_HEADER,Tn as MCP_SERVER_NAME,we as MIN_GIT_VERSION,Oe as MISSING_OK_CONFIG_MESSAGE,Yr as MalformedGitPointerError,Ie as McpLogger,X as MissingOkConfigError,ce as OBSERVER_SYNC_ORIGIN,be as OK_OKIGNORE_TEMPLATE,v as ORPHAN_MODES,We as PANE_TARGET_TTL_MS,b as PROTOCOL_VERSION,Jr as PinoLogger,x as ProcessLockCollisionError,M as ProjectGitInitError,lt as ROLLBACK_ORIGIN,ie as ROOT_GITIGNORE_TEMPLATE,f as RUNTIME_VERSION,at as SERVICE_WRITER,pt as SKILL_INSTALL_EVENTS_FILE_REL,r as SKILL_STATE_TARGETS,ee as STARTER_FOLDERS,ge as STARTER_FOLDER_FRONTMATTER_FILENAME,ir as STARTER_PACKS,fe as STARTER_PACK_IDS,xt as STARTER_TEMPLATES,_t as STATE_MANIFEST_FILENAME,_ as STATE_SCHEMA_VERSION,e as SYSTEM_DOC_NAME,Tt as SeedPrerequisiteError,Be as SeedRootDirError,l as ServerLockCollisionError,w as SingleFileNotAFileError,rn as SingleFileNotFoundError,Sr as SingleFileNotMarkdownError,qn as StateManifestError,fr as TagIndex,wn as UiLockCollisionError,Rt as __getShowAllWalkStatsForTesting,Qn as __resetShowAllWalkStatsForTesting,n as acquireProcessLock,p as acquireServerLock,_r as acquireUiLock,Jt as applyAgentMarkdownWrite,Ln as applyExternalChange,Dr as applySeed,$t as armPaneTarget,ln as assertCompatibleStateManifest,rr as assertGitAvailable,Hn as assertNeverDiskEvent,yn as attachIdleShutdown,mn as bootServer,Nt as buildAndOpenSkill,Mr as buildConfigYmlContent,qr as buildExecResult,Ut as buildInstructions,Hr as buildSkillZip,$e as buildStarterFolderFrontmatterYaml,B as buildWipTree,Lr as classifyEvents,it as classifyFsPath,Y as clearArmedPaneTarget,W as clearContributors,Fe as coercePackId,C as colorFromSeed,Mn as commitUpstreamImport,j as commitWip,On as commitWipFromTree,De as compareSemver,je as containsConflictMarkers,ze as contentHash,$ as contributorCount,de as createApiExtension,Ce as createAssetServeMiddleware,Je as createContentFilter,Qr as createContentFilterAsync,F as createEphemeralProjectDir,ft as createExternalChangeHandler,se as createFileLogger,ct as createLiveDerivedIndexExtension,gt as createMcpHttpHandler,re as createOsProbe,ye as createPersistenceExtension,sr as createServer,he as createServerObserverExtension,wt as createStreamingErrorWriter,bt as createTestLogger,Ot as detectClaudeDesktopPresence,Ue as detectGit,D as detectProjectShape,tn as emitPreflightFailureSpan,br as encodeDocName,Gn as encodeFolderRoute,ur as ensureProjectGit,Sn as errorResponse,It as evictStaleTrackerEntries,Xn as extractWikiLinksFromMarkdown,hr as fallbackPaths,Kt as findEnclosingGitRoot,Fn as findEnclosingProjectRoot,Tr as formatAuthRejectionWire,Zt as formatContributors,sn as formatContributorsFrom,tr as gcCheckpointRefs,Bn as getCurrentMcpLogger,_n as getLocalDir,fn as getLogFilePath,jt as getLogger,Ar as getLogsDir,Gr as getMeter,Vt as getMetrics,Br as getTracer,Ze as handleCollabSocketError,R as handleSpawnCursor,t as iconFromClientName,Fr as incrementCollabSocketFilteredError,nt as incrementServerObserverFire,q as initContent,H as initShadowRepo,Ne as initTelemetry,An as installPrettyZodErrors,k as installTestLoggers,En as installUserSkill,Te as isAllowedApiOrigin,ke as isAllowedWorkspaceHostHeader,Le as isConfigDoc,Z as isHocuspocusAuthRejectionReason,le as isKnownPackId,xe as isLoopbackAddress,g as isOrphanMode,Ke as isPairedWriteOrigin,Xr as isPathWithinDir,y as isProcessAlive,N as isProjectRoot,ut as isSelfWrite,ae as isSystemDoc,i as isValidLockPid,ot as lastKnownHash,mt as listRescueCheckpoints,te as listStarterPacks,_e as loadPrincipal,u as lockFilePath,ar as loggerFactory,pe as logsCurrentPath,St as logsPreviousPath,vt as mountMcpAndApi,Et as normalizeFsPath,Ve as packageVersionMajorMinor,T as parseAuthRejectionWire,nn as parseGitVersion,xr as parseHocuspocusAuthToken,Kn as parseKeepaliveConnectionId,dr as pathToDocName,Cn as planSeed,Lt as prepareSingleFileOpen,Zn as readAllTargets,gr as readArmedPaneTarget,qt as readBranchFromHead,S as readProcessLock,a as readProcessLockDetailed,o as readServerLock,In as readServerPackageVersion,Er as readSkillInstallStateSnapshot,Qt as readStateManifest,cn as readTargetRecordedAt,nr as readTargetVersion,Vn as readUiLock,vn as reconcile,pn as recordContributor,Mt as recordSkillInstallEvent,jr as registerAllTools,Kr as registerWrite,m as releaseProcessLock,d as releaseServerLock,Ht as releaseUiLock,Vr as removeLastKnownHash,Qe as resetMetrics,z as resolveBundledSkillDir,Ir as resolveContentDir,rt as resolveCursorBinaryDefault,J as resolveCursorSpawnInvocation,U as resolveLockDir,Pe as resolvePack,jn as resolvePackageVersion,A as resolveUiInfo,Dn as restoreContributors,Ee as restoreLifecycleFromConflictsJson,Ae as rewriteMarkdownLinksForDocumentRename,Re as rewriteWikiLinksForDocumentRename,Q as runAuthReposSubprocess,ue as runAuthStatusSubprocess,Se as runCloneSubprocess,qe as runDeviceFlowSubprocess,Zr as runWithMcpLogger,P as safeContentPath,dt as safeSubdir,oe as safetyCheckpoint,st as sanitizeClientName,ht as saveInMemoryCheckpoint,ne as saveVersion,ve as seedBasenameIndex,or as serializeError,me as setActiveSpanAttributes,Ct as shadowGit,yt as shutdownTelemetry,Dt as spansCurrentPath,He as spansPreviousPath,E as spawnDetached,en as splitMarkdownBlocks,yr as startWatcher,Wn as streamingProblemEvent,lr as swapContributors,xn as toBroadcasterKey,Ft as tracedAppendFileSync,Yn as tracedLinkSync,mr as tracedMkdir,Gt as tracedMkdirSync,Pn as tracedRename,wr as tracedRenameSync,Xt as tracedRmSync,on as tracedRmdirSync,er as tracedUnlinkSync,zn as tracedWriteFile,gn as tracedWriteFileSync,dn as updateLastKnownHash,c as updateProcessLockPort,s as updateServerLockPort,At as updateUiLockPort,kr as validateAgentId,Wr as validateCloneInputs,Bt as validateSkillZip,zr as withSpan,Xe as withSpanSync,L as writeRootGitignoreForNewRepo,Pr as writeStateManifest,tt as writeTargetVersion,K as writeTracker};
|