@inkeep/open-knowledge 0.5.0-beta.44 → 0.5.0-beta.45
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/open-knowledge/SKILL.md +1 -1
- package/dist/cli.mjs +4 -4
- package/dist/constants-CvW406ds.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/init-BTwDMDdc.mjs +1 -0
- package/dist/{init-CzIlOXY5.mjs → init-DqApv-bY.mjs} +4 -4
- package/dist/loader-CuPkY1R-.mjs +1 -0
- package/dist/{loader-B93v7E2S.mjs → loader-DXesUuxk.mjs} +2 -2
- package/dist/{preview-fcmKJ-7t.mjs → preview-CGp3adCc.mjs} +2 -2
- package/dist/preview-eIL7AIMY.mjs +1 -0
- package/dist/{repair-launch-json-CL8XKjlC.mjs → repair-launch-json-D5A35XkF.mjs} +2 -2
- package/dist/{repair-mcp-configs-BFieSr-Q.mjs → repair-mcp-configs-BPXNDxGY.mjs} +2 -2
- package/dist/{src-DPfUVBkb.mjs → src-BUH_zaQF.mjs} +2 -2
- package/dist/{start-Pye6UK9z.mjs → start-CKo41lFY.mjs} +2 -2
- package/dist/start-D3m3CmFc.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-SS3E-YX9.mjs +0 -2
- package/dist/init-CXHjEcRB.mjs +0 -1
- package/dist/loader-BylDL0Yu.mjs +0 -1
- package/dist/preview-BD6NhOot.mjs +0 -1
- package/dist/start-DOTmfJ-6.mjs +0 -1
|
@@ -3,7 +3,7 @@ name: open-knowledge
|
|
|
3
3
|
description: "MUST invoke when the project contains a .ok/ directory — before any read or edit of .md / .mdx files, any mcp__open-knowledge__ tool call, and any write_document / edit_document. Skip if no .ok/ — not an Open Knowledge project. Carries preview-attach (open preview browser at session start; one-shot on `action: attach-preview-once`; surface to user on `action: start-ui` when no UI is running), STOP rules for native Read/Grep/Edit on in-scope markdown, grounding rules (every factual claim needs a source), standard markdown linking with get_dead_links verification, image sourcing + alt-text + source-citation rules, folder-first organization with opt-in nested .ok/ frontmatter + templates, and the anti-pattern table."
|
|
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.5.0-beta.
|
|
6
|
+
version: "0.5.0-beta.45"
|
|
7
7
|
author: "Inkeep"
|
|
8
8
|
repository: "https://github.com/inkeep/open-knowledge"
|
|
9
9
|
---
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Ai as n,B as r,Ci as i,D as a,Di as o,Dn as s,E as c,Ei as l,Gn as u,Gr as d,Gt as f,Hr as p,Jn as m,Kr as h,Mi as g,Oi as _,Si as v,Ti as y,U as b,Ur as x,Wr as S,Xr as ee,Yr as te,Z as ne,bi as re,cr as ie,it as ae,ji as oe,ki as se,m as ce,nn as le,nt as ue,pi as de,pn as fe,qr as pe,vi as me,wi as he,xi as ge,z as _e,zn as ve}from"./dist-CQVP3NVF.mjs";import{n as ye,r as be,t as C}from"./dist-bundle-BSdjl7Rj.mjs";import{C as xe,D as Se,E as Ce,O as we,S as Te,T as Ee,a as De,b as Oe,f as ke,k as Ae,v as je,w as Me,x as Ne,y as Pe}from"./init-
|
|
2
|
+
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Ai as n,B as r,Ci as i,D as a,Di as o,Dn as s,E as c,Ei as l,Gn as u,Gr as d,Gt as f,Hr as p,Jn as m,Kr as h,Mi as g,Oi as _,Si as v,Ti as y,U as b,Ur as x,Wr as S,Xr as ee,Yr as te,Z as ne,bi as re,cr as ie,it as ae,ji as oe,ki as se,m as ce,nn as le,nt as ue,pi as de,pn as fe,qr as pe,vi as me,wi as he,xi as ge,z as _e,zn as ve}from"./dist-CQVP3NVF.mjs";import{n as ye,r as be,t as C}from"./dist-bundle-BSdjl7Rj.mjs";import{C as xe,D as Se,E as Ce,O as we,S as Te,T as Ee,a as De,b as Oe,f as ke,k as Ae,v as je,w as Me,x as Ne,y as Pe}from"./init-DqApv-bY.mjs";import{c as Fe,f as Ie,l as Le,n as Re,s as w}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as ze}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Be}from"./constants-CvW406ds.mjs";import{i as Ve}from"./src-BUH_zaQF.mjs";import{n as He,t as Ue}from"./loader-DXesUuxk.mjs";import{d as We,f as Ge,l as Ke,m as qe,p as Je,s as Ye}from"./start-CKo41lFY.mjs";import{c as Xe,i as T,n as E,o as D,r as O,s as Ze,t as k}from"./colors-BtKMHmBX.mjs";import{execFileSync as Qe,execSync as $e,spawn as et,spawnSync as A}from"node:child_process";import tt,{basename as nt,dirname as rt,isAbsolute as it,join as j,relative as at,resolve as M}from"node:path";import{closeSync as ot,existsSync as N,mkdirSync as st,mkdtempSync as ct,openSync as lt,readFileSync as P,readdirSync as ut,realpathSync as dt,rmSync as ft,statSync as pt,unlinkSync as mt,writeFileSync as ht}from"node:fs";import gt from"node:process";import{homedir as _t,hostname as vt,tmpdir as yt}from"node:os";import{fileURLToPath as bt}from"node:url";import{AsyncLocalStorage as xt,AsyncResource as St}from"node:async_hooks";import{stripVTControlCharacters as Ct,styleText as F}from"node:util";import*as wt from"node:readline";import{randomUUID as Tt}from"node:crypto";import{realpath as Et}from"node:fs/promises";import{setTimeout as Dt}from"node:timers/promises";import{createInterface as Ot}from"node:readline/promises";var kt=g();const At=`open-knowledge`;var jt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(At,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(At,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(At,e).deletePassword()}catch{}}},Mt=class{backend=`file`;authFile;constructor(e){this.authFile=e??j(_t(),`.ok`,`auth.yml`)}read(){if(!N(this.authFile))return{};try{return(0,kt.parse)(P(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=rt(this.authFile);N(t)||st(t,{recursive:!0,mode:448}),ht(this.authFile,(0,kt.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Nt(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(At,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
3
3
|
`),new jt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
|
|
4
4
|
`),new Mt(e)}}async function Pt(e,t){let n=[],r=new Mt(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(At,`__probe__`);let r=new jt;await r.get(e)!=null&&(await r.clear(e),n.push(`keychain`))}catch{}return{touched:n}}async function Ft(e,t,n){let r=It(await Lt(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function It(e){let t={};for(let n of e.split(`
|
|
5
5
|
`)){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 Lt(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 Rt(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Ft(process.stdin,process.stdout,t);process.exit(n)}),n}function zt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Bt(e,t,n){let r={baseUrl:zt(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ye(`${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 Vt(e){let t=e.request||C,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Bt(t,`POST /login/device/code`,n)}async function Ht(e){let t=await Bt(e.request||C,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ut(e,t.data.expires_in),n.refreshTokenExpiresAt=Ut(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ut(e,t){return new Date(e+t*1e3).toISOString()}async function Wt(e,t){let n=Gt(e,t.auth);if(n)return n;let{data:r}=await Vt({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await qt(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Gt(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 Kt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function qt(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Ht({...i,clientType:`oauth-app`}):await Ht({...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 Kt(r.interval),qt(e,t,n,r);if(a===`slow_down`)return await Kt(r.interval+7),qt(e,t,n,r);throw i}}async function Jt(e,t){return Wt(e,{auth:t})}async function Yt(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 Wt(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Xt=`0.0.0-development`;function Zt(e){let t=e.request||C.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Xt} ${be()}`}}),{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(Jt.bind(null,i),{hook:Yt.bind(null,i)})}async function Qt(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=Zt({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-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}const $t={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 en;(function(e){})(en||={});function tn(e){return n(re,e)}function nn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const rn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function I(e){let t=e.toLowerCase().replace(/:\d+$/,``);rn.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function an(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function on(e,t,n=Qt){let r=nn(),{host:i,json:a}=e;I(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?an(!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?an(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function sn(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await on(t,await e())})}const cn=e=>e.name===`enter`||e.name===`return`;var ln=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},un=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},dn=class extends Error{name=`ExitPromptError`},fn=class extends Error{name=`HookError`},pn=class extends Error{name=`ValidationError`};const mn=new xt;function hn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function gn(e,t){let n=hn(e);return mn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function L(){let e=mn.getStore();if(!e)throw new fn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function _n(){return L().rl}function vn(e){return St.bind((...t)=>{let n=L(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function yn(e){let t=L(),{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 bn(){L().handleChange()}const xn={queue(e){let t=L(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(_n());if(r!=null&&typeof r!=`function`)throw new pn(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=L();vn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=L();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Sn(e){return typeof e==`function`}function R(e){return yn(t=>{let n=St.bind(function(e){t.get()!==e&&(t.set(e),bn())});if(t.initialized)return[t.get(),n];let r=Sn(e)?e():e;return t.set(r),[r,n]})}function Cn(e,t){yn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&xn.queue(e),n.set(t)})}const wn={prefix:{idle:F(`blue`,`?`),done:F(`green`,Ae.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>F(`yellow`,e))},style:{answer:e=>F(`cyan`,e),message:e=>F(`bold`,e),error:e=>F(`red`,`> ${e}`),defaultAnswer:e=>F(`dim`,`(${e})`),help:e=>F(`dim`,e),highlight:e=>F(`cyan`,e),key:e=>F(`cyan`,F(`bold`,`<${e}>`))}};function Tn(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 En(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=Tn(n)&&Tn(r)?En(n,r):r}return t}function Dn(...e){return En(wn,...e.filter(e=>e!=null))}function On({status:e=`idle`,theme:t}){let[n,r]=R(!1),[i,a]=R(0),{prefix:o,spinner:s}=Dn(t);return Cn(()=>{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 kn(e){return R({current:e})[0]}function An(e){let t=kn(e);t.current=e,Cn(e=>{let n=!1,r=vn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var jn=e(we(),1);function Mn(e,t){return e.split(`
|
|
@@ -19,10 +19,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
|
|
|
19
19
|
`)}function Gr(){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async e=>{await Wr(e)})}async function Kr(e,t,n=Br){let r=n(e);if(r.available&&r.token)return{tier:`A`,token:r.token};let i=await t.get(e);return i==null?{tier:`none`}:{tier:i.gitProtocol===`ssh`?`C`:`B`,token:i.token}}async function qr(e,t){let{host:n,json:r}=e;I(n);let i=await Kr(n,t);i.tier===`none`&&(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new B({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,tier:i.tier,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
|
|
20
20
|
`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Jr(e){return new t(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await qr(t,await e())})}function Yr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>Nt();return e.addCommand(sn(n)),e.addCommand(Jr(n)),e.addCommand(Ur(n)),e.addCommand(Gr()),e.addCommand(Rr(n)),e.addCommand(Rt(n)),e}function V(e,t,n={}){let r=Le(e,t);if(!N(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(P(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Fe(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??w)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??vt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Xr(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 Zr(e){let t=e.inspect??(t=>V(e.lockDir,t)),n=e.unlink??(e=>mt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Xr(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 Qr(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Zr({lockDir:m(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function $r(e,t,n={},r=Br){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 ei(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 ti=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function ni(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 ti)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function H(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function ri(e,t,n){return e===`https`&&t===`github.com`&&n}async function ii(e,t,n,r=process.cwd()){let i=Ve(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?M(r,t.dir):M(r,i.name);if(N(a)&&ut(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Nt(),s=i.protocol===`https`&&i.hostname===`github.com`?await ei(i.owner,i.name):!1,c=ri(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await $r(i.hostname,o,{}),l=ze({baseDir:r,config:c.credentialArgs.length>=2?[c.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),u=-1;l.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
21
21
|
`)){let n=ni(e);n&&n.pct!==u&&(u=n.pct,H(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await l.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
|
|
22
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
22
|
+
`);try{let{runInit:e}=await import(`./init-BTwDMDdc.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?H(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ai(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ai(e){let t=j(e,`.git`,`info`,`exclude`);if(!N(t))return`no-exclude`;let n=P(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
|
|
23
23
|
`).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(ht(t,`${n}${n.length===0||n.endsWith(`
|
|
24
24
|
`)?``:`
|
|
25
|
-
`}.ok/\n`,`utf-8`),`appended`)}function oi(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).action(async(t,n,r)=>{let i=e();try{let a=await ii(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-
|
|
25
|
+
`}.ok/\n`,`utf-8`),`appended`)}function oi(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).action(async(t,n,r)=>{let i=e();try{let a=await ii(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-D3m3CmFc.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?H(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const si=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function ci(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??He;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 li(e){let t=(0,kt.parseDocument)(P(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 si)t.hasIn(e)&&n.push(e.join(`.`));return n}function ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function di(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=ui(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function fi(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??ee,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:te(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:te(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!N(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=li(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:di(si.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:de(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function pi(){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(()=>{ci({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await fi({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(Xe(),1);const W=2e3,mi=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/];function hi(e){return mi.some(t=>t.test(e))}function gi(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return it(e)?e:null}catch{return null}}function _i(e){let t=[];for(let n of e.split(`
|
|
26
26
|
`)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&hi(a)&&t.push({pid:o,command:a})}return t}function vi(e){let t=[],n=e.split(`
|
|
27
27
|
`);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.indexOf(` `);if(i===-1)continue;let a=r.slice(0,i),o=r.slice(i+1).trim(),s=Number.parseInt(a,10);!Number.isNaN(s)&&hi(o)&&t.push({pid:s,command:o})}return t}async function yi(){let e=A(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|--ok-lock-dir-b64=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:W});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=_i(t);if(n.length>0||t.trim()===``)return n}let t=A(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?[]:vi(t.stdout)}function bi(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=nt(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function xi(e){let t=A(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function Si(e){let t=A(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:W});if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}async function Ci(e){let t=A(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:W});if(t.error!=null)return null;let n=t.stdout??``;for(let e of n.split(`
|
|
28
28
|
`))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function wi(e){let t=[],n=e.split(`
|
|
@@ -59,7 +59,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
|
|
|
59
59
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
60
60
|
`&&r++}}return[t,n]}var mo=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=fo({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const ho={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Y=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},go=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Qi(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??ho}async _authThenStart(){if(!this._authProvider)throw new J(`No auth provider`);let e;try{e=await Ha(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new J;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Zi(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Y(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new mo({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=x.parse(JSON.parse(e.data));pe(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new J(`No auth provider`);if(await Ha(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:h(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Y(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Ka(o);if(this._resourceMetadataUrl=t,this._scope=n,await Ha(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Ka(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Y(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Ha(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new J;return this.send(e)}}throw new Y(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),d(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>x.parse(e)):[x.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Y(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Y(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function _o(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function vo(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function yo(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function bo(e,t){return`http://${yo(e)}:${t}/mcp`}function xo(e,t){return`ws://${yo(e)}:${t}`}function So(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function Co(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function wo(e){return N(e)?P(e,`utf-8`).trim():``}function To(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function Eo(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Do(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function Oo(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function ko(e){let t=e.readLock??(()=>Ie(e.lockDir)),n=e.isAlive??w,r=e.sleep??(e=>Dt(e)),i=e.spawn??et,a=e.readErrorLog??wo,o=e.openErrorLog??(e=>lt(e,`w`)),s=e.closeFd??ot,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return bo(`localhost`,t)}let u=Co(t(),n);if(u!==void 0)return bo(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);N(e.lockDir)||st(e.lockDir,{recursive:!0});let d=j(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=We();try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`}}),p.on(`error`,e=>{m=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){m=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let g=Date.now()+c;for(;Date.now()<g;){if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}await r(l);let e=Co(t(),n);if(e!==void 0)return bo(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(To(c,a(d)))}function Ao(e,t){if(e.portOverride!==void 0)return So(t);let n=e.readLock??(()=>Ie(e.lockDir)),r=e.isAlive??w,i=Co(n(),r);if(i!==void 0)return xo(`localhost`,i)}async function jo(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Ki(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new go(new URL(e),{fetch:_o(r),...t.connectionId===void 0?{}:{requestInit:{headers:{[c]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let l=Promise.resolve();i.onmessage=e=>{l=l.then(async()=>{try{await a.send(e)}catch(t){let r=Eo(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(Oo(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=Do(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function Mo(e){let t=e.stderr??process.stderr,n=e.bridgeFn??jo,r=await ko(e),i=e.createConnectionId?.()??Tt(),a=!1,o=(e.startKeepalive??Xi)({connectionId:i,resolveWsUrl:async()=>Ao(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}const No=bt(import.meta.url);function Po(e){let t=M(e);for(;;){if(fe(t))return t;let n=rt(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 \`${me}\`).`);t=n}}function Fo(e){try{let t=new URL(e);return t.protocol===`file:`?bt(t):void 0}catch{return}}async function Io(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=Fo(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Lo(e,t){if(e!==void 0)return Po(e);let n=await t();if(n!==void 0)return Po(n);throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.")}async function Ro(e){let t=process.stderr,n=e.spawnTimeoutMs??vo(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Ue({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),o=new p({name:a,version:Re},{instructions:ae({dir:`.`})});le(o);let s=Tt(),c={current:{connectionId:s,displayName:s,colorSeed:s}},l=new Map,d=e=>{if(l.has(e))return;let n=f(e),r=c.current,i=Xi({connectionId:s,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Ao({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});l.set(e,i)},m=()=>Io({getClientCapabilities:()=>o.server.getClientCapabilities(),listRoots:()=>o.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),h=e=>Lo(e,m),g=async e=>{let t;if(e===void 0){let e=await m();if(e===void 0)return;t=Po(e)}else t=Po(e);let a=await i(t),o=await ko({lockDir:f(t),contentDir:u(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return d(t),o.replace(/\/mcp$/,``)};o.server.oninitialized=()=>{let e=o.server.getClientVersion(),t=ie(e?.name,s);c.current={connectionId:s,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},ve(o,{serverUrl:g,resolveCwd:h,config:i,identityRef:c});let _=new Ki,v=!1,y,b=async()=>{if(v)return;v=!0,y?.stop();for(let e of l.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}l.clear();let e=await Promise.allSettled([o.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 o.connect(_),t.write(`[mcp] global stdio server ready (per-call project routing)
|
|
61
61
|
`);let x=!1,S=()=>{x||(x=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
62
|
-
`),process.exit(1)},5e3).unref(),b().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,S),process.once(`SIGTERM`,S),process.platform===`darwin`){let e=Yi(No,{realpathSync:dt,statInoSync:e=>pt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${Re}\n`);let{resolvedPath:n,inode:r}=e;y=Ji({detect:()=>qi({bundleAnchorPath:No,currentInode:r,platform:process.platform,realpath:dt,statInode:e=>pt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${Re} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:b}}function zo(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`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=vo(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Mo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await Ro({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 Bo(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-
|
|
62
|
+
`),process.exit(1)},5e3).unref(),b().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,S),process.once(`SIGTERM`,S),process.platform===`darwin`){let e=Yi(No,{realpathSync:dt,statInoSync:e=>pt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${Re}\n`);let{resolvedPath:n,inode:r}=e;y=Ji({detect:()=>qi({bundleAnchorPath:No,currentInode:r,platform:process.platform,realpath:dt,statInode:e=>pt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${Re} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:b}}function zo(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`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=vo(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Mo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await Ro({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 Bo(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-eIL7AIMY.mjs`),r=e(),i=process.cwd(),a=u(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 Vo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Ho(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Uo(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:bi(r),command:r,isDesktop:Vo(r)}}function Wo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Go(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&Wo(e)?`ui-orphan`:`stale`}const Ko=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function qo(e){switch(e){case`running`:return U.default.green(e);case`desktop`:return U.default.blue(e);case`foreign`:return U.default.cyan(e);case`ui-orphan`:return U.default.magenta(e);case`stale`:return U.default.yellow(e)}}function Jo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Yo(e){return`${Jo(e.server.usage)} | ${Jo(e.ui?.usage??null)}`}function Xo(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Zo(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Go(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Xo(e),Yo(e),t,String(n),Ho(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=qo(Go(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=U.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
|
|
63
63
|
`)}async function Qo(e={}){let t=e.discover??Ti,n=e.inspect??V,r=e.log??(e=>console.log(e)),i=e.resolveCommand??xi,a=e.resolveUsage??Si,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=Uo(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:Go(e)}));r(JSON.stringify(e,null,2));return}r(Zo(e.all?s:s.filter(e=>Ko.has(Go(e)))))}function $o(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await Qo({all:t.all===!0||e===`all`,json:t.json===!0})})}function X(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function es(e,t,n=process.cwd()){let r=e.op??`sync`,i=Ie(m(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`},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}`)}X(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=ze({baseDir:n});if(r===`sync`||r===`pull`){X(e.json,{type:`step`,step:`pull`});let t=await a.pull();X(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(X(e.json,{type:`step`,step:`push`}),await a.push(),X(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
64
64
|
`)),X(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function ts(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 es({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 ns(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await es({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 rs(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await es({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 is(e){return typeof e==`string`&&r.includes(e)}async function as(e={}){let t=M(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!_e[n])return{status:`failed`,message:`${O(`Error:`)} Unknown pack "${n}". Available: ${r.join(`, `)}`,exitCode:1};let i;try{i=await s({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof b?{status:`prerequisite-missing`,message:`${O(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${O(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(i.created.length===0){let e=_e[n].name;return{status:`no-op`,message:`${D(`Your ${e} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:i,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${k(`Plan (dry-run — no changes made):`)}\n\n${ss(i,t)}`,plan:i,exitCode:0};if(!e.yes&&!await cs(`${k(`Plan:`)}\n\n${ss(i,t)}\n\n${k(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:i,exitCode:0};let a=await ne(i,{projectDir:t,packId:n});if(a.errors.length>0){let e=a.errors.map(e=>` ${O(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Ze(`Applied`)} ${a.applied} entries, ${Ze(String(a.errors.length))} error(s):`,...e].join(`
|
|
65
65
|
`),plan:i,exitCode:1}}let o=_e[n].name;return{status:`applied`,message:`${D(`✓ Seeded ${o}`)} ${E(`(${a.applied} entries, ${a.durationMs}ms)`)}`,plan:i,exitCode:0}}function os(){let e=[k(`Available packs:`)];for(let t of r){let n=_e[t];e.push(` ${D(t)} ${E(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,d as t,h as n,l as r,m as i,o as a,p as o,r as s,t as c,u as l,v as u}from"./init-
|
|
1
|
+
import{_ as e,d as t,h as n,l as r,m as i,o as a,p as o,r as s,t as c,u as l,v as u}from"./init-DqApv-bY.mjs";import{i as d,n as f,r as p,t as m}from"./src-BUH_zaQF.mjs";import{n as h}from"./loader-DXesUuxk.mjs";import{n as g}from"./preview-CGp3adCc.mjs";export{o as ALL_EDITOR_IDS,i as EDITOR_LABELS,n as EDITOR_TARGETS,c as LAUNCH_CONFIG_NAME,s as detectInstalledEditors,u as initContent,h as loadConfig,p as parseGitHubBlobUrl,d as parseGitUrl,g as previewContent,a as readExistingMcpEntry,e as resolveProjectRoot,r as scaffoldLaunchJson,f as validateLocalFolderForShare,l as writeEditorMcpConfig,m as writeProjectAiIntegrations,t as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as e}from"./init-DqApv-bY.mjs";export{e as runInit};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{$r as a,D as o,Mt as s,N as c,Pt as l,Wn as u,_i as d,ai as f,an as p,ci as m,ei as h,fi as g,gi as _,ii as v,in as y,oi as b,on as x,pn as S,un as C}from"./dist-CQVP3NVF.mjs";import{n as ee,t as te}from"./constants-SS3E-YX9.mjs";import{t as w}from"./is-object-C-4FJ0rP.mjs";import{i as T,o as E,r as ne,s as D,t as O}from"./colors-BtKMHmBX.mjs";import{t as re}from"./preview-fcmKJ-7t.mjs";import{execFileSync as ie}from"node:child_process";import ae,{basename as k,dirname as A,isAbsolute as j,join as M,posix as N,relative as P,resolve as F,sep as I,win32 as L}from"node:path";import{cpSync as oe,existsSync as R,lstatSync as se,mkdirSync as z,readFileSync as ce,realpathSync as le,rmSync as ue,writeFileSync as B}from"node:fs";import V from"node:process";import{homedir as H}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as U}from"node:util";import*as me from"node:readline";import{randomUUID as he}from"node:crypto";import{createServer as ge,request as _e}from"node:http";import{connect as ve}from"node:net";function ye(){return V.platform.startsWith(`win`)?!!V.env.CI||!!V.env.WT_SESSION||!!V.env.TERMINUS_SUBLIME||V.env.ConEmuTask===`{cmd::Cmder}`||V.env.TERM_PROGRAM===`Terminus-Sublime`||V.env.TERM_PROGRAM===`vscode`||V.env.TERM===`xterm-256color`||V.env.TERM===`alacritty`||V.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:V.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},W=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},G=(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:G(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=G(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&&!G(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=G(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=G(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=G(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){We(s,r,t),c=G(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){We(s,r,t),c=G(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{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{$r as a,D as o,Mt as s,N as c,Pt as l,Wn as u,_i as d,ai as f,an as p,ci as m,ei as h,fi as g,gi as _,ii as v,in as y,oi as b,on as x,pn as S,un as C}from"./dist-CQVP3NVF.mjs";import{n as ee,t as te}from"./constants-CvW406ds.mjs";import{t as w}from"./is-object-C-4FJ0rP.mjs";import{i as T,o as E,r as ne,s as D,t as O}from"./colors-BtKMHmBX.mjs";import{t as re}from"./preview-CGp3adCc.mjs";import{execFileSync as ie}from"node:child_process";import ae,{basename as k,dirname as A,isAbsolute as j,join as M,posix as N,relative as P,resolve as F,sep as I,win32 as L}from"node:path";import{cpSync as oe,existsSync as R,lstatSync as se,mkdirSync as z,readFileSync as ce,realpathSync as le,rmSync as ue,writeFileSync as B}from"node:fs";import V from"node:process";import{homedir as H}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as U}from"node:util";import*as me from"node:readline";import{randomUUID as he}from"node:crypto";import{createServer as ge,request as _e}from"node:http";import{connect as ve}from"node:net";function ye(){return V.platform.startsWith(`win`)?!!V.env.CI||!!V.env.WT_SESSION||!!V.env.TERMINUS_SUBLIME||V.env.ConEmuTask===`{cmd::Cmder}`||V.env.TERM_PROGRAM===`Terminus-Sublime`||V.env.TERM_PROGRAM===`vscode`||V.env.TERM===`xterm-256color`||V.env.TERM===`alacritty`||V.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:V.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},W=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},G=(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:G(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=G(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&&!G(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=G(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=G(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=G(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){We(s,r,t),c=G(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){We(s,r,t),c=G(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(`
|
|
@@ -401,9 +401,9 @@ last-spawn-error.log
|
|
|
401
401
|
# *.draft.md # exclude files matching a pattern
|
|
402
402
|
# !keep.md # re-include a file .gitignore excluded
|
|
403
403
|
`,`.okignore`)?r.push(`.okignore`):a.push(`.okignore`),{created:r,updated:i,skipped:a}}function $n(e,t){let n=P(t,e);return n.length>0&&!n.startsWith(`..`)&&!j(n)}const er=e=>{try{let t=ie(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return t.length>0?t:null}catch{return null}};function tr(e,t={}){let n=t.homeDir??H(),r=t.gitTopLevel??er,i=F(e),a;try{a=le(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(S(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=A(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&$n(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}const nr=a,rr=v,ir=[`-y`,`@inkeep/open-knowledge@latest`,`mcp`],ar={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function or(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=F(e);if(k(t)===`cli.mjs`&&k(A(t))===`dist`)return t;let n=t.split(I),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return M(i.length===0?I:i.join(I),`packages`,`cli`,`dist`,`cli.mjs`)}function sr(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[or(),`mcp`],env:{...ar}}:{command:`npx`,args:[...ir]}}function cr(e){return e===`win32`?L:N}function lr(e={}){let t=e.platformName??process.platform,n=e.home??H();return cr(t).join(n,`.claude.json`)}function ur(e={}){let t=e.platformName??process.platform,n=e.home??H(),r=e.env??process.env;if(t===`darwin`)return N.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??L.join(n,`AppData`,`Roaming`);return L.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function dr(e={}){let t=e.platformName??process.platform,n=e.home??H();return cr(t).join(n,`.cursor`,`mcp.json`)}function fr(e={}){let t=e.platformName??process.platform,n=e.home??H();return(e.env??process.env).CODEX_HOME??cr(t).join(n,`.codex`)}function pr(e={}){return cr(e.platformName??process.platform).join(fr(e),`config.toml`)}function mr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>mr(e,t[n]));if(w(e)&&w(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>mr(e[n],t[n]))}return!1}function hr(e,t){return Object.entries(t).every(([t,n])=>mr(e[t],n))}function gr(e,t){return{...e,...t}}function _r(e){return{...e,isCompatible(t,n,r){return hr(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return gr(t,e.buildEntry(n,r))}}}const Q={claude:_r({id:`claude`,label:rr.claude,configPath:(e,t)=>lr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>sr(t),scope:`global`,detectPath:(e,t)=>M(t??H(),`.claude`),projectConfigPath:e=>M(e,`.mcp.json`),projectSkillPath:e=>M(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)}),"claude-desktop":_r({id:`claude-desktop`,label:rr[`claude-desktop`],configPath:(e,t)=>ur({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>sr(t),scope:`global`,detectPath:(e,t)=>A(ur({home:t}))}),cursor:_r({id:`cursor`,label:rr.cursor,configPath:(e,t)=>dr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>sr(t),scope:`global`,detectPath:(e,t)=>A(dr({home:t})),projectConfigPath:e=>M(e,`.cursor`,`mcp.json`),projectSkillPath:e=>M(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)}),codex:_r({id:`codex`,label:rr.codex,configPath:(e,t)=>pr({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>o,buildEntry:(e,t)=>sr(t),scope:`global`,detectPath:(e,t)=>A(pr({home:t})),projectConfigPath:e=>M(e,`.codex`,`config.toml`)})};function vr(e){let t=e.filter(e=>!Object.hasOwn(Q,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${nr.join(`, `)}`);return e.map(e=>Q[e])}function $(e,t,n,r,i){let a=`urn:uuid:${he()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},s=m.safeParse(o);if(!s.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:s.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const yr=1e4;function br(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!C(n))return $(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!x(e.headers.host))return $(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!p(r)?($(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const xr=3e4;function Sr(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!C(n)||!x(e.headers.host))return t.destroy(),!0;let r=e.headers.origin;return typeof r==`string`&&!p(r)?(t.destroy(),!0):!1}function Cr(e,t,n,r,i,a){a.add(t),t.once(`close`,()=>a.delete(t));let o=ve({host:r,port:i,timeout:yr});a.add(o),o.once(`close`,()=>a.delete(o));let s=!1,c=n=>{if(!s){if(s=!0,n!==void 0){let t=n.err;console.warn(JSON.stringify({event:n.event,upstreamHost:r,upstreamPort:i,url:e.url,code:t instanceof Error?t.code:void 0,message:t instanceof Error?t.message:void 0}))}try{o.destroy()}catch{}try{t.destroy()}catch{}}};o.once(`connect`,()=>{o.setTimeout(0);let a=[`${e.method??`GET`} ${e.url??`/`} HTTP/1.1`,`host: ${r}:${i}`];for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()!==`host`&&n!==void 0)if(Array.isArray(n))for(let e of n)a.push(`${t}: ${e}`);else a.push(`${t}: ${n}`);try{o.write(`${a.join(`\r
|
|
404
|
-
`)}\r\n\r\n`),n.length>0&&o.write(n)}catch(e){c({event:`proxy-upgrade-handshake-write-failed`,err:e});return}o.on(`data`,e=>{t.writable&&t.write(e)}),t.on(`data`,e=>{o.writable&&o.write(e)})}),o.once(`timeout`,()=>{c({event:`proxy-upgrade-upstream-connect-timeout`})}),o.on(`error`,e=>c({event:`proxy-upgrade-upstream-error`,err:e})),t.on(`error`,e=>c({event:`proxy-upgrade-client-error`,err:e})),o.once(`close`,()=>c()),t.once(`close`,()=>c())}const wr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Tr(e){let t=e.upstreamTimeoutMs??yr,n=ge((n,r)=>{br(n,r)||Dr(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,
|
|
404
|
+
`)}\r\n\r\n`),n.length>0&&o.write(n)}catch(e){c({event:`proxy-upgrade-handshake-write-failed`,err:e});return}o.on(`data`,e=>{t.writable&&t.write(e)}),t.on(`data`,e=>{o.writable&&o.write(e)})}),o.once(`timeout`,()=>{c({event:`proxy-upgrade-upstream-connect-timeout`})}),o.on(`error`,e=>c({event:`proxy-upgrade-upstream-error`,err:e})),t.on(`error`,e=>c({event:`proxy-upgrade-client-error`,err:e})),o.once(`close`,()=>c()),t.once(`close`,()=>c())}const wr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Tr(e){let t=e.upstreamTimeoutMs??yr,n=new Set,r=ge((n,r)=>{br(n,r)||Dr(n,r,e.upstreamHost,e.upstreamPort,t)});r.on(`upgrade`,(t,r,i)=>{Sr(t,r)||Cr(t,r,i,e.upstreamHost,e.upstreamPort,n)}),await new Promise((t,n)=>{let i=e=>n(e);r.once(`error`,i),r.listen(e.listenPort,e.host,()=>{r.off(`error`,i),t()})});let i=r.address();return{httpServer:r,port:typeof i==`object`&&i?i.port:e.listenPort,close:()=>new Promise(e=>{for(let e of n)try{e.destroy()}catch{}n.clear(),r.close(()=>e()),r.closeIdleConnections()})}}function Er(e,t,n){Dr(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??yr)}function Dr(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of wr)delete a[e];e.setTimeout(xr,()=>{if(t.headersSent)try{t.end()}catch{}else try{$(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${xr/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=_e({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of wr)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)$(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)$(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}const Or=39847,kr=39848;async function Ar(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function jr(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:a,createContentFilter:o,readServerLock:s,releaseUiLock:c,updateUiLockPort:l}=await import(`./dist-DZjV1a0G.mjs`),{default:u}=await import(`./build-B4ZT2GMK.mjs`),{resolveContentDir:d,resolveLockDir:p}=await import(`./dist-DZjV1a0G.mjs`),m=d(e.config,e.cwd),_=p(e.cwd);i(_,{port:0,worktreeRoot:e.cwd});let v=import.meta.dirname??new URL(`.`,import.meta.url).pathname,y=[r(v,`public`),r(v,`../../app/dist`),r(v,`../../../app/dist`)].find(e=>t(e)),x=y?u(y,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,S=t(m)?a({contentFilter:o({projectDir:e.cwd,contentDir:m}),contentSirv:u(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:b,assetExtensions:h,blocklistExtensions:f}):null,C=e.port,ee=null,te=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&br(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){ee?.();let n=s(_),r=e.headers.host??`localhost:${C}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=JSON.stringify({collabUrl:i,previewUrl:null,port:C});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(a);return}if(n?.startsWith(`/api/`)){ee?.();let r=s(_);if(!r||r.port<=0){$(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}Er(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(x&&n?.startsWith(`/assets/`)){x(e,t,()=>{S?S(e,t,()=>Mr(t,n)):Mr(t,n)});return}if(S){S(e,t,()=>{x?x(e,t):Mr(t,n)});return}if(x){x(e,t);return}Mr(t,n)}},w=new Set,T=(e,t,n)=>{if(Sr(e,t))return;let r=e.url?.split(`?`)[0]??``;if(r!==`/collab`&&!r.startsWith(`/collab/`)){t.destroy();return}let i=s(_);if(!i||i.port<=0){console.warn(JSON.stringify({event:`ok-ui-upgrade-no-collab-lock`,url:r,reason:"server.lock missing or port unbound — is `ok start` running?"})),t.destroy();return}Cr(e,t,n,`localhost`,i.port,w)},E=()=>{for(let e of w)try{e.destroy()}catch{}w.clear()},ne=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],D=[],O=e.port,re=e=>e instanceof Error&&e.code===`EADDRINUSE`,ie=async()=>{await Promise.all(D.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},ae=async e=>{O=e;for(let e of ne){let t=n(te);t.on(`upgrade`,T),D.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(O,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(O=e.port),n()})})}};try{try{await ae(e.port)}catch(t){if(e.fallbackToKernel===!0&&re(t))await ie(),await ae(0);else throw t}}catch(e){await ie();try{c(_)}catch{}throw e}let k=O;C=k,l(_,k);let A=e.scheduler??g,j=e.safetyNetMs??432e5,M=null,N=!1,P=!1,F=()=>{N||(N=!0,M!==null&&(A.clearTimeout(M),M=null))},I=()=>{if(F(),!P){P=!0;try{c(_)}catch{}}},L=()=>{N||j<=0||(M!==null&&(A.clearTimeout(M),M=null),M=A.setTimeout(()=>{M=null,console.warn(`[ui] safety-net (${j}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}E();for(let e of D)try{e.close()}catch{}I()},j))},oe=()=>{N||j<=0||L()};return ee=oe,L(),{httpServers:D,port:k,release:I,detachSafetyNet:F,nudgeSafetyNet:oe,drainUpgradeSockets:E}}function Mr(e,t){$(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Nr(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return{port:t,fallbackToKernel:!1}}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return{port:e,fallbackToKernel:!1}}return{port:Or,fallbackToKernel:!0}}async function Pr(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-DZjV1a0G.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Tr({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Fr(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Or}, kernel-allocated fallback if busy)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud. Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BCE2jNgl.mjs`),{UiLockCollisionError:r}=await import(`./dist-DZjV1a0G.mjs`),{resolveLockDir:i}=await import(`./dist-DZjV1a0G.mjs`),a=e(),o=t.host,s;try{s=Nr(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}let c=s.port;try{let e=await jr({config:a,cwd:process.cwd(),port:c,fallbackToKernel:s.fallbackToKernel,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};e.drainUpgradeSockets(),Ar(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,s;try{s=await Pr({requestedPort:c,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}s.mode===`already-running`&&(console.log(`UI already running at http://${a}:${s.port}`),process.exit(0)),console.log(`UI running at http://${a}:${s.upstreamPort}; acting as HTTP proxy on port ${s.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})`)),s.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}function Ir(e){if(!R(e))return{};let t=ce(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(w(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function Lr(e){if(!R(e))return{};let t=ce(e,`utf-8`).trim();if(t===``)return{};try{let n=Fn(t);if(w(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function Rr(e,t){z(A(e),{recursive:!0}),B(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function zr(e,t){z(A(e),{recursive:!0});let n=Gn(t);B(e,n.endsWith(`
|
|
405
405
|
`)?n:`${n}\n`,`utf-8`)}function Br(e,t){let n;try{n=le(t)}catch{n=F(t)}let r;try{r=se(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run \`ok init\`, or pass \`--no-mcp\` to skip MCP config writes.`);let i=A(e);for(;i.length>1&&i!==I;){let t;try{t=le(i)}catch(e){if(e.code===`ENOENT`){i=A(i);continue}throw e}let r=P(n,t);if(r===``||!r.startsWith(`..`)&&!j(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run, or pass \`--no-mcp\`.`)}}const Vr=e=>e!==`project`,Hr=e=>e!==`user`;async function Ur(){let e=await dn({message:`Where should the MCP server be configured?
|
|
406
406
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Wr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Ur)():`both`}const Gr=`0.0.1`,Kr=`open-knowledge-ui`,qr=[`-y`,`@inkeep/open-knowledge@latest`,`ui`];function Jr(e,t={}){let n=M(e,`.claude`,`launch.json`),r=t.cliPath===void 0?t.mode===`dev`?{name:Kr,runtimeExecutable:`node`,runtimeArgs:[or(),`ui`],port:kr,autoPort:!0}:{name:Kr,runtimeExecutable:`npx`,runtimeArgs:[...qr],port:kr,autoPort:!0}:{name:Kr,runtimeExecutable:t.cliPath,runtimeArgs:[`ui`],port:kr,autoPort:!0};try{if(Br(n,e),!R(n))return z(A(n),{recursive:!0}),B(n,`${JSON.stringify({version:Gr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=ce(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!w(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=>w(e)&&e.name===`open-knowledge-ui`);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Gr,configurations:a};return B(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 Yr(e,t,n){try{return R(e.detectPath?.(t,n)??A(e.configPath(t,n)))}catch{return!1}}function Xr(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&&!Yr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Br(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.format===`toml`?Lr(o):Ir(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=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)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?zr(o,d):Rr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function Zr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=u(),i=A(n);Br(i,t);let a=R(n)?`overwritten`:`written`;return ue(i,{recursive:!0,force:!0}),z(A(i),{recursive:!0}),oe(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function Qr(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!R(n)))return{editorId:e.id,label:e.label,path:n}}async function $r(e){let t=vr(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>Xr(t,``,n,e.home))}function ei(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return null}let a;try{a=e.format===`toml`?Lr(i):Ir(i)}catch{return null}let o=a[e.topLevelKey];if(!w(o))return null;let s=o[e.serverName(t)];return w(s)?s:null}async function ti(e={}){let t=F(e.cwd??process.cwd()),n=tr(t,{homeDir:e.home}),r=n.projectRoot,i=!R(M(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 ${P(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await l(r),c;try{c=Qn(r,{contentDir:n.defaultContentDir})}catch(t){let n=Q.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:o.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:n,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`}}let u=await Wr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),d=e.editors??ri(r,e.home),f=e.editors??nr.filter(e=>Q[e].projectConfigPath!==void 0),p=vr(d),m=vr(f),h=e.mcp===!1||u===null,g=Array.from(new Map([...p,...h?[]:m].map(e=>[e.id,e])).values()),_=p.filter(t=>Yr(t,r,e.home)),v=[],b=[],x=new Set;for(let t of g){if(h){let n=``;try{n=t.configPath(r,e.home)}catch{}v.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(Vr(u)&&p.includes(t)&&v.push(Xr(t,r,a,e.home)),Hr(u)&&m.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Xr(t,r,a,e.home,n);v.push(i),(i.action===`written`||i.action===`overwritten`)&&(x.add(n),b.push(Zr(t,r)))}}let S=!h&&u!==null&&Hr(u)?m.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,C=h?[]:_.map(e=>Qr(e,r)).filter(e=>e!==void 0).filter(e=>!x.has(e.path)),ee=_.some(e=>e.id===`claude`)&&!h?Jr(r,a):void 0,te=await(e.installUserSkill??y)({home:e.home}),w=s({home:e.home}),T=h?`skipped-flag`:`skipped-missing`,E=v.find(e=>e.editorId===`claude`)??v[0]??{action:T,configPath:Q.claude.configPath(r,e.home)};return{projectRoot:r,contentCreated:c.created,contentUpdated:c.updated,contentSkipped:c.skipped,editors:v,projectSkills:b,legacyProjectConfigs:C,launchJson:ee,skillInstall:te,didGitInit:o.didInit,claudeDesktopDetected:w,mcpAction:E.action,mcpPath:E.configPath,mcpError:`error`in E?E.error:void 0,projectScopeUnsupportedLabels:S}}function ni(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)?P(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)`);let c=M(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`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(O(`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(O(`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(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?P(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} ${E(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${E(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${ne(`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(O(`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?P(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${E(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${E(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${ne(`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} ${P(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(O(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${E(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${E(`already installed at current version`)}`);break;case`failed`:n.push(` ${D(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${D(` 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: ${O(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(re(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),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(`${E(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${T(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${T(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${T(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${T(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${T(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${T(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
|
|
407
407
|
`)}function ri(e,t){let n=[];for(let r of nr)Yr(Q[r],e,t)&&n.push(r);return n}function ii(){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`])).action(async e=>{let t=process.cwd(),n;try{n=await ti({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof c){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
408
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
409
|
-
//# sourceMappingURL=init-
|
|
408
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-eIL7AIMY.mjs`),{loadConfig:t}=await import(`./loader-CuPkY1R-.mjs`),{resolveContentDir:r}=await import(`./dist-DZjV1a0G.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${ni(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{dt as C,Je as D,Ye as E,Te as O,pt as S,ot as T,tr as _,ii as a,lt as b,ti as c,$r as d,Fr as f,ir as g,Q as h,ni as i,W as k,Jr as l,rr as m,qr as n,ei as o,nr as p,ri as r,Wr as s,Kr as t,Xr as u,Qn as v,ht as w,ut as x,ft as y};
|
|
409
|
+
//# sourceMappingURL=init-DqApv-bY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-DXesUuxk.mjs";export{e as loadConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Jr as e,Mi as t,Yr as n,f as r,pi as i,yi as a}from"./dist-CQVP3NVF.mjs";import{t as o}from"./constants-
|
|
1
|
+
import{Jr as e,Mi as t,Yr as n,f as r,pi as i,yi as a}from"./dist-CQVP3NVF.mjs";import{t as o}from"./constants-CvW406ds.mjs";import{t as s}from"./is-object-C-4FJ0rP.mjs";import{resolve as c}from"node:path";import{existsSync as l,readFileSync as u}from"node:fs";import{realpath as d}from"node:fs/promises";async function f(e){let t=c(e);try{return await d(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 p=t();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];s(a)&&s(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(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,p.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 s(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!s(t))return[];let n=t.content;if(!s(n))return[];let r=[];for(let t of g)if(t in n){let n=[`content`,t],i;e.doc!==null&&e.source!==null&&(i=a({file:e.path,source:e.source,doc:e.doc,path:n})),r.push({code:`REMOVED_KEY`,path:n,redirect:_(t),...i===void 0?{}:{source:i}})}return r}function y(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=a({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(t){let a=t??process.cwd(),s=[],l=n(`user`,a),u=e({absPath:l}),d={};u.valid&&u.source!==void 0?(d=m(d,u.value),s.push(l)):u.valid;let f=c(a,`.ok`,o),p=h(f);if(p.value!==null){let e=v(p);if(e.length>0)throw Error(e.map(i).join(`
|
|
2
2
|
|
|
3
3
|
`));d=m(d,p.value),s.push(f)}x(d,[`upload`,`maxBytes`],`streaming uploads have no user-facing cap`),x(d,[`github`,`oauthAppClientId`],`use the OPEN_KNOWLEDGE_GITHUB_CLIENT_ID env var instead`),x(d,[`server`,`host`],`use the --host flag or HOST env var instead`),x(d,[`server`,`openOnAgentEdit`]),x(d,[`mcp`,`autoStart`],`to disable auto-start, set OK_MCP_AUTOSTART=0`),x(d,[`mcp`,`tools`,`read_document`,`historyDepth`]),x(d,[`mcp`,`tools`,`grep`,`maxResults`]),x(d,[`mcp`,`tools`,`search`,`maxResults`]),x(d,[`preview`,`baseUrl`],"preview URLs now resolve only to the running UI process — start one with `ok ui`");let g=r.safeParse(d);if(!g.success){let e={code:`SCHEMA_INVALID`,issues:y(g.error.issues,p)};throw Error(i(e))}return{config:g.data,sources:s}}function x(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){if(!s(r))return;r=r[t[e]]}if(!s(r))return;let i=t[t.length-1];if(r[i]===void 0)return;let a=t.join(`.`);console.warn(`[config] ${a} is no longer user-configurable; ${n??`the value is hardcoded in @inkeep/open-knowledge-core`}. Remove the key to silence this warning.`)}function S(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=f(e.startupCwd);return async o=>{let s=await f(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{b as n,S as t};
|
|
4
|
-
//# sourceMappingURL=loader-
|
|
4
|
+
//# sourceMappingURL=loader-DXesUuxk.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{xt as e}from"./dist-CQVP3NVF.mjs";import"./constants-
|
|
1
|
+
import{xt as e}from"./dist-CQVP3NVF.mjs";import"./constants-CvW406ds.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(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 r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);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,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
|
|
2
2
|
`)}export{c as n,l as t};
|
|
3
|
-
//# sourceMappingURL=preview-
|
|
3
|
+
//# sourceMappingURL=preview-CGp3adCc.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-CGp3adCc.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{l as e,n as t}from"./init-
|
|
2
|
-
//# sourceMappingURL=repair-launch-json-
|
|
1
|
+
import{l as e,n as t}from"./init-DqApv-bY.mjs";import{t as n}from"./is-object-C-4FJ0rP.mjs";import{join as r}from"node:path";import{existsSync as i,readFileSync as a}from"node:fs";const o=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`]];function s(e){if(e.runtimeExecutable!==`npx`||!Array.isArray(e.runtimeArgs))return`preserved`;if(c(e.runtimeArgs,t))return`canonical`;for(let t of o)if(c(e.runtimeArgs,t))return`legacy-bare`;return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(t){let o=t.logger??u,c=r(t.projectDir,`.claude`,`launch.json`);if(!i(c))return{outcome:{configPath:c,outcome:`no-file`},repairedCount:0};let l;try{let e=a(c,`utf-8`).trim();l=e?JSON.parse(e):{}}catch(e){let t=e instanceof Error?e.message:String(e);return o({event:`launch-json-repair-read-failed`,configPath:c,error:t}),{outcome:{configPath:c,outcome:`read-failed`,error:t},repairedCount:0}}if(!n(l)){let e=`launch.json root is not an object`;return o({event:`launch-json-repair-read-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`read-failed`,error:e},repairedCount:0}}let d=l.configurations;if(!Array.isArray(d))return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let f=d.find(e=>n(e)&&e.name===`open-knowledge-ui`);if(!f)return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let p=s(f);if(p===`canonical`)return{outcome:{configPath:c,outcome:`canonical`},repairedCount:0};if(p===`preserved`)return{outcome:{configPath:c,outcome:`preserved`},repairedCount:0};let m=e(t.projectDir,{mode:`published`});if(m.action===`failed`){let e=m.error??`unknown write failure`;return o({event:`launch-json-repair-write-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`write-failed`,error:e},repairedCount:0}}return o({event:`launch-json-repair-applied`,configPath:c}),{outcome:{configPath:c,outcome:`repaired`},repairedCount:1}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairLaunchJson};
|
|
2
|
+
//# sourceMappingURL=repair-launch-json-D5A35XkF.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{g as e,h as t,o as n,p as r,u as i}from"./init-
|
|
2
|
-
//# sourceMappingURL=repair-mcp-configs-
|
|
1
|
+
import{g as e,h as t,o as n,p as r,u as i}from"./init-DqApv-bY.mjs";import{homedir as a}from"node:os";const o=[[`@inkeep/open-knowledge`,`mcp`],[`-y`,`@inkeep/open-knowledge`,`mcp`]];function s(t){if(t.command!==`npx`||!Array.isArray(t.args))return`preserved`;if(c(t.args,e))return`canonical`;for(let e of o)if(c(t.args,e))return`legacy-bare`;return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(e){let n=e.logger??f,i=e.home??a(),o=[];for(let a of r){let r=t[a],s=u(()=>r.configPath(``,i));if(s!==null&&o.push(d({scope:`user`,editorId:a,target:r,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:n})),r.projectConfigPath){let t=r.projectConfigPath,i=u(()=>t(e.projectDir));i!==null&&o.push(d({scope:`project`,editorId:a,target:r,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:n}))}}return{outcomes:o,repairedCount:o.filter(e=>e.outcome===`repaired`).length}}function u(e){try{return e()}catch{return null}}function d(e){let t={scope:e.scope,editorId:e.editorId,configPath:e.configPath},r=n(e.target,e.cwd,e.home,e.configPathOverride);if(r===null)return{...t,outcome:`no-entry`};let a=s(r);if(a===`canonical`)return{...t,outcome:`canonical`};if(a===`preserved`)return{...t,outcome:`preserved`};let o=i(e.target,e.cwd,{mode:`published`,skipAvailabilityCheck:!0},e.home,e.configPathOverride);if(o.action===`failed`){let n=o.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:n}),{...t,outcome:`write-failed`,error:n}}return e.logger({event:`mcp-config-repair-applied`,scope:e.scope,editorId:e.editorId,configPath:e.configPath}),{...t,outcome:`repaired`}}function f(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairMcpConfigs};
|
|
2
|
+
//# sourceMappingURL=repair-mcp-configs-BPXNDxGY.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as e,l as t,u as n}from"./init-
|
|
2
|
-
//# sourceMappingURL=src-
|
|
1
|
+
import{h as e,l as t,u as n}from"./init-DqApv-bY.mjs";import"./loader-DXesUuxk.mjs";import"./preview-CGp3adCc.mjs";import{dirname as r,isAbsolute as i,join as a,relative as o,resolve as s}from"node:path";import{statSync as c}from"node:fs";import{readFile as l,realpath as u}from"node:fs/promises";function d(e){return e.replace(/:\d+$/,``)}function f(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:d(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:d(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:d(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function p(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}async function m(e,t){let n,o;try{n=await u(s(e)),o=await u(s(r(e)))}catch{return{kind:`not-git`}}if(!h(n,o))return{kind:`symlink-escape`};let d=a(n,`.git`),p;try{p=c(d)}catch{return{kind:`not-git`}}let m;if(p.isDirectory()){let e;try{e=await u(d)}catch{return{kind:`not-git`}}if(!h(e,n))return{kind:`symlink-escape`};m=e}else if(p.isFile()){let e;try{e=await l(d,`utf-8`)}catch{return{kind:`not-git`}}let t=/^gitdir:\s*(.+)$/m.exec(e.trim());if(!t)return{kind:`not-git`};let r=t[1].trim(),a=i(r)?r:s(n,r);try{m=await u(a)}catch{return{kind:`not-git`}}}else return{kind:`not-git`};let g=a(m,`config`),v;try{v=await l(g,`utf-8`)}catch{return{kind:`not-git`}}let y=_(v);if(y===null)return{kind:`no-origin`};let b=f(y);if(b===null||b.hostname!==`github.com`)return{kind:`non-github`};let x=b.owner.toLowerCase()===t.owner.toLowerCase(),S=b.name.toLowerCase()===t.repo.toLowerCase();return!x||!S?{kind:`wrong-repo`,actualOwner:b.owner,actualRepo:b.name}:{kind:`ok`,gitRemoteUrl:`https://github.com/${b.owner}/${b.name}.git`}}function h(e,t){if(e===t)return!0;let n=o(t,e);return n.length>0&&!n.startsWith(`..`)&&!i(n)}function g(e){let t=e.indexOf(`#`),n=e.indexOf(`;`),r=-1;return t>=0&&n>=0?r=Math.min(t,n):t>=0?r=t:n>=0&&(r=n),(r===-1?e:e.slice(0,r)).trim()}function _(e){let t=!1;for(let n of e.split(/\r?\n/)){let e=g(n);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let r=/^url\s*=\s*(.+)$/.exec(e);if(r)return v(r[1])}return null}function v(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function y(r,i,a={}){let o=[];for(let t of i){let i=e[t],s=i.projectConfigPath?.(r);if(!s){o.push({editorId:t,outcome:`skipped-no-project-surface`});continue}let c;try{c=n(i,r,a,void 0,s)}catch(e){o.push({editorId:t,outcome:`failed`,error:e instanceof Error?e.message:String(e)});continue}if(c.action===`written`||c.action===`overwritten`){o.push({editorId:t,outcome:c.action});continue}if(c.action===`failed`){o.push({editorId:t,outcome:`failed`,error:c.error});continue}o.push({editorId:t,outcome:`failed`,error:`unexpected project-scope action: ${c.action}`})}return{editorOutcomes:o,claudeLaunchJson:i.includes(`claude`)?t(r,a):void 0}}export{f as i,m as n,p as r,y as t};
|
|
2
|
+
//# sourceMappingURL=src-BUH_zaQF.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-CQVP3NVF.mjs";import{n as r}from"./constants-
|
|
1
|
+
import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-CQVP3NVF.mjs";import{n as r}from"./constants-CvW406ds.mjs";import{spawn as i}from"node:child_process";import{join as a}from"node:path";import{closeSync as o,existsSync as s,mkdirSync as c,openSync as l,statSync as u}from"node:fs";import{homedir as d}from"node:os";import{setTimeout as f}from"node:timers/promises";const p=`Open Knowledge.app`,m=`/Applications/${p}`;function h(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return u(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function g(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(_(e,m))return m;let t=a(e.homeDir??d(),`Applications`,p);return _(e,t)?t:null}function _(e,t){try{let n=a(t,`Contents`,`MacOS`,`Open Knowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function v(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=g(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function y(e){(e.log??(e=>console.error(e)))("Launching Open Knowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function b(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${m}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${m} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${m} but launch dispatch did not fire (caller bug).`}}function x(){let e=process.execPath,t=process.argv[1];return t?{command:e,prefixArgs:[t]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function S(e,t){return e.host??t.HOST??`localhost`}var C=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function w(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function T(e){s(e.lockDir)||c(e.lockDir,{recursive:!0});let t=l(a(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??i,{PORT:r,...u}=process.env,d=x();try{let r=n(d.command,[...d.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:u});return r.unref(),r}finally{try{o(t)}catch{}}}async function E(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}function D(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>f(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function O(e){let{config:t,cwd:r,host:i}=e,a=e.skipAutoInit??!1,o=e.skipUiAutoSpawn??!1,s=e.idleThresholdMs??18e5,{existsSync:c,mkdirSync:l}=await import(`node:fs`),{bootServer:u,getLogger:d,isProcessAlive:p,readUiLock:m,resolveContentDir:h}=await import(`./dist-DZjV1a0G.mjs`),g=e.log??d(`start`);if(!a&&!n(r))throw new C(r);try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-BPXNDxGY.mjs`)).repairMcpConfigs)({projectDir:r})}catch(e){g.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-D5A35XkF.mjs`)).repairLaunchJson)({projectDir:r})}catch(e){g.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}let _=h(t,r);c(_)||(l(_,{recursive:!0}),g.info({contentDir:_},`Created content directory`));let v=null,y=await u({config:t,contentDir:_,projectDir:r,contentRoot:t.content.dir,port:e.port,host:i,quiet:!1,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:s,skipAutoInit:!0,spawnUiSiblingFn:async({lockDir:t})=>{if(v=w({uiLock:m(t),isAlive:p}),v.action===`spawn`&&!o)try{T({lockDir:t,cwd:r,spawn:e.spawn}),g.info({reason:v.reason},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else v.action===`skip`&&g.info({port:v.port,pid:v.pid},`UI already running at port ${v.port}`)},idleShutdownHandler:e=>D({readUiLock:()=>m(y.lockDir),isAlive:p,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:g}),log:g});v||={action:`skip`,reason:`alive`,pid:0,port:0};let b=v,x=null;if(b.action===`skip`)x=b.port>0?b.port:null;else if(!o){let t=e.uiBindTimeoutMs??3e3;x=await E({readUiLock:()=>m(y.lockDir),now:Date.now,sleep:e=>f(e),timeoutMs:t,pollIntervalMs:50}),x===null&&g.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:y.httpServer,destroy:y.destroy,lockDir:y.lockDir,contentDir:_,port:y.port,ready:y.ready,degraded:y.degraded,uiSpawnDecision:v,resolvedUiPort:x}}function k(t){if(t===`browser`||t===`app`)return t;throw new e(`--mode must be 'browser' or 'app'`)}async function A(e,t){let{renderBanner:n}=await import(`./banner-COfNQySC.mjs`),{dim:i,error:a,warning:o}=await import(`./colors-BCE2jNgl.mjs`),s=process.cwd(),c=e,l=S(t,process.env),u=t.port===void 0?void 0:Number(t.port),d=process.env.PORT?Number(process.env.PORT):void 0,f=u??d,p;try{p=await O({config:c,cwd:s,host:l,port:f})}catch(e){e instanceof C&&(console.error(a(e.message)),process.exit(1));let t=j(e,s,await import(`./dist-DZjV1a0G.mjs`));t!==null&&(console.error(a(t)),process.exit(1)),console.error(`${a(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let m=!1,h=async e=>{if(!m){m=!0,console.log(i(`\nShutting down (${e})`));try{await p.destroy()}catch(e){console.error(`${a(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{h(`SIGINT`)}),process.once(`SIGTERM`,()=>{h(`SIGTERM`)});let g=`http://${l}:${p.port}`,_=l===`0.0.0.0`||l===`::`?`http://0.0.0.0:${p.port}`:void 0,v=p.resolvedUiPort,y=v!==null&&v>0?`http://${l}:${v}`:g;console.log(n({name:`open-knowledge`,version:r,localUrl:y,apiUrl:y===g?void 0:g,networkUrl:_}));let b={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};p.ready.then(async()=>{if(p.degraded.length>0){console.log();for(let e of p.degraded){let t=b[e]??`${e} (check server logs for details)`;console.warn(` ${o(`⚠`)} ${o(e)}: ${i(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-Be-7qaQ9.mjs`);e(y)}}).catch(e=>{console.error(` ${a(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function j(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=a(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`Open Knowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function M(e){return new t(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,k).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
|
|
2
2
|
`),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=v(h());if(n.available){y({spawn:i});return}console.error(b(n.reason)),process.exit(1)}await A(n,t)})}export{w as a,T as c,x as d,h as f,D as i,M as l,y as m,E as n,S as o,v as p,O as r,A as s,C as t,j as u};
|
|
3
|
-
//# sourceMappingURL=start-
|
|
3
|
+
//# sourceMappingURL=start-CKo41lFY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as e}from"./start-CKo41lFY.mjs";export{e as startCommand};
|
package/package.json
CHANGED
package/dist/init-CXHjEcRB.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as e}from"./init-CzIlOXY5.mjs";export{e as runInit};
|
package/dist/loader-BylDL0Yu.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./loader-B93v7E2S.mjs";export{e as loadConfig};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./preview-fcmKJ-7t.mjs";export{t as formatPreviewBlock,e as previewContent};
|
package/dist/start-DOTmfJ-6.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l as e}from"./start-Pye6UK9z.mjs";export{e as startCommand};
|