@inkeep/open-knowledge 0.16.0-beta.0 → 0.16.0-beta.1
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-PrZJ-CTv.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/{init-Dx1FSwm_.mjs → init-Bd49mCW9.mjs} +3 -3
- package/dist/init-CmEFD2yV.mjs +1 -0
- package/dist/loader-BMjYHLZp.mjs +1 -0
- package/dist/{loader-Bi8VVUuv.mjs → loader-yyLYaVhN.mjs} +2 -2
- package/dist/{preview-CNJw1WeR.mjs → preview-DF7SCtlt.mjs} +2 -2
- package/dist/preview-DVsrv_hV.mjs +1 -0
- package/dist/public/assets/SettingsDialogBody-CIE_A6cd.js +7 -0
- package/dist/public/assets/TerminalPanel-Cs6SOojP.js +145 -0
- package/dist/public/assets/{config-validation-events-Dom3HCUM.js → config-validation-events-C0vw-EiG.js} +5 -5
- package/dist/public/assets/index-BnOmMrYn.js +2019 -0
- package/dist/public/assets/index-CZh9fj9x.css +1 -0
- package/dist/public/index.html +3 -3
- package/dist/{repair-launch-json-Bm5zcxnt.mjs → repair-launch-json-IjDH1MEo.mjs} +2 -2
- package/dist/{repair-mcp-configs-B6-IzQ47.mjs → repair-mcp-configs-DP8S99Yv.mjs} +2 -2
- package/dist/{src-DmdJFypb.mjs → src-6vQuUOgy.mjs} +2 -2
- package/dist/start-DQUEhZj2.mjs +1 -0
- package/dist/{start-mHeHaykC.mjs → start-DnZWr4Pv.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-zR9K6MQx.mjs +0 -2
- package/dist/init-5s5Urhtt.mjs +0 -1
- package/dist/loader-N9LzTn4Q.mjs +0 -1
- package/dist/preview-BvKJzJeL.mjs +0 -1
- package/dist/public/assets/SettingsDialogBody-BM8EOX42.js +0 -7
- package/dist/public/assets/TerminalPanel-CDbNsVll.js +0 -145
- package/dist/public/assets/index-CIPatjw4.css +0 -1
- package/dist/public/assets/index-DIPWIhIx.js +0 -2019
- package/dist/start-LI_wE7gV.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.16.0-beta.
|
|
6
|
+
version: "0.16.0-beta.1"
|
|
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 for working inside this Open Knowledge project."
|
|
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.16.0-beta.
|
|
6
|
+
version: "0.16.0-beta.1"
|
|
7
7
|
author: "Inkeep"
|
|
8
8
|
repository: "https://github.com/inkeep/open-knowledge"
|
|
9
9
|
---
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{Da as n,Gr as r,Ji as i,Li as a,Mi as o,Ni as s,Oa as c,Sr as l,Wi as u,Xi as d,Yi as f,bn as p,ea as m,f as h,n as g,na as _,pa as v,ra as y,s as b,sa as x,ta as S,ua as C}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{a as ee,n as w,r as te,t as ne}from"./gh-detect-wbzQ2Z5B.mjs";import{r as T}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$i as re,Bt as ie,Cr as ae,F as oe,Gi as se,Gr as ce,Hr as le,Ht as ue,Ji as de,Ki as fe,Ln as pe,Nr as me,P as he,Pn as ge,Q as _e,Qn as ve,T as ye,Tn as be,Ui as xe,Vn as Se,Vt as Ce,Wi as we,Xt as Te,Z as Ee,Zi as De,_ as Oe,_t as ke,an as Ae,at as je,c as Me,dn as Ne,ea as Pe,ia as Fe,ii as Ie,it as Le,jt as Re,mt as ze,na as Be,qi as Ve,qt as He,rt as Ue,ta as We,tt as Ge,un as Ke,v as qe,vr as Je,w as Ye,xt as Xe,yn as Ze,yr as Qe,zr as $e}from"./dist-Dcg4smYg.mjs";import{t as et}from"./yazl-Docqgl6q.mjs";import{n as tt,r as nt,t as rt}from"./dist-bundle-D75dREX-.mjs";import{B as it,C as at,E as ot,F as st,H as ct,I as lt,L as ut,M as dt,N as ft,P as pt,R as mt,S as ht,T as gt,V as _t,b as vt,u as yt,v as bt,w as xt,z as St}from"./init-
|
|
2
|
+
import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{Da as n,Gr as r,Ji as i,Li as a,Mi as o,Ni as s,Oa as c,Sr as l,Wi as u,Xi as d,Yi as f,bn as p,ea as m,f as h,n as g,na as _,pa as v,ra as y,s as b,sa as x,ta as S,ua as C}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{a as ee,n as w,r as te,t as ne}from"./gh-detect-wbzQ2Z5B.mjs";import{r as T}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$i as re,Bt as ie,Cr as ae,F as oe,Gi as se,Gr as ce,Hr as le,Ht as ue,Ji as de,Ki as fe,Ln as pe,Nr as me,P as he,Pn as ge,Q as _e,Qn as ve,T as ye,Tn as be,Ui as xe,Vn as Se,Vt as Ce,Wi as we,Xt as Te,Z as Ee,Zi as De,_ as Oe,_t as ke,an as Ae,at as je,c as Me,dn as Ne,ea as Pe,ia as Fe,ii as Ie,it as Le,jt as Re,mt as ze,na as Be,qi as Ve,qt as He,rt as Ue,ta as We,tt as Ge,un as Ke,v as qe,vr as Je,w as Ye,xt as Xe,yn as Ze,yr as Qe,zr as $e}from"./dist-Dcg4smYg.mjs";import{t as et}from"./yazl-Docqgl6q.mjs";import{n as tt,r as nt,t as rt}from"./dist-bundle-D75dREX-.mjs";import{B as it,C as at,E as ot,F as st,H as ct,I as lt,L as ut,M as dt,N as ft,P as pt,R as mt,S as ht,T as gt,V as _t,b as vt,u as yt,v as bt,w as xt,z as St}from"./init-Bd49mCW9.mjs";import{a as Ct,c as wt,h as Tt,i as Et,l as Dt,m as Ot,o as kt,s as At,u as jt}from"./src-6vQuUOgy.mjs";import{n as Mt,t as Nt}from"./constants-PrZJ-CTv.mjs";import{n as Pt,t as Ft}from"./loader-yyLYaVhN.mjs";import{S as It,_ as Lt,b as Rt,m as zt,x as Bt,y as Vt}from"./start-DnZWr4Pv.mjs";import{c as Ht,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-8SzMRIVy.mjs";import{n as Ut}from"./repair-skills-DsHqeRKO.mjs";import{execFile as Wt,execSync as Gt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as Kt,closeSync as qt,constants as Jt,cpSync as Yt,createWriteStream as Xt,existsSync as P,mkdirSync as F,mkdtempSync as Zt,openSync as Qt,readFileSync as I,readdirSync as $t,realpathSync as en,rmSync as tn,statSync as nn,unlinkSync as rn,writeFileSync as L}from"node:fs";import an,{basename as R,dirname as on,join as z,relative as sn,resolve as B,sep as cn}from"node:path";import ln from"node:process";import{arch as un,freemem as dn,homedir as fn,platform as pn,release as mn,tmpdir as hn,totalmem as gn,type as _n,uptime as vn}from"node:os";import{fileURLToPath as yn}from"node:url";import{rm as bn}from"node:fs/promises";import{createHash as xn,randomUUID as Sn}from"node:crypto";import{setTimeout as Cn}from"node:timers/promises";import{promisify as wn,stripVTControlCharacters as Tn,styleText as V}from"node:util";import{AsyncLocalStorage as En,AsyncResource as Dn}from"node:async_hooks";import*as On from"node:readline";import{createInterface as kn}from"node:readline/promises";const An={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var jn;(function(e){})(jn||={});function Mn(e){return v(u,e)}async function Nn(e,t,n,r){let i=Pn(await Fn(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function Pn(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 Fn(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 In(e,n){let r=new t(`git-credential`);return r.description(`Git credential helper (git credential-helper protocol)`),r.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=n?.();try{let n,r=await e({onKeychainRead:e=>{n=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&t?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await Nn(process.stdin,process.stdout,r,{log:t,getDiag:()=>n});await Ze(t),process.exit(i)}catch(e){t?.error({error:e instanceof Error?e.message:String(e)},`[auth] git-credential get: unexpected error`),await Ze(t),process.exit(1)}}),r}function Ln(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Rn(e,t,n){let r={baseUrl:Ln(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new tt(`${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 zn(e){let t=e.request||rt,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Rn(t,`POST /login/device/code`,n)}async function Bn(e){let t=await Rn(e.request||rt,`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=Vn(e,t.data.expires_in),n.refreshTokenExpiresAt=Vn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Vn(e,t){return new Date(e+t*1e3).toISOString()}async function Hn(e,t){let n=Un(e,t.auth);if(n)return n;let{data:r}=await zn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Gn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Un(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 Wn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Gn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Bn({...i,clientType:`oauth-app`}):await Bn({...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 Wn(r.interval),Gn(e,t,n,r);if(a===`slow_down`)return await Wn(r.interval+7),Gn(e,t,n,r);throw i}}async function Kn(e,t){return Hn(e,{auth:t})}async function qn(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 Hn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Jn=`0.0.0-development`;function Yn(e){let t=e.request||rt.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Jn} ${nt()}`}}),{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:qn.bind(null,i)})}async function Xn(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Yn({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BnlRWriT.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Zn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Qn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function H(e){let t=e.toLowerCase().replace(/:\d+$/,``);Qn.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 $n(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function er(e,t,n=Xn){let r=Zn(),{host:i,json:a}=e;H(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?$n(!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?$n(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function tr(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 er(t,await e())})}const nr=e=>e.name===`enter`||e.name===`return`;var rr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},ir=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},ar=class extends Error{name=`ExitPromptError`},or=class extends Error{name=`HookError`},sr=class extends Error{name=`ValidationError`};const cr=new En;function lr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ur(e,t){let n=lr(e);return cr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function U(){let e=cr.getStore();if(!e)throw new or(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function dr(){return U().rl}function fr(e){return Dn.bind((...t)=>{let n=U(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function pr(e){let t=U(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function mr(){U().handleChange()}const hr={queue(e){let t=U(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(dr());if(r!=null&&typeof r!=`function`)throw new sr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=U();fr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=U();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function gr(e){return typeof e==`function`}function W(e){return pr(t=>{let n=Dn.bind(function(e){t.get()!==e&&(t.set(e),mr())});if(t.initialized)return[t.get(),n];let r=gr(e)?e():e;return t.set(r),[r,n]})}function _r(e,t){pr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&hr.queue(e),n.set(t)})}const vr={prefix:{idle:V(`blue`,`?`),done:V(`green`,ct.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>V(`yellow`,e))},style:{answer:e=>V(`cyan`,e),message:e=>V(`bold`,e),error:e=>V(`red`,`> ${e}`),defaultAnswer:e=>V(`dim`,`(${e})`),help:e=>V(`dim`,e),highlight:e=>V(`cyan`,e),key:e=>V(`cyan`,V(`bold`,`<${e}>`))}};function yr(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 br(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=yr(n)&&yr(r)?br(n,r):r}return t}function xr(...e){return br(vr,...e.filter(e=>e!=null))}function Sr({status:e=`idle`,theme:t}){let[n,r]=W(!1),[i,a]=W(0),{prefix:o,spinner:s}=xr(t);return _r(()=>{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 Cr(e){return W({current:e})[0]}function wr(e){let t=Cr(e);t.current=e,_r(e=>{let n=!1,r=fr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var Tr=e(_t(),1);function Er(e,t){return e.split(`
|
|
4
4
|
`).flatMap(e=>it(e,t,{trim:!1,hard:!0}).split(`
|
|
5
5
|
`).map(e=>e.trimEnd())).join(`
|
|
@@ -19,7 +19,7 @@ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";impor
|
|
|
19
19
|
`),patterns:[...t],lineCount:n}}const Ki=z(fn(),`.ok`,`logs`),qi=z(fn(),`.ok`,`bug-reports`);function Ji(e){let t=z(e,`.ok`,`config.yml`);if(P(t))try{let e=I(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return P(z(e,`.ok`))?xn(`sha256`).update(B(e)).digest(`hex`).slice(0,12):null}function Yi(){let e={timestamp:new Date().toISOString(),platform:pn(),osType:_n(),osRelease:mn(),hostname:`[redacted]`,uptime:vn(),freeMem:dn(),totalMem:gn(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Gt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=z(__dirname,`..`,`..`,`package.json`);P(t)&&(e.okVersion=JSON.parse(I(t,`utf8`)).version)}catch{}return e}function Xi(e){if(!P(Ki))return{files:[],dir:Ki};let t=$t(Ki).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>z(Ki,e));if(e&&t.length>0){let n=t.filter(t=>{try{return I(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:Ki}}function Zi(e){let t=z(e,`.ok`,`local`);return P(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}function Qi(e){let t=z(e,`.ok`,`local`,`logs`);return P(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}async function $i(t){let n=Au();F(qi,{recursive:!0});let r=z(qi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Yi(),{files:a}=Xi(t.projectSlug),{files:o}=Zi(t.cwd),{files:s}=Qi(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CQSNnbvt.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Gi(I(e,`utf8`)),i=`logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of o)try{let{redacted:t,patterns:n,lineCount:r}=Gi(I(e,`utf8`)),i=`lockdir/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of s)try{let{redacted:t,patterns:n,lineCount:r}=Gi(I(e,`utf8`)),i=`local-logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}let f=JSON.stringify(i,null,2);d.addBuffer(Buffer.from(f,`utf8`),`sysinfo.json`),l.push(`sysinfo.json`);let p={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:t.projectSlug,files:l,redactions:c,sysinfo:i};d.addBuffer(Buffer.from(JSON.stringify(p,null,2),`utf8`),`MANIFEST.json`);let m=c.reduce((e,t)=>e+t.lineCount,0),h=[`# Bug Report Bundle`,``,`Generated: ${p.generatedAt}`,`Project: ${t.projectSlug??`(unscoped)`}`,`Discipline version: ${p.disciplineVersion}`,``,`## Contents`,``,...l.map(e=>`- ${e}`),``,`## Privacy`,``,`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Wi.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
|
|
20
20
|
`);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Xt(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&&pn()===`darwin`)try{M(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function ea(){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=Ji(t);try{await $i({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 ta(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 na(e){let t=e.inspect??(t=>Tt(e.lockDir,t)),n=e.unlink??(e=>rn(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=ta(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 ra(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),na({lockDir:le(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function ia(e,t,n={},r=ne){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 aa(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 oa=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function sa(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 oa)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function ca(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t.GIT_TERMINAL_PROMPT=`0`,t.LANG=`C`,t.LC_ALL=`C`,t}function la(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const ua=r;async function da(e){try{return await e.clone(la(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&ua(t))return e.onFallback(e.branch),await e.clone(la(null)),{fellBack:!0};throw t}}function fa(e,t,n){return e===`https`&&t===`github.com`&&n}async function pa(e,t,n,r=process.cwd()){let i=Ot(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?B(r,t.dir):B(r,i.name);if(P(a)&&$t(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=ee(),s=i.protocol===`https`&&i.hostname===`github.com`?await aa(i.owner,i.name):!1,c=fa(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await ia(i.hostname,o,{}),l=ca(),u=T({baseDir:r,config:c.credentialArgs.length>=2?[c.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env(l),d=-1;u.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
21
21
|
`)){let n=sa(e);n&&n.pct!==d&&(d=n.pct,q(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await da({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>u.clone(e,a,t),onFallback:e=>{q(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
|
|
22
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
22
|
+
`);try{let{runInit:e}=await import(`./init-CmEFD2yV.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ma(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ma(e){let t=vt(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function ha(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 pa(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DQUEhZj2.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?q(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var ga=c();const _a=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...s.map(e=>e.path)];function va(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Pt;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 ya(e){let t=(0,ga.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of _a)t.hasIn(e)&&n.push(e.join(`.`));return n}function ba(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xa(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=ba(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Sa(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,o=e.cwd??process.cwd(),s=e.writeConfigPatchFn??re,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:De(`project`,o,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:De(`user`,o,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ya(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:o,scope:t,patch:xa(_a.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:a(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(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:l,ok:u}}function Ca(){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(()=>{va({}).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 Sa({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var wa=e(et(),1),J=e(Ht(),1);const Ta=new Set([`doc.name`]);function Ea(e){return`doc:${xn(`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 Oa(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Ea(e);return t.originalToHashed.set(e,r),Da(t,e,r),r}function ka(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function Aa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ja(e,t){if(typeof e==`string`)return ka(e,t.contentDir);if(Array.isArray(e))return e.map(e=>ja(e,t));if(!Aa(e))return e;let n=typeof e.key==`string`&&Ta.has(e.key)&&Aa(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`&&Aa(a)){let e=Oa(n,t);r[i]={...a,stringValue:e}}else Ta.has(i)&&typeof a==`string`?r[i]=Oa(a,t):r[i]=ja(a,t);return r}function Ma(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 Na(e,t){let n=I(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
23
23
|
`),i=n.split(`
|
|
24
24
|
`),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=ja(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}L(e,r?`${a.join(`
|
|
25
25
|
`)}\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 Go(e,t,n,r,i){let a=Wo(e,t,z(r,`cpu.cpuprofile`)),o=!1,s=M(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{tn(z(a,`..`),{recursive:!0,force:!0})}catch{}return o}function Ko(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 qo(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??wt,s=t.inspect??Tt,c=t.resolveCommand??Dt,l=t.resolveUsage??jt,u=t.collectLsofFn??Vo,d=t.getEndpoints??Uo,f=t.profiler??Go,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(J.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let b=new Date().toISOString().replace(/[:.]/g,`-`),x=e.output?e.output:v?z(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):z(process.cwd(),`ok-diagnose-${n}-${b}`);try{F(x,{recursive:!0})}catch(e){a(J.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(J.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{L(z(x,e),t),a(` wrote ${e}`)},C=c(n),ee=l(n);S(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:C,usage:ee,lockInfo:y},null,2)),a(` sampling lsof`);let w=u(n);if(w&&S(`lsof.txt`,w),!i){let e=w?Ho(w).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(J.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){S(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,x,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(J.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
|
|
53
|
-
`)}\n`);try{S(`stacks.txt`,Ko(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Jo(e){let t=kn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Yo(e){let t=Zt(z(hn(),`ok-bundle-process-`));return await qo({pid:e,output:t}),t}function Xo(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Zo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Qo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Xo(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 $o(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Jo,i=t.runProcessDiagnose??Yo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=on(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await ho({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),Qo(n,c,o),e.yes!==!0&&!Zo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await go({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{tn(s,{recursive:!0,force:!0})}catch{}}}function es(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await qo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(zo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-
|
|
53
|
+
`)}\n`);try{S(`stacks.txt`,Ko(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Jo(e){let t=kn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Yo(e){let t=Zt(z(hn(),`ok-bundle-process-`));return await qo({pid:e,output:t}),t}function Xo(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Zo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function Qo(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Xo(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 $o(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Jo,i=t.runProcessDiagnose??Yo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=on(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await ho({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),Qo(n,c,o),e.yes!==!0&&!Zo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await go({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{tn(s,{recursive:!0,force:!0})}catch{}}}function es(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await qo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(zo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-BMjYHLZp.mjs`),{resolveContentDir:r}=await import(`./dist-6j4x3nmy.mjs`),i=process.cwd(),{config:a}=n(i);await $o({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function ts(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Lr({message:`Enter OpenAI embeddings API key:`})).trim()}function ns(e){return ae(e)}async function rs(){return(await Ae()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function is(e){try{let t=h(le(e));if(!t||t.port<=0||!b(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function as(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await ts();if(!e){process.stderr.write(`No key provided.
|
|
54
54
|
`),process.exitCode=1;return}await He().set(e),process.stderr.write(`✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).
|
|
55
55
|
Now enable it per project — the easiest path is OK Desktop → Settings → This
|
|
56
56
|
project → Search (a toggle with an egress-confirmation prompt), or run
|
|
@@ -70,7 +70,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
|
|
|
70
70
|
`).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function xl(e){let t=B(e);for(;;){if(ve(t))return t;let n=on(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 \`${o}\`).`);t=n}}function Sl(e){try{let t=new URL(e);return t.protocol===`file:`?yn(t):void 0}catch{return}}async function Cl(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=Sl(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function wl(e,t,n,r=xl){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function Tl(e){let t=process.stderr,n=e.spawnTimeoutMs??rl(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Ft({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new xe({name:oe,version:g});Se(a);let o=Sn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=be(e),r=s.current,i=ws({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>hl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Cl({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d,f=!1,p=async e=>{if(f)return;f=!0;let n=await bl(e);if(n<=1){f=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${n} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{t.write(`[mcp] ${r}\n`),await a.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},m=async e=>{let t=await wl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&p(t.projectDir),t.projectDir},h=async e=>{let t=await wl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)return;t.viaRootGuess&&p(t.projectDir);let a=t.projectDir,o=await i(a),s=await ml({lockDir:be(a),contentDir:$e(o,a),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(a),s.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Ie(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},me(a,{serverUrl:h,resolveCwd:m,config:i,identityRef:s});let _=new Os,v=!1,y,b,x=async()=>{if(v)return;v=!0,y?.stop(),b?.stop();for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),_.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(_),t.write(`[mcp] global stdio server ready (per-call project routing)
|
|
71
71
|
`);let S=!1,C=()=>{S||(S=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
72
72
|
`),process.exit(1)},5e3).unref(),x().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,C),process.once(`SIGTERM`,C),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
|
|
73
|
-
`),C()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),C()}),b=Ms({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),C()}}),Ns({log:e=>t.write(`${e}\n`),transport:_,process,stdin:process.stdin}),process.platform===`darwin`){let e=js(vl,{realpathSync:en,statInoSync:e=>nn(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;y=As({detect:()=>ks({bundleAnchorPath:vl,currentInode:r,platform:process.platform,realpath:en,statInode:e=>nn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${g} — exiting for host respawn\n`),C()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function El(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=rl(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await _l({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=xs(process.env,i,process.platform);if(a.proxy){let e=bs(process.platform,fn(),{existsSync:P});if(e===null)Ss({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Cs({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Ss({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`;Ss({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Tl({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 Dl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Ol(e=()=>Bt(Rt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ce({lockDir:le(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Dl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function kl(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Ne(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Ke(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Al(){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=kl(e,t,Ol())})}function jl(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-
|
|
73
|
+
`),C()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),C()}),b=Ms({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),C()}}),Ns({log:e=>t.write(`${e}\n`),transport:_,process,stdin:process.stdin}),process.platform===`darwin`){let e=js(vl,{realpathSync:en,statInoSync:e=>nn(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;y=As({detect:()=>ks({bundleAnchorPath:vl,currentInode:r,platform:process.platform,realpath:en,statInode:e=>nn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${g} — exiting for host respawn\n`),C()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function El(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=rl(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await _l({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=xs(process.env,i,process.platform);if(a.proxy){let e=bs(process.platform,fn(),{existsSync:P});if(e===null)Ss({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Cs({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Ss({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`;Ss({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Tl({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 Dl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Ol(e=()=>Bt(Rt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ce({lockDir:le(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Dl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function kl(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Ne(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Ke(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Al(){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=kl(e,t,Ol())})}function jl(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-DVsrv_hV.mjs`),r=e(),i=process.cwd(),a=$e(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ml(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(le(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...l({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}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=T({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await a.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await a.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
74
74
|
`)),Z(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 Ml({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 Pl(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ml({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 Fl(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ml({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 Il(e){return typeof e==`string`&&_e.includes(e)}async function Ll(e={}){let t=B(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!Ee[n])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${n}". Available: ${_e.join(`, `)}`,exitCode:1};let r;try{r=await Je({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ge?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=Ee[n].name;return{status:`no-op`,message:`${O(`Your ${e} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${j(`Plan (dry-run — no changes made):`)}\n\n${zl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await Bl(`${j(`Plan:`)}\n\n${zl(r,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:r,exitCode:0};let i=await ze(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${i.applied} entries, ${A(String(i.errors.length))} error(s):`,...e].join(`
|
|
75
75
|
`),plan:r,exitCode:1}}let a=Ee[n].name,o=i.packSkillsInstalled.length>0?`\n${D(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${O(`✓ Seeded ${a}`)} ${D(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function Rl(){let e=[j(`Available packs:`)];for(let t of _e){let n=Ee[t];e.push(` ${O(t)} ${D(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
|
76
76
|
`)}function zl(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(j(`Folders to create:`));for(let e of r)n.push(` ${O(`+`)} ${E(sn(t,B(t,e.path))||e.path)}${D(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(j(`Files to create:`));for(let e of i)n.push(` ${O(`+`)} ${E(sn(t,B(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(D(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${D(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(A(`Warnings:`));for(let t of e.warnings)n.push(` ${A(`!`)} ${t}`)}return n.join(`
|
|
@@ -79,7 +79,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
|
|
|
79
79
|
`);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 Wl(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 Ul(t,await e())})}async function Gl(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 Kl(e,t){let{host:n,json:r}=e;H(n);let i=await Ni(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 Gl(new K({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function ql(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 Kl(t,await e())})}function Jl(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(`
|
|
80
80
|
`)??``}\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 Yl(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 Xl(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 Zl(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function Ql(e){return T({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function $l(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const eu={ensureOkScaffold:e=>{pe(e)},gitFactory:Ql};async function tu(e){let t={...eu,...e.deps},n=B(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await Zl(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:Jl(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!P(z(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await Yl({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(Jl(t)===`name-conflict`){let t=await Xl(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:Jl(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=$l(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function nu(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 ru(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;H(n);let l=await Ni(n,t);if(l==null){nu(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new K({auth:l,...u?{baseUrl:u}:{}});try{Gt(`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`}nu(c,await tu({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function iu(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'
|
|
81
81
|
`),process.exit(1)),await ru(t,await e())})}function au(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>te();return e.addCommand(ql(n)),e.addCommand(Wl(n)),e.addCommand(iu(n)),e}function ou(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=gt(t),r=ot(t,at(t));if(r.kind===`no-exclude`){su(e.json,t,r.reason);return}let i=gt(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${E(`Sharing mode is already`)} ${j(`shared`)} ${E(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${j(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function su(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function cu(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=gt(t),r=[...ht(t)],i=xt(t,at(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: ${lu(n)}`),a.push(``),a.push(`Excluded from git via ${j(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${E(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
|
|
82
|
-
`)}\n`)})}function lu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function uu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=vt(t,at(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`){du(e.json,t,n.reason);return}let r=gt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function du(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function fu(){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(ou()),e.addCommand(uu()),e.addCommand(cu()),e}const pu=new Set([`--cwd`,`--log-level`]);function mu(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(`-`)){pu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function hu(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 gu(e){return/\.(md|mdx)$/i.test(e)}function _u(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function vu(e=()=>Bt(Rt())){return{prepare:Qe,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:_u(process.env)}).unref()},runProjectOpen:(e,t)=>kl(e,{project:t},Ol()),runBrowserOpen:e=>xu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function yu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Le||e instanceof Ue||e instanceof je)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 bu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function xu(e){let{createEphemeralProjectDir:t}=await import(`./dist-6j4x3nmy.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-
|
|
82
|
+
`)}\n`)})}function lu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function uu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=vt(t,at(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`){du(e.json,t,n.reason);return}let r=gt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function du(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function fu(){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(ou()),e.addCommand(uu()),e.addCommand(cu()),e}const pu=new Set([`--cwd`,`--log-level`]);function mu(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(`-`)){pu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function hu(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 gu(e){return/\.(md|mdx)$/i.test(e)}function _u(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function vu(e=()=>Bt(Rt())){return{prepare:Qe,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:_u(process.env)}).unref()},runProjectOpen:(e,t)=>kl(e,{project:t},Ol()),runBrowserOpen:e=>xu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function yu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Le||e instanceof Ue||e instanceof je)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 bu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function xu(e){let{createEphemeralProjectDir:t}=await import(`./dist-6j4x3nmy.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-DQUEhZj2.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=bu();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 bn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Ke(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
|
|
83
83
|
`),a(m),await new Promise(()=>{})}function Su(e,t){return{server:Cu(`server`,e),ui:Cu(`ui`,t)}}function Cu(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 wu(e){return`${Tu(e.server)}\n${Tu(e.ui)}`}function Tu(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 Eu(e){let t=e.inspect??(t=>Tt(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Su(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(wu(r)),r}function Du(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(),Eu({lockDir:le(process.cwd()),json:t.json===!0})})}function Ou(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(`
|
|
84
84
|
`)}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 $,ku;function Au(){return ku}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Ou(Mt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=kt(n,process.cwd());r!==null&&(Ct(process.cwd()),process.chdir(r),console.error(`[ok] Using Open Knowledge project at ${r}`));let{config:i}=Pt(r??t);$=i;let a=e.args?.[0]??e.name()??`cli`;ku=Te({name:`cli`,project:i.project?.name??void 0}),ku.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Bt(Rt()).available){It({spawn:M});return}await zt($,{})});const ju=Lt(()=>$);Q.addCommand(ju);const Mu=El(()=>$);Q.addCommand(Mu),Q.addCommand(yt()),Q.addCommand(Vl()),Q.addCommand(_s()),Q.addCommand(Ut());const Nu=jl(()=>$);Q.addCommand(Nu);const Pu=bt(()=>$);Q.addCommand(Pu),Q.addCommand(Al()),Q.addCommand(Et(()=>$)),Q.addCommand(ra(()=>$)),Q.addCommand(Du(()=>$)),Q.addCommand(At()),Q.addCommand(es()),Q.addCommand(ea()),Q.addCommand(Ca()),Q.addCommand(Hi(Au)),Q.addCommand(ls()),Q.addCommand(ha(()=>$)),Q.addCommand(Nl(()=>$)),Q.addCommand(Fl(()=>$)),Q.addCommand(Pl(()=>$)),Q.addCommand(au()),Q.addCommand(fu()),Q.addHelpText(`after`,`
|
|
85
85
|
Examples:
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./gh-detect-wbzQ2Z5B.mjs";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,b as d,d as f,g as p,h as m,i as h,j as g,k as _,o as v,r as y,s as b,t as x,w as S,x as C,y as w}from"./init-
|
|
1
|
+
import{i as e,r as t,t as n}from"./gh-detect-wbzQ2Z5B.mjs";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,b as d,d as f,g as p,h as m,i as h,j as g,k as _,o as v,r as y,s as b,t as x,w as S,x as C,y as w}from"./init-Bd49mCW9.mjs";import{d as T,f as E,m as D,n as O,p as k,r as A,t as j}from"./src-6vQuUOgy.mjs";import{n as M}from"./loader-yyLYaVhN.mjs";import{n as N}from"./preview-DF7SCtlt.mjs";import{n as P,t as F}from"./mcp-migrate-event-D0NrGjvc.mjs";export{a as ALL_EDITOR_IDS,s as EDITOR_LABELS,_ as EDITOR_TARGETS,x as LAUNCH_CONFIG_NAME,y as LAUNCH_UI_CHAIN_SENTINEL,h as LAUNCH_UI_CHAIN_V1,d as addOkPathsToGitExclude,r as buildManagedServerEntry,F as buildMcpConfigMigrateEvent,v as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,b as detectInstalledEditors,C as formatTrackedRemediation,c as getExcludedOkPaths,i as getOkArtifactPaths,g as isEntryUpToDate,M as loadConfig,e as makeLazyProbeTokenStore,T as parseGitHubBlobUrl,E as parseGitHubShareUrl,k as parseGitHubTreeUrl,D as parseGitUrl,N as previewContent,S as probeTrackedOkPaths,f as readExistingMcpEntry,l as readSharingMode,o as removeOkPathsFromGitExclude,w as resolveProjectRoot,A as runStop,m as scaffoldLaunchJson,P as truncatePriorEntry,O as validateLocalFolderForShare,p as writeEditorMcpConfig,j as writeProjectAiIntegrations,u as writeUserMcpConfigs};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{r,t as i}from"./esm-BLMtE3s6.mjs";import{Ft as a,St as o,kr as s,ln as c,v as l,xt as u,y as d}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{F as f,Gn as p,Ln as m,Qi as h,Qn as g,Un as _,W as v,Wn as y,Yi as b,Yn as x,fn as S,on as C,ra as w,zi as ee}from"./dist-Dcg4smYg.mjs";import"./constants-zR9K6MQx.mjs";import{t as T}from"./is-object-Cie0xXKD.mjs";import{i as E,o as D,r as O,s as k,t as A}from"./colors-8SzMRIVy.mjs";import{t as te}from"./preview-CNJw1WeR.mjs";import{n as ne,t as j}from"./write-project-skill-C5HoLkCk.mjs";import{execFileSync as re}from"node:child_process";import{existsSync as M,mkdirSync as ie,readFileSync as N,realpathSync as ae,writeFileSync as P}from"node:fs";import F,{basename as I,dirname as L,isAbsolute as oe,join as R,posix as se,relative as z,resolve as ce,sep as le,win32 as ue}from"node:path";import B from"node:process";import{homedir as V}from"node:os";import{randomUUID as de}from"node:crypto";import{stripVTControlCharacters as fe,styleText as H}from"node:util";import{AsyncLocalStorage as pe,AsyncResource as me}from"node:async_hooks";import{createServer as he,request as ge}from"node:http";import*as _e from"node:readline";import{connect as ve}from"node:net";function ye(){return B.platform.startsWith(`win`)?!!B.env.CI||!!B.env.WT_SESSION||!!B.env.TERMINUS_SUBLIME||B.env.ConEmuTask===`{cmd::Cmder}`||B.env.TERM_PROGRAM===`Terminus-Sublime`||B.env.TERM_PROGRAM===`vscode`||B.env.TERM===`xterm-256color`||B.env.TERM===`alacritty`||B.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:B.env.TERM!==`linux`}const be={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},xe={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},Se={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},Ce={...be,...xe},we={...be,...Se},U=ye()?Ce:we;Object.entries(xe);var Te=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Ee=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),De=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Oe=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,ke=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ae=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,je=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Me=/\t{1,1000}/y,Ne=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Pe=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Fe=/\p{M}+/gu,Ie={limit:1/0,ellipsis:``},Le=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Le(i,Ie,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Pe,l],[ke,0],[Ae,o],[Me,s],[Ne,c],[je,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Fe,``)){let t=e.codePointAt(0)||0;if(S=De(t)?2:Oe(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===je?Ee(e.slice(p,n.lastIndex)):n===Ne?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Re={limit:1/0,ellipsis:``,ellipsisWidth:0},W=(e,t={})=>Le(e,Re,t).width,ze=`]8;;`,Be=RegExp(`(?:\\[(?<code>\\d+)m|\\${ze}(?<uri>.*))`,`y`),Ve=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},He=e=>`[${e}m`,Ue=e=>`${ze}${e}`,We=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:W(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=W(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(ze,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ge=e=>{let t=e.split(` `),n=t.length;for(;n&&!W(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ke=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=W(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=W(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),We(s,r,t),c=W(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){We(s,r,t),c=W(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){We(s,r,t),c=W(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ge(e)));let l=s.join(`
|
|
1
|
+
import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{r,t as i}from"./esm-BLMtE3s6.mjs";import{Ft as a,St as o,kr as s,ln as c,v as l,xt as u,y as d}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{F as f,Gn as p,Ln as m,Qi as h,Qn as g,Un as _,W as v,Wn as y,Yi as b,Yn as x,fn as S,on as C,ra as w,zi as ee}from"./dist-Dcg4smYg.mjs";import"./constants-PrZJ-CTv.mjs";import{t as T}from"./is-object-Cie0xXKD.mjs";import{i as E,o as D,r as O,s as k,t as A}from"./colors-8SzMRIVy.mjs";import{t as te}from"./preview-DF7SCtlt.mjs";import{n as ne,t as j}from"./write-project-skill-C5HoLkCk.mjs";import{execFileSync as re}from"node:child_process";import{existsSync as M,mkdirSync as ie,readFileSync as N,realpathSync as ae,writeFileSync as P}from"node:fs";import F,{basename as I,dirname as L,isAbsolute as oe,join as R,posix as se,relative as z,resolve as ce,sep as le,win32 as ue}from"node:path";import B from"node:process";import{homedir as V}from"node:os";import{randomUUID as de}from"node:crypto";import{stripVTControlCharacters as fe,styleText as H}from"node:util";import{AsyncLocalStorage as pe,AsyncResource as me}from"node:async_hooks";import{createServer as he,request as ge}from"node:http";import*as _e from"node:readline";import{connect as ve}from"node:net";function ye(){return B.platform.startsWith(`win`)?!!B.env.CI||!!B.env.WT_SESSION||!!B.env.TERMINUS_SUBLIME||B.env.ConEmuTask===`{cmd::Cmder}`||B.env.TERM_PROGRAM===`Terminus-Sublime`||B.env.TERM_PROGRAM===`vscode`||B.env.TERM===`xterm-256color`||B.env.TERM===`alacritty`||B.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:B.env.TERM!==`linux`}const be={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},xe={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},Se={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},Ce={...be,...xe},we={...be,...Se},U=ye()?Ce:we;Object.entries(xe);var Te=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Ee=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),De=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Oe=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,ke=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ae=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,je=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Me=/\t{1,1000}/y,Ne=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Pe=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Fe=/\p{M}+/gu,Ie={limit:1/0,ellipsis:``},Le=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Le(i,Ie,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Pe,l],[ke,0],[Ae,o],[Me,s],[Ne,c],[je,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Fe,``)){let t=e.codePointAt(0)||0;if(S=De(t)?2:Oe(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===je?Ee(e.slice(p,n.lastIndex)):n===Ne?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Re={limit:1/0,ellipsis:``,ellipsisWidth:0},W=(e,t={})=>Le(e,Re,t).width,ze=`]8;;`,Be=RegExp(`(?:\\[(?<code>\\d+)m|\\${ze}(?<uri>.*))`,`y`),Ve=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},He=e=>`[${e}m`,Ue=e=>`${ze}${e}`,We=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:W(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=W(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(ze,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ge=e=>{let t=e.split(` `),n=t.length;for(;n&&!W(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ke=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=W(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=W(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),We(s,r,t),c=W(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){We(s,r,t),c=W(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){We(s,r,t),c=W(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ge(e)));let l=s.join(`
|
|
2
2
|
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){Be.lastIndex=e+1;let t=Be.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
3
3
|
`){a&&(r+=Ue(``));let e=i?Ve(i):void 0;i&&e&&(r+=He(e))}else t===`
|
|
4
4
|
`&&(i&&Ve(i)&&(r+=He(i)),a&&(r+=Ue(a)))}return r},qe=/\r?\n/;function Je(e,t,n){return String(e).normalize().split(qe).map(e=>Ke(e,t,n)).join(`
|
|
@@ -310,6 +310,6 @@ UIPORT="\${PORT:-${Ui}}"
|
|
|
310
310
|
unset PORT
|
|
311
311
|
exec node "${xt()}" start --ui-port "$UIPORT"`],port:Ui,autoPort:!0}:{name:ca,runtimeExecutable:`/bin/sh`,runtimeArgs:[`-l`,`-c`,da],port:Ui,autoPort:!0};try{if(j(n,e),!M(n))return ie(L(n),{recursive:!0}),P(n,`${JSON.stringify({version:sa,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=N(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!T(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>T(e)&&e.name===`open-knowledge-ui`);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??sa,configurations:a};return P(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function pa(e,t,n){try{return M(e.detectPath?.(t,n)??L(e.configPath(t,n)))}catch{return!1}}function ma(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!pa(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{j(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{ie(L(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let c,l;try{h(`${o}.lock`,()=>{let t=e.format===`toml`?Qi(o):Zi(o),n=t[e.topLevelKey]??{};c=n[a];let r={...t,[e.topLevelKey]:{...n,[a]:s}};e.format===`toml`?ea(o,r):$i(o,r)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){l=e instanceof Error?e:Error(String(e))}return l?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:l.message,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:c===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function ha(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!M(n)))return{editorId:e.id,label:e.label,path:n}}async function ga(e){let t=kt(e.editors),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>ma(t,``,n,e.home))}function _a(e,t,n,r){let i=va(e,t,n,r);return i.kind===`present`?i.entry:null}function va(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!M(i))return{kind:`absent`};let a;try{a=N(i,`utf-8`)}catch(e){return{kind:`corrupt`,error:e instanceof Error?e.message:String(e)}}if(a.trim()===``)return{kind:`corrupt`,error:`file is empty`};let o;try{o=e.format===`toml`?Qi(i):Zi(i)}catch(e){return{kind:`corrupt`,error:e instanceof Error?e.message:String(e)}}let s=o[e.topLevelKey];if(!T(s))return{kind:`no-entry`};let c=s[e.serverName(t)];return T(c)?{kind:`present`,entry:c}:{kind:`no-entry`}}async function ya(e={}){let t=ce(e.cwd??process.cwd()),n=Mi(t,{homeDir:e.home}),r=n.projectRoot,i=!M(R(r,`.ok`));n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&console.log(`[ok] Initialized OK at ${r} — opened parent of ${z(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await S(r),s;try{s=m(r,{contentDir:n.defaultContentDir})}catch(t){let n=G.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:o.didInit,rootGitignoreCreated:!1,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:n,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let c=!1;if(o.didInit)try{c=ee(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}let l=await ia({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),u=e.editors??Ca(r,e.home),d=e.editors??_t.filter(e=>G[e].projectConfigPath!==void 0),f=kt(u),p=kt(d),h=e.mcp===!1||l===null,g=Array.from(new Map([...f,...h?[]:p].map(e=>[e.id,e])).values()),v=f.filter(t=>pa(t,r,e.home)),y=[],b=[],x=new Set;for(let t of g){if(h){let n=``;try{n=t.configPath(r,e.home)}catch{}y.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(ta(l)&&f.includes(t)&&y.push(ma(t,r,a,e.home)),na(l)&&p.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=ma(t,r,a,e.home,n);y.push(i),(i.action===`written`||i.action===`overwritten`)&&x.add(n)}}for(let e of p)e.projectSkillPath&&b.push(ne(e,r));let w=!h&&l!==null&&na(l)?p.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,T=h?[]:v.map(e=>ha(e,r)).filter(e=>e!==void 0).filter(e=>!x.has(e.path)),E=v.some(e=>e.id===`claude`)&&!h?fa(r,a):void 0,D=await(e.installUserSkill??_)({home:e.home}),O=C({home:e.home}),k=h?`skipped-flag`:`skipped-missing`,A=y.find(e=>e.editorId===`claude`)??y[0]??{action:k,configPath:G.claude.configPath(r,e.home)},te=await ba({projectRoot:r,desiredMode:await oa({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:s.created,contentUpdated:s.updated,contentSkipped:s.skipped,editors:y,projectSkills:b,legacyProjectConfigs:T,launchJson:E,skillInstall:D,didGitInit:o.didInit,rootGitignoreCreated:c,claudeDesktopDetected:O,mcpAction:A.action,mcpPath:A.configPath,mcpError:`error`in A?A.error:void 0,projectScopeUnsupportedLabels:w,sharing:te}}async function ba(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=Nt(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=At(t);if(n===`local-only`){let e=jt(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:xa(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=Mt(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:xa(t,o,`remove`)}function xa(e,t,n){let r=Nt(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:[]}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function Sa(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?z(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let c=R(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(A(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(A(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(A(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(A(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(A(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?z(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${D(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${D(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${O(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(A(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?z(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${D(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${D(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${O(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${z(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(A(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${D(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${D(`already installed at current version`)}`);break;case`failed`:n.push(` ${k(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${k(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${A(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(te(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...Ta(e.sharing,t)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${D(`✓`)} ${A(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${E(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${E(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${E(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${E(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${E(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
|
|
312
312
|
`)}function Ca(e,t){let n=[];for(let r of _t)pa(G[r],e,t)&&n.push(r);return n}function wa(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new r(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new r(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r;try{r=await ya({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n})}catch(e){if(e instanceof v){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
313
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
313
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DVsrv_hV.mjs`),{loadConfig:t}=await import(`./loader-BMjYHLZp.mjs`),{resolveContentDir:n}=await import(`./dist-6j4x3nmy.mjs`),{config:i}=t(r.projectRoot),a=n(i,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:a})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Sa(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}function Ta(e,t){let n=[];switch(e.kind){case`applied`:return n.push(A(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?n.push(` ${D(`local-only`)} — appended ${e.appended.length} path(s) to ${A(`${t}/.git/info/exclude`)} (per-clone, not committed).`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${D(`local-only`)} — already excluded; nothing to do.`):n.push(` ${D(`local-only`)}`):e.action===`removed`?n.push(` ${D(`shared`)} — removed OK paths from ${A(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${D(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(k(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
314
314
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${E(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(k(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${E(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${E(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(k(`Sharing mode unavailable: ${e.reason}.`));return n}}export{St as A,Je as B,At as C,_t as D,Mt as E,mt as F,U as H,ft as I,gt as L,pt as M,ut as N,vt as O,dt as P,st as R,Pt as S,Nt as T,Te as V,ga as _,ba as a,jt as b,Sa as c,_a as d,ia as f,ma as g,fa as h,da as i,bt as j,G as k,Ta as l,ya as m,la as n,va as o,oa as p,ua as r,Ca as s,ca as t,wa as u,Yi as v,Ft as w,It as x,Mi as y,Ye as z};
|
|
315
|
-
//# sourceMappingURL=init-
|
|
315
|
+
//# sourceMappingURL=init-Bd49mCW9.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as e}from"./init-Bd49mCW9.mjs";export{e as runInit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-yyLYaVhN.mjs";export{e as loadConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ii as e,Li as t,Oa as n,zi as r}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{Xi as i,Zi as a,m as o}from"./dist-Dcg4smYg.mjs";import{t as s}from"./constants-
|
|
1
|
+
import{Ii as e,Li as t,Oa as n,zi as r}from"./server-lock-BpjJj3OD-DlYx_Xz-.mjs";import{Xi as i,Zi as a,m as o}from"./dist-Dcg4smYg.mjs";import{t as s}from"./constants-PrZJ-CTv.mjs";import{t as c}from"./is-object-Cie0xXKD.mjs";import{existsSync as l,readFileSync as u}from"node:fs";import{resolve as d}from"node:path";import{realpath as f}from"node:fs/promises";async function p(e){let t=d(e);try{return await f(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var m=n();function h(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];c(a)&&c(i)?n[r]=h(i,a):a!==void 0&&(n[r]=a)}return n}function g(e){if(!l(e))return{value:null,path:e,source:null,doc:null};let t;try{t=u(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,m.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return c(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function _(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=r({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...i,source:e}}return i})}function v(n){let r=n??process.cwd(),c=[],l=a(`user`,r),u=i({absPath:l}),f={};u.valid&&u.source!==void 0?(f=h(f,u.value),c.push(l)):u.valid;let p=d(r,`.ok`,s),m=g(p);if(m.value!==null){let n=e({value:m.value,file:m.path,source:m.source,doc:m.doc});if(n.length>0)throw Error(n.map(t).join(`
|
|
2
2
|
|
|
3
3
|
`));f=h(f,m.value),c.push(p)}let v=o.safeParse(f);if(!v.success){let e={code:`SCHEMA_INVALID`,issues:_(v.error.issues,m)};throw Error(t(e))}return{config:v.data,sources:c}}function y(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??v,r=new Map,i=new Map,a=p(e.startupCwd);return async o=>{let s=await p(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{v as n,y as t};
|
|
4
|
-
//# sourceMappingURL=loader-
|
|
4
|
+
//# sourceMappingURL=loader-yyLYaVhN.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Gt as e}from"./dist-Dcg4smYg.mjs";import"./constants-
|
|
1
|
+
import{Gt as e}from"./dist-Dcg4smYg.mjs";import"./constants-PrZJ-CTv.mjs";import{existsSync as t,lstatSync as n,readdirSync as r,realpathSync as i,statSync as a}from"node:fs";import{join as o,relative as s}from"node:path";function c(t){let{projectDir:c,contentDir:l,sampleCap:u=5}=t,d=[],f=[];try{n(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=r(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${s(l,e)||`.`}: ${n}`);return}for(let n of t){let t=o(e,n.name);if(n.isSymbolicLink()){let e;try{e=i(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${s(l,t)}`):d.push(`cannot resolve symlink ${s(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=a(e)}catch{continue}if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,n){let r=[],i=s(n,e.contentDir),a=i===``?`./`:`./${i}`;if(r.push(`Content:`),r.push(` Found ${e.totalCount} markdown files in ${a}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;r.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)r.push(` Warning: ${t}`);return r.push(``),t(o(n,`.ok`,`config.yml`))?(r.push(` To adjust scope, add patterns to .okignore at the project root.`),r.push(` To change the content root, edit .ok/config.yml → content.dir.`)):r.push(" Run `open-knowledge init` to scaffold config + .okignore."),r.push(``),r.push(` Re-check anytime: open-knowledge preview`),r.join(`
|
|
2
2
|
`)}export{c as n,l as t};
|
|
3
|
-
//# sourceMappingURL=preview-
|
|
3
|
+
//# sourceMappingURL=preview-DF7SCtlt.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-DF7SCtlt.mjs";export{t as formatPreviewBlock,e as previewContent};
|