@inkeep/open-knowledge 0.5.0-beta.27 → 0.5.0-beta.29
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-9XRv4ouM.mjs +2 -0
- package/dist/{dist-D1HyCuHh.mjs → dist-C0nimAjR.mjs} +10 -10
- package/dist/{dist-DnmXfGWp.mjs → dist-Cne34K7V.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/init-CsMSp7be.mjs +1 -0
- package/dist/{init-CwWjtnYQ.mjs → init-DITZo5MW.mjs} +4 -4
- package/dist/{loader-DI-aJeHv.mjs → loader-C1XRvFmK.mjs} +2 -2
- package/dist/loader-C9nvsl4r.mjs +1 -0
- package/dist/{preview-CrCqux1_.mjs → preview-CNu5ET06.mjs} +2 -2
- package/dist/preview-CpsM6Oy_.mjs +1 -0
- package/dist/{repair-launch-json-C792vDvw.mjs → repair-launch-json-BE8BhJHf.mjs} +2 -2
- package/dist/{repair-mcp-configs-Cv8AjpGE.mjs → repair-mcp-configs-RaKlR1Tj.mjs} +2 -2
- package/dist/{src-mexJq_Rj.mjs → src-qd3O6KiT.mjs} +2 -2
- package/dist/{start-DXb8xQF1.mjs → start-BzeK2VhT.mjs} +2 -2
- package/dist/start-DIvt2h6l.mjs +1 -0
- package/package.json +2 -2
- package/dist/constants-Dy6rDbqx.mjs +0 -2
- package/dist/init-BBRgjZZW.mjs +0 -1
- package/dist/loader-B21ETXD-.mjs +0 -1
- package/dist/preview-BXTWMK3J.mjs +0 -1
- package/dist/start-C1vmnar4.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`), 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.29"
|
|
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{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as ne,Si as v,Ti as y,Ur as re,V as b,Vr as x,Wr as ie,Yn as ae,Yr as oe,_i as se,bi as ce,cr as le,fi as ue,it as de,ji as fe,ki as pe,m as me,ot as he,pn as ge,wi as _e,xi as S,yi as ve}from"./dist-
|
|
2
|
+
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as ne,Si as v,Ti as y,Ur as re,V as b,Vr as x,Wr as ie,Yn as ae,Yr as oe,_i as se,bi as ce,cr as le,fi as ue,it as de,ji as fe,ki as pe,m as me,ot as he,pn as ge,wi as _e,xi as S,yi as ve}from"./dist-C0nimAjR.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,w as je,x as Me,y as Ne}from"./init-DITZo5MW.mjs";import{c as Pe,f as Fe,l as Ie,n as Le,s as w}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Re}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as ze}from"./constants-9XRv4ouM.mjs";import{n as Be,t as Ve}from"./loader-C1XRvFmK.mjs";import{d as He,f as Ue,l as We,m as Ge,p as Ke,s as qe}from"./start-BzeK2VhT.mjs";import{c as Je,i as T,n as E,o as D,r as O,s as k,t as A}from"./colors-BNufdynn.mjs";import"./src-qd3O6KiT.mjs";import{execFileSync as Ye,spawn as Xe,spawnSync as j}from"node:child_process";import Ze,{basename as Qe,dirname as $e,isAbsolute as et,join as M,relative as tt,resolve as N}from"node:path";import{closeSync as nt,existsSync as P,mkdirSync as rt,mkdtempSync as it,openSync as at,readFileSync as F,readdirSync as ot,realpathSync as st,rmSync as ct,statSync as lt,unlinkSync as ut,writeFileSync as dt}from"node:fs";import ft from"node:process";import{homedir as pt,hostname as mt,tmpdir as ht}from"node:os";import{fileURLToPath as gt}from"node:url";import{AsyncLocalStorage as _t,AsyncResource as vt}from"node:async_hooks";import{stripVTControlCharacters as yt,styleText as I}from"node:util";import*as bt from"node:readline";import{randomUUID as xt}from"node:crypto";import{realpath as St}from"node:fs/promises";import{setTimeout as Ct}from"node:timers/promises";import{createInterface as wt}from"node:readline/promises";var Tt=fe();const Et=`open-knowledge`;var Dt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Et,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(Et,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(Et,e).deletePassword()}catch{}}},Ot=class{backend=`file`;authFile;constructor(e){this.authFile=e??M(pt(),`.ok`,`auth.yml`)}read(){if(!P(this.authFile))return{};try{return(0,Tt.parse)(F(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=$e(this.authFile);P(t)||rt(t,{recursive:!0,mode:448}),dt(this.authFile,(0,Tt.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 kt(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Et,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
3
3
|
`),new Dt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
|
|
4
4
|
`),new Ot(e)}}async function At(e,t,n){let r=jt(await Mt(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 jt(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 Mt(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 Nt(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 At(process.stdin,process.stdout,t);process.exit(n)}),n}function Pt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Ft(e,t,n){let r={baseUrl:Pt(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 It(e){let t=e.request||C,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Ft(t,`POST /login/device/code`,n)}async function Lt(e){let t=await Ft(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=Rt(e,t.data.expires_in),n.refreshTokenExpiresAt=Rt(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Rt(e,t){return new Date(e+t*1e3).toISOString()}async function zt(e,t){let n=Bt(e,t.auth);if(n)return n;let{data:r}=await It({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Ht(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Bt(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 Vt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Ht(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Lt({...i,clientType:`oauth-app`}):await Lt({...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 Vt(r.interval),Ht(e,t,n,r);if(a===`slow_down`)return await Vt(r.interval+7),Ht(e,t,n,r);throw i}}async function Ut(e,t){return zt(e,{auth:t})}async function Wt(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 zt(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Gt=`0.0.0-development`;function Kt(e){let t=e.request||C.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Gt} ${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(Ut.bind(null,i),{hook:Wt.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=Kt({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 Jt={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 Yt;(function(e){})(Yt||={});function Xt(e){return pe(ve,e)}function Zt(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Qt=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function $t(e){let t=e.toLowerCase().replace(/:\d+$/,``);Qt.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 en(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function tn(e,t,n=qt){let r=Zt(),{host:i,json:a}=e;$t(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?en(!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?en(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function nn(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 tn(t,await e())})}const rn=e=>e.name===`enter`||e.name===`return`;var an=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},on=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},sn=class extends Error{name=`ExitPromptError`},cn=class extends Error{name=`HookError`},ln=class extends Error{name=`ValidationError`};const un=new _t;function dn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function fn(e,t){let n=dn(e);return un.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function L(){let e=un.getStore();if(!e)throw new cn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function pn(){return L().rl}function mn(e){return vt.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 hn(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 gn(){L().handleChange()}const R={queue(e){let t=L(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(pn());if(r!=null&&typeof r!=`function`)throw new ln(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=L();mn(()=>{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 _n(e){return typeof e==`function`}function z(e){return hn(t=>{let n=vt.bind(function(e){t.get()!==e&&(t.set(e),gn())});if(t.initialized)return[t.get(),n];let r=_n(e)?e():e;return t.set(r),[r,n]})}function vn(e,t){hn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&R.queue(e),n.set(t)})}const yn={prefix:{idle:I(`blue`,`?`),done:I(`green`,Ae.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>I(`yellow`,e))},style:{answer:e=>I(`cyan`,e),message:e=>I(`bold`,e),error:e=>I(`red`,`> ${e}`),defaultAnswer:e=>I(`dim`,`(${e})`),help:e=>I(`dim`,e),highlight:e=>I(`cyan`,e),key:e=>I(`cyan`,I(`bold`,`<${e}>`))}};function bn(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 xn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=bn(n)&&bn(r)?xn(n,r):r}return t}function Sn(...e){return xn(yn,...e.filter(e=>e!=null))}function Cn({status:e=`idle`,theme:t}){let[n,r]=z(!1),[i,a]=z(0),{prefix:o,spinner:s}=Sn(t);return vn(()=>{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 wn(e){return z({current:e})[0]}function Tn(e){let t=wn(e);t.current=e,vn(e=>{let n=!1,r=mn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var En=e(we(),1);function Dn(e,t){return e.split(`
|
|
@@ -17,10 +17,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
|
|
|
17
17
|
`),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function Pr(e){return new t(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Nr(t,await e())})}function Fr(e){try{let t=Ye(`gh`,[`auth`,`token`,...e?[`--hostname`,e]:[]],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return t.length===0?{available:!1}:{available:!0,token:t}}catch{return{available:!1}}}async function Ir(e,t,n=Fr){let r=n(e);return r.available&&r.token?r.token:(await t.get(e))?.token??null}async function Lr(e,t){let{host:n,json:r}=e;$t(n);let i=await Ir(n,t);i??(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 Mr({auth:i,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Rr(e){return new t(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Lr(t,await e())})}async function zr(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function Br(e){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await zr(t,await e())})}async function Vr(e,t,n=Fr){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 Hr(e,t){let{host:n,json:r}=e;$t(n);let i=await Vr(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 Mr({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`})+`
|
|
18
18
|
`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Ur(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 Hr(t,await e())})}function Wr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>kt();return e.addCommand(nn(n)),e.addCommand(Ur(n)),e.addCommand(Rr(n)),e.addCommand(Br(n)),e.addCommand(Pr(n)),e.addCommand(Nt(n)),e}function V(e,t,n={}){let r=Ie(e,t);if(!P(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(F(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Pe(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??mt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Gr(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 Kr(e){let t=e.inspect??(t=>V(e.lockDir,t)),n=e.unlink??(e=>ut(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Gr(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(),Kr({lockDir:ae(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function Jr(e,t,n={},r=Fr){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`]}}function Yr(e){return e.replace(/:\d+$/,``)}function Xr(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Yr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Yr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Yr(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}const Zr=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Qr(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 Zr)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`)}async function $r(e,t,n,r=process.cwd()){let i=Xr(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?N(r,t.dir):N(r,i.name);if(P(a)&&ot(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await kt(),s=await Jr(i.hostname,o,{}),c=Re({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
19
19
|
`)){let n=Qr(e);n&&n.pct!==l&&(l=n.pct,H(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
|
|
20
|
-
`);try{let{runInit:e}=await import(`./init-
|
|
20
|
+
`);try{let{runInit:e}=await import(`./init-CsMSp7be.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{ei(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 ei(e){let t=M(e,`.git`,`info`,`exclude`);if(!P(t))return`no-exclude`;let n=F(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
|
|
21
21
|
`).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(dt(t,`${n}${n.length===0||n.endsWith(`
|
|
22
22
|
`)?``:`
|
|
23
|
-
`}.ok/\n`,`utf-8`),`appended`)}function ti(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 $r(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-
|
|
23
|
+
`}.ok/\n`,`utf-8`),`appended`)}function ti(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 $r(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-DIvt2h6l.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 ni=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function ri(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Be;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 ii(e){let t=(0,Tt.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of ni)t.hasIn(e)&&n.push(e.join(`.`));return n}function ai(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oi(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=ai(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function si(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??oe,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:m(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:m(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!P(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ii(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:oi(ni.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:ue(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 ci(){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(()=>{ri({}).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 si({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(Je(),1);const W=2e3,li=[/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 ui(e){return li.some(t=>t.test(e))}function di(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 et(e)?e:null}catch{return null}}function fi(e){let t=[];for(let n of e.split(`
|
|
24
24
|
`)){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)&&ui(a)&&t.push({pid:o,command:a})}return t}function pi(e){let t=[],n=e.split(`
|
|
25
25
|
`);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)&&ui(o)&&t.push({pid:s,command:o})}return t}async function mi(){let e=j(`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=fi(t);if(n.length>0||t.trim()===``)return n}let t=j(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?[]:pi(t.stdout)}function hi(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=Qe(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 gi(e){let t=j(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function _i(e){let t=j(`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 vi(e){let t=j(`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(`
|
|
26
26
|
`))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function yi(e){let t=[],n=e.split(`
|
|
@@ -57,7 +57,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
|
|
|
57
57
|
`,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]===`
|
|
58
58
|
`&&r++}}return[t,n]}var co=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=oo({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 lo={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}},uo=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??lo}async _authThenStart(){if(!this._authProvider)throw new J(`No auth provider`);let e;try{e=await La(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=Ki(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 co({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=p.parse(JSON.parse(e.data));g(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 La(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:d(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}=Va(o);if(this._resourceMetadataUrl=t,this._scope=n,await La(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}=Va(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 La(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(),ie(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=>p.parse(e)):[p.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 fo(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 po(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function mo(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function ho(e,t){return`http://${mo(e)}:${t}/mcp`}function go(e,t){return`ws://${mo(e)}:${t}`}function _o(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function vo(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function yo(e){return P(e)?F(e,`utf-8`).trim():``}function bo(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function xo(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function So(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 Co(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function wo(e){let t=e.readLock??(()=>Fe(e.lockDir)),n=e.isAlive??w,r=e.sleep??(e=>Ct(e)),i=e.spawn??Xe,a=e.readErrorLog??yo,o=e.openErrorLog??(e=>at(e,`w`)),s=e.closeFd??nt,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 ho(`localhost`,t)}let u=vo(t(),n);if(u!==void 0)return ho(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||rt(e.lockDir,{recursive:!0});let d=M(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=He();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=vo(t(),n);if(e!==void 0)return ho(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(bo(c,a(d)))}function To(e,t){if(e.portOverride!==void 0)return _o(t);let n=e.readLock??(()=>Fe(e.lockDir)),r=e.isAlive??w,i=vo(n(),r);if(i!==void 0)return go(`localhost`,i)}async function Eo(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Vi(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new uo(new URL(e),{fetch:fo(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=xo(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(Co(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=So(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 Do(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Eo,r=await wo(e),i=e.createConnectionId?.()??xt(),a=!1,o=(e.startKeepalive??Gi)({connectionId:i,resolveWsUrl:async()=>To(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 Oo=gt(import.meta.url);function ko(e){let t=N(e);for(;;){if(ge(t))return t;let n=$e(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 \`${se}\`).`);t=n}}function Ao(e){try{let t=new URL(e);return t.protocol===`file:`?gt(t):void 0}catch{return}}async function jo(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=Ao(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Mo(e,t){if(e!==void 0)return ko(e);let n=await t();if(n!==void 0)return ko(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 No(e){let t=process.stderr,n=e.spawnTimeoutMs??po(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,a=Ve({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),s=new x({name:o,version:Le},{instructions:he({dir:`.`})}),c=xt(),l={current:{connectionId:c,displayName:c,colorSeed:c}},u=new Map,d=e=>{if(u.has(e))return;let n=ee(e),r=l.current,i=Gi({connectionId:c,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>To({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});u.set(e,i)},f=()=>jo({getClientCapabilities:()=>s.server.getClientCapabilities(),listRoots:()=>s.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),p=e=>Mo(e,f),m=async e=>{let t;if(e===void 0){let e=await f();if(e===void 0)return;t=ko(e)}else t=ko(e);let i=await a(t),o=await wo({lockDir:ee(t),contentDir:h(i,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return d(t),o.replace(/\/mcp$/,``)};s.server.oninitialized=()=>{let e=s.server.getClientVersion(),t=le(e?.name,c);l.current={connectionId:c,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},i(s,{serverUrl:m,resolveCwd:p,config:a,identityRef:l});let g=new Vi,_=!1,te,ne=async()=>{if(_)return;_=!0,te?.stop();for(let e of u.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}u.clear();let e=await Promise.allSettled([s.close(),g.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 s.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
|
|
59
59
|
`);let v=!1,y=()=>{v||(v=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
60
|
-
`),process.exit(1)},5e3).unref(),ne().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,y),process.once(`SIGTERM`,y),process.platform===`darwin`){let e=Wi(Oo,{realpathSync:st,statInoSync:e=>lt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${Le}\n`);let{resolvedPath:n,inode:r}=e;te=Ui({detect:()=>Hi({bundleAnchorPath:Oo,currentInode:r,platform:process.platform,realpath:st,statInode:e=>lt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${Le} — exiting for host respawn\n`),y()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:ne}}function Po(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=po(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Do({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await No({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 Fo(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-
|
|
60
|
+
`),process.exit(1)},5e3).unref(),ne().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,y),process.once(`SIGTERM`,y),process.platform===`darwin`){let e=Wi(Oo,{realpathSync:st,statInoSync:e=>lt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${Le}\n`);let{resolvedPath:n,inode:r}=e;te=Ui({detect:()=>Hi({bundleAnchorPath:Oo,currentInode:r,platform:process.platform,realpath:st,statInode:e=>lt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${Le} — exiting for host respawn\n`),y()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:ne}}function Po(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=po(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Do({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await No({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 Fo(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-CpsM6Oy_.mjs`),r=e(),i=process.cwd(),a=h(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 Io(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Lo(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 Ro(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:hi(r),command:r,isDesktop:Io(r)}}function zo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Bo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&zo(e)?`ui-orphan`:`stale`}const Vo=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Ho(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 Uo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Wo(e){return`${Uo(e.server.usage)} | ${Uo(e.ui?.usage??null)}`}function Go(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ko(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=Bo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Go(e),Wo(e),t,String(n),Lo(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=Ho(Bo(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(`
|
|
61
61
|
`)}async function qo(e={}){let t=e.discover??bi,n=e.inspect??V,r=e.log??(e=>console.log(e)),i=e.resolveCommand??gi,a=e.resolveUsage??_i,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=Ro(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:Bo(e)}));r(JSON.stringify(e,null,2));return}r(Ko(e.all?s:s.filter(e=>Vo.has(Bo(e)))))}function Jo(){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 Yo(e,t,n=process.cwd()){let r=e.op??`sync`,i=Fe(ae(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=Re({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
|
|
62
62
|
`)),X(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Xo(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 Yo({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 Zo(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yo({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 Qo(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yo({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 $o(e){return typeof e==`string`&&f.includes(e)}async function es(e={}){let t=N(e.cwd??process.cwd()),r=e.pack??`knowledge-base`;if(!b[r])return{status:`failed`,message:`${O(`Error:`)} Unknown pack "${r}". Available: ${f.join(`, `)}`,exitCode:1};let i;try{i=await ne({projectDir:t,rootDir:e.root,packId:r})}catch(e){return e instanceof u?{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 t=b[r].name;if(e.personalTemplates&&!e.dryRun){let e=_();if(e.errors.length>0){let n=e.errors.map(e=>` ${k(`!`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${D(`Your ${t} pack is already seeded.`)}`,`${k(`Personal templates: some writes failed:`)}`,...n].join(`
|
|
63
63
|
`),plan:i,exitCode:1}}let n=e.written.length;if(n>0)return{status:`applied`,message:`${D(`Your ${t} pack is already seeded.`)}\n${D(`✓ Wrote ${n} personal template${n===1?``:`s`}`)} ${E(`to ~/.ok/templates/`)}`,plan:i,exitCode:0}}return{status:`no-op`,message:`${D(`Your ${t} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:i,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${A(`Plan (dry-run — no changes made):`)}\n\n${ns(i,t)}`,plan:i,exitCode:0};if(!e.yes&&!await rs(`${A(`Plan:`)}\n\n${ns(i,t)}\n\n${A(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:i,exitCode:0};let a=await n(i,{projectDir:t,packId:r});if(a.errors.length>0){let e=a.errors.map(e=>` ${O(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${k(`Applied`)} ${a.applied} entries, ${k(String(a.errors.length))} error(s):`,...e].join(`
|
|
@@ -1161,7 +1161,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
|
|
|
1161
1161
|
`,`
|
|
1162
1162
|
`).replaceAll(`\r`,`
|
|
1163
1163
|
`).split(`
|
|
1164
|
-
`))S(E)||collectHrefsFromLine(stripHtmlComments(E,w).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let S=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(S))return null;let w=resolveAssetProjectPath(t,e.fromDocName);if(!w)return null;let E=resolve(e.contentDir,w),D,O;try{if(D=normalize(realpathSync(E)),!isWithinContentDir(D,e.contentDir))return null;O=statSync(D)}catch(t){let S=errnoCode$1(t);return S!==`ENOENT`&&S!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return O.isFile()?{absolutePath:D,relativePath:toContentRelativePath(e.contentDir,D),stat:O}:null}function toContentRelativePath(e,t){let S=normalize(realpathSync(e));return normalize(t).slice(S.length+(S.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let S=new Map;for(let[w,E]of e.fileIndex){let D=e.readMarkdown(E.canonicalPath);if(D!==null)for(let E of extractLocalAssetHrefs(D)){let D=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:w,href:E});if(!D||e.isExcluded?.(D.relativePath))continue;let O=mediaKindForAssetPath(D.absolutePath),k=S.get(D.relativePath);if(k){k.referencedBy.includes(w)||k.referencedBy.push(w);continue}S.set(D.relativePath,{kind:`asset`,path:D.relativePath,assetExt:extname(D.relativePath).toLowerCase(),mediaKind:O,size:D.stat.size,modified:D.stat.mtime.toISOString(),referencedBy:[w]})}}return[...S.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:S,inlineExtensions:w,assetExtensions:E,blocklistExtensions:D}=e;return(e,O,k)=>{let j;try{j=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return k()}let F=extname(j).slice(1).toLowerCase(),L=F===`md`||F===`mdx`;if(!j||t.isPathIgnored(j)||!L&&!E.has(F))return k();O.setHeader(`X-Content-Type-Options`,`nosniff`),L||(w.has(F)?O.setHeader(`Content-Disposition`,`inline`):O.setHeader(`Content-Disposition`,`attachment`)),F===`svg`&&O.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),S(e,O,()=>{if(!O.headersSent){if(E.has(F)||D.has(F)){O.statusCode=404,O.end();return}k()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let S=resolve(e),w=resolve(S,t),E=relative(S,w);return E===``?{ok:!0,abs:w,rel:``}:E===`..`||E.startsWith(`../`)||isAbsolute(E)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:w,rel:E}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string$2().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function textPlusStructured(e,t,S){let w={
|
|
1164
|
+
`))S(E)||collectHrefsFromLine(stripHtmlComments(E,w).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let S=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(S))return null;let w=resolveAssetProjectPath(t,e.fromDocName);if(!w)return null;let E=resolve(e.contentDir,w),D,O;try{if(D=normalize(realpathSync(E)),!isWithinContentDir(D,e.contentDir))return null;O=statSync(D)}catch(t){let S=errnoCode$1(t);return S!==`ENOENT`&&S!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return O.isFile()?{absolutePath:D,relativePath:toContentRelativePath(e.contentDir,D),stat:O}:null}function toContentRelativePath(e,t){let S=normalize(realpathSync(e));return normalize(t).slice(S.length+(S.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let S=new Map;for(let[w,E]of e.fileIndex){let D=e.readMarkdown(E.canonicalPath);if(D!==null)for(let E of extractLocalAssetHrefs(D)){let D=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:w,href:E});if(!D||e.isExcluded?.(D.relativePath))continue;let O=mediaKindForAssetPath(D.absolutePath),k=S.get(D.relativePath);if(k){k.referencedBy.includes(w)||k.referencedBy.push(w);continue}S.set(D.relativePath,{kind:`asset`,path:D.relativePath,assetExt:extname(D.relativePath).toLowerCase(),mediaKind:O,size:D.stat.size,modified:D.stat.mtime.toISOString(),referencedBy:[w]})}}return[...S.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:S,inlineExtensions:w,assetExtensions:E,blocklistExtensions:D}=e;return(e,O,k)=>{let j;try{j=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return k()}let F=extname(j).slice(1).toLowerCase(),L=F===`md`||F===`mdx`;if(!j||t.isPathIgnored(j)||!L&&!E.has(F))return k();O.setHeader(`X-Content-Type-Options`,`nosniff`),L||(w.has(F)?O.setHeader(`Content-Disposition`,`inline`):O.setHeader(`Content-Disposition`,`attachment`)),F===`svg`&&O.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),S(e,O,()=>{if(!O.headersSent){if(E.has(F)||D.has(F)){O.statusCode=404,O.end();return}k()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let S=resolve(e),w=resolve(S,t),E=relative(S,w);return E===``?{ok:!0,abs:w,rel:``}:E===`..`||E.startsWith(`../`)||isAbsolute(E)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:w,rel:E}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string$2().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string$2().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude Code / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,S){let w={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:w,...S?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
|
|
1165
1165
|
|
|
1166
1166
|
Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
|
|
1167
1167
|
|
|
@@ -2454,7 +2454,7 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
2454
2454
|
`}const DESCRIPTION$27=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
|
|
2455
2455
|
`);function register$27(e,t){e.tool(`consolidate`,DESCRIPTION$27,{topic:string$2().describe(`The topic to consolidate into a canonical article`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`electron-protocol`,`lock`],ELECTRON_PROTOCOL_ENV_VAR=`OK_ELECTRON_PROTOCOL_HOST`;function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}async function resolvePreviewUrlForTool(e,t,S){let w=S??await t.resolveCwd(),E=resolveContentDir(await resolveConfig(t.config,w),w);return resolvePreviewUrl(e,{lockDir:resolveLockDir(w),contentDir:E})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function buildListResolver(e,t){let S=t??await e.resolveCwd(),w=resolveContentDir(await resolveConfig(e.config,S),S),E={lockDir:resolveLockDir(S),contentDir:w};return{resolve:e=>resolvePreviewUrl(e,E),ui:resolveUiInfo(E)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let S=`/#/${encodeDocName(e)}`;if(process.env[ELECTRON_PROTOCOL_ENV_VAR]===`1`&&t.contentDir)try{let S=realpathSync(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(S)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${S}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$26=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `get_backlinks({ docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.',"- Deletion is irreversible from this tool. Use `save_version` beforehand if you may need to roll back.","- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
|
|
2456
2456
|
`);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function register$26(e,t){e.tool(`delete_document`,DESCRIPTION$26,{docName:string$2().describe(`Document name to delete`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(E,`/api/delete-path`,{kind:`file`,path:D.docName,...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok){let e=k.error,t={ok:!1,error:e};return textPlusStructured(`Error: ${e}`,t,!0)}let j=parseDeletedDocNames(k.deletedDocNames),F=await resolvePreviewUrlForTool(D.docName,{config:t.config,resolveCwd:t.resolveCwd},w),L={ok:!0,deletedDocNames:j.length>0?j:[D.docName],...F?{previousPreviewUrl:F.url}:{}};return textPlusStructured(L.deletedDocNames.length===1?`Deleted ${L.deletedDocNames[0]}.`:`Deleted ${L.deletedDocNames.length} documents: ${L.deletedDocNames.join(`, `)}.`,L)})}const DESCRIPTION$25=[`[Operates on disk; no running OK server required] Delete a template.`,``,"**Targets.** Mirrors `write_template`:",'- `target: "project"` (default) — deletes `<folder>/.ok/templates/<name>.md` from the current project.','- `target: "user"` — deletes `~/.ok/templates/<name>.md` from the user-global library. The `folder` argument is ignored.',``,"Idempotent: deleting a template that does not exist returns success with `existed: false`. Auto-cleans empty `<folder>/.ok/templates/` and `<folder>/.ok/` directories.",``,`**Parameters:**`,'- `folder` — Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.',"- `name` — Template filename without `.md` extension.",'- `target` (optional) — `"project"` (default) or `"user"`.'].join(`
|
|
2457
|
-
`),InputSchema$7={folder:string$2().describe('Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.'),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only.").describe("Template filename without `.md` extension."),target:_enum([`project`,`user`]).optional().describe('Where the template lives. `"project"` (default) deletes from `<folder>/.ok/templates/`; `"user"` deletes from `~/.ok/templates/` (folder ignored).'),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$7={result:union([object$1({ok:literal(!0),path:string$2(),existed:boolean$1(),cleanedEmpty:object$1({templatesDir:boolean$1(),okDir:boolean$1()})}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])};function register$25(e,t){e.registerTool(`delete_template`,{description:DESCRIPTION$25,inputSchema:InputSchema$7,outputSchema:OutputSchema$7,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E={projectDir:w,folder:e.folder,name:e.name};e.target!==void 0&&(E.target=e.target);let D=applyTemplateDelete(E);if(!D.ok)return{isError:!0,structuredContent:{result:D},content:[{type:`text`,text:`${D.error.code}: ${D.error.message}`}]};let O=[D.existed?`Deleted template at ${D.path}`:`Template at ${D.path} did not exist (no-op)`];return D.cleanedEmpty.templatesDir&&O.push(`Removed empty .ok/templates/ directory`),D.cleanedEmpty.okDir&&O.push(`Removed empty .ok/ directory`),textPlusStructured(O.join(`
|
|
2457
|
+
`),InputSchema$7={folder:string$2().describe('Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.'),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only.").describe("Template filename without `.md` extension."),target:_enum([`project`,`user`]).optional().describe('Where the template lives. `"project"` (default) deletes from `<folder>/.ok/templates/`; `"user"` deletes from `~/.ok/templates/` (folder ignored).'),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$7=outputSchemaWithText({result:union([object$1({ok:literal(!0),path:string$2(),existed:boolean$1(),cleanedEmpty:object$1({templatesDir:boolean$1(),okDir:boolean$1()})}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])});function register$25(e,t){e.registerTool(`delete_template`,{description:DESCRIPTION$25,inputSchema:InputSchema$7,outputSchema:OutputSchema$7,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E={projectDir:w,folder:e.folder,name:e.name};e.target!==void 0&&(E.target=e.target);let D=applyTemplateDelete(E);if(!D.ok)return{isError:!0,structuredContent:{result:D},content:[{type:`text`,text:`${D.error.code}: ${D.error.message}`}]};let O=[D.existed?`Deleted template at ${D.path}`:`Template at ${D.path} did not exist (no-op)`];return D.cleanedEmpty.templatesDir&&O.push(`Removed empty .ok/templates/ directory`),D.cleanedEmpty.okDir&&O.push(`Removed empty .ok/ directory`),textPlusStructured(O.join(`
|
|
2458
2458
|
`),{result:D})})}function buildDiscoverBody(e){return`# Discover — Project Convention Extraction + Link Graph Activation
|
|
2459
2459
|
|
|
2460
2460
|
You're invoked because (a) the user explicitly asked to set up an existing repo, OR (b) \`list_documents\` surfaced a hint because content exists with no folder frontmatter / templates configured. Your job: **extract conventions from existing siblings + activate the link graph, leaving the repo more structured and more navigable than you found it.**
|
|
@@ -2771,7 +2771,7 @@ Link-graph activation:
|
|
|
2771
2771
|
- **User aborts at any STOP gate** → exit cleanly, leaving any already-applied proposals in place (apply is per-phase, not all-or-nothing).
|
|
2772
2772
|
- **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
|
|
2773
2773
|
`}const DESCRIPTION$24=[`Set up an existing repo for Open Knowledge by extracting conventions from existing siblings + activating the link graph. Multi-step instructional body with seven phases and per-phase user-confirmation STOP gates.`,``,`**Use when:**`,`- First arrival at a repo that has existing markdown content AND no folder frontmatter / templates configured`,"- `list_documents` returns empty `frontmatter_defaults` + empty `templates_available` for substantial folders",`- User explicitly asks to onboard / set up / configure an existing repo`,``,`**Do NOT invoke when:**`,"- The repo is empty (< 5 .md files) — use `ok seed` instead",`- The repo is already fully configured (every substantial folder has folder frontmatter + templates)`,``,'One-shot per project. Idempotent on re-run — detects prior configuration and switches to "extend mode" (proposes additions only, never re-proposes existing artifacts). **Requires the OK Hocuspocus server running** — most primitives the body composes (`list_documents`, `read_document`, link-graph) hit the server. Phase 1 step 0 enforces this; if the server is down, the tool exits cleanly with a "run `open-knowledge start`" instruction. Only `exec`, `set_folder_rule`, `write_template`, and the `.okignore` write are fs-direct.',``,"**Composes existing primitives only** — no new MCP tools, no schema changes. Uses `exec`, `list_documents`, `read_document`, `search`, `set_folder_rule`, `write_template`, `get_orphans`, `get_hubs`, `get_dead_links`, `get_backlinks`, `get_forward_links`, `suggest_links`, `edit_document`."].join(`
|
|
2774
|
-
`),InputSchema$6={cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6={previewUrl:_null()};function register$24(e,t){e.registerTool(`discover`,{description:DESCRIPTION$24,inputSchema:InputSchema$6,outputSchema:OutputSchema$6,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return S.ok?textPlusStructured(buildDiscoverBody(S.config.content.dir),{previewUrl:null}):textResult(`Error: ${S.error}`,!0)})}const DESCRIPTION$23=`${[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,'**Body-only.** Frontmatter-intersecting find/replace calls are rejected with HTTP 400. Frontmatter editing via MCP is currently unavailable — to change frontmatter, use `write_document` with `position: "replace"` and a payload that includes the new YAML block.',``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
2774
|
+
`),InputSchema$6={cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6=outputSchemaWithText({previewUrl:_null()});function register$24(e,t){e.registerTool(`discover`,{description:DESCRIPTION$24,inputSchema:InputSchema$6,outputSchema:OutputSchema$6,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return S.ok?textPlusStructured(buildDiscoverBody(S.config.content.dir),{previewUrl:null}):textResult(`Error: ${S.error}`,!0)})}const DESCRIPTION$23=`${[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,'**Body-only.** Frontmatter-intersecting find/replace calls are rejected with HTTP 400. Frontmatter editing via MCP is currently unavailable — to change frontmatter, use `write_document` with `position: "replace"` and a payload that includes the new YAML block.',``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
2775
2775
|
`)}\n${renderInventoryFooter()}`;function register$23(e,t){e.tool(`edit_document`,DESCRIPTION$23,{docName:string$2().describe(`Document name to edit`),find:string$2().describe(`Text to find (exact match)`),replace:string$2().describe(`Replacement text`),offset:number$1().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(E,`/api/agent-patch`,{docName:D.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=resolveLockDir(w),F=resolvePreviewUrl(D.docName,{lockDir:j}),L=typeof k.subscriberCount==`number`?k.subscriberCount:void 0,B=(typeof k.systemSubscriberCount==`number`?k.systemSubscriberCount:void 0)===0,H=L===0,q=k.summary&&typeof k.summary==`object`?k.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y=[`Edit applied successfully.`];F&&Y.push(`Preview: ${F.url}`),B&&Y.push(F?`Open ${F.url} in your preview browser.`:`No preview attached. Start the UI.`),J&&Y.push(J);let ee=Y.join(`
|
|
2776
2776
|
`);if(!F&&!B&&!H&&!q)return textResult(ee);let te={};return F&&(te.previewUrl=F.url,te.previewUrlSource=F.source),B&&(te.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:F?.url??null}),q&&(te.summary=q),textPlusStructured(ee,te)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let S=nonFlagArgs(argsOf(t)),w=S.length>0?S[S.length-1]:``,E=w&&w!==`.`?normalize$1(w):``,D=[];E&&D.push(E);for(let t of e.split(`
|
|
2777
2777
|
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let S=E?`${E}/${e}`:e;D.push(S)}return D}function extractFromGrep(e){let t=[];for(let S of e.split(`
|
|
@@ -2785,8 +2785,8 @@ Link-graph activation:
|
|
|
2785
2785
|
`)}async function classifyPaths(e,t){let S=[],w=[];return await Promise.all(t.map(async t=>{try{let E=await stat$1(resolve(e,t));E.isDirectory()?w.push(t):E.isFile()&&S.push(t)}catch{/\.(md|mdx)$/i.test(t)&&S.push(t)}})),{files:S,dirs:w}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let S=t(docNameFromPath(e.path));return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}})}async function buildExecResult(e,t){let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${S.error}`);let{cwd:w,config:E,url:D}=S,O=parseCommand(e.command);if(`error`in O)return errorCategoryResult(O.error.category,O.error.message);let k=augmentStagesWithExcludes(O.stages),j=serializeStages(k),F=await snapshotMtimes(w),L=createBashInstance(w),B=``,H=``;try{let e=await execBash(L,j);B=e.stdout,H=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let q=await snapshotMtimes(w),J=diffMtimes(F.snapshot,q.snapshot);if(J.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${J.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let Y=applySoftCap(B),ee=extractReferencedPaths(B,k).filter(e=>resolveWithinRoot(w,e).ok),{files:te,dirs:ne}=await classifyPaths(w,ee),ae=k.length===1&&k[0].command===`cat`&&te.length===1,oe=await Promise.all(te.map(e=>enrichPath(e,{projectDir:w,serverUrl:D},{includeRichFields:ae}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),se=await Promise.all(ne.map(e=>enrichDirectory(e,{projectDir:w}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!ae&&D&&oe.length>0){let e=await fetchBacklinkCountsBatch(D,oe.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of oe){let S=e.get(pathToDocName$1(t.path));typeof S==`number`&&(t.backlinkCount=S)}}let ce=new Map(oe.map(e=>[e.path,e])),ue=new Map(se.map(e=>[e.path,e])),de=[];for(let e of ee){let t=ce.get(e);if(t){de.push(t);continue}let S=ue.get(e);S&&de.push(S)}let fe=detectBinaryArgs(k),me=[];fe.length>0&&me.push(`File${fe.length>1?`s`:``} ${fe.join(`, `)} appear${fe.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let ge=detectHeadTailTruncation(k,B);ge&&me.push(ge.banner),H&&me.push(`stderr: ${H.trim()}`);let _e=me.length>0?`${me.join(`
|
|
2786
2786
|
`)}\n\n`:``,ve=buildStdoutProvenance(k,ue,ce)+Y.text,ye=`${_e}${ve}${formatEnrichedBlock(de)}`,{resolve:Ce,ui:we}=await buildListResolver({config:E,resolveCwd:async()=>w}),Te=withPreviewUrls(de,Ce),De=we;return textPlusStructured(ye,{enrichedPaths:Te,stdout:ve,stdoutTruncated:Y.truncated,cwd:w,...De?{ui:De}:{},...me.length>0?{warnings:me}:{}})}function register$22(e,t){e.tool(`exec`,DESCRIPTION$22,{command:string$2().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:string$2().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{return await buildExecResult(e,t)}catch(e){return errorCategoryResult(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const DESCRIPTION$21=[`[Requires: Hocuspocus server] Find all pages that link to a given page.`,`Returns source page names, resolved titles, and context snippets as JSON.`,``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
2787
2787
|
`);function register$21(e,t){e.tool(`get_backlinks`,DESCRIPTION$21,{docName:string$2().describe(`Target page docName`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=await httpGet(E,`/api/backlinks?docName=${encodeURIComponent(D.docName)}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=j,{resolve:L,ui:B}=await buildListResolver(t,w),H=(F.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,S=t?L(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),q={...F,backlinks:H,ui:B,cwd:w};return textPlusStructured(JSON.stringify(q,null,2),q)})}const ID_CARDINALITY_CAP=32,DESCRIPTION$20=["[Operates on registry data; no running OK server required] Return full per-entry details for the canonical components an agent picked from the inventory rendered in the `write_document` / `edit_document` tool descriptions.",``,"Each entry carries: literal source-form `example` (copy-pasteable) + form-aware `params` (every prop, with `type` / `values?` / `required` / `defaultValue?` / `description`). Unmatched ids surface in `notFound` rather than failing the call.",``,`**Parameters:**`,`- \`ids\` — Array of canonical ids picked from the write-tool inventory (e.g. \`["Callout", "Tabs"]\`). Max ${ID_CARDINALITY_CAP} ids per call. Case-sensitive — must match the inventory exactly (\`Callout\` not \`callout\`; \`img\` not \`Image\`).`,"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2788
|
-
`),InputSchema$5={ids:array(string$2().min(1)).max(ID_CARDINALITY_CAP).describe(`Array of canonical ids to fetch. Max ${ID_CARDINALITY_CAP} ids per call. Empty array returns an empty components list.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},ParamSchema=object$1({name:string$2(),type:_enum([`string`,`boolean`,`number`,`enum`,`reactnode`]),values:array(string$2()).optional(),required:boolean$1(),defaultValue:union([string$2(),boolean$1(),number$1()]).optional(),description:string$2().optional(),omitOnDefault:literal(!0).optional(),advanced:literal(!0).optional(),language:_enum([`mermaid`,`latex`,`html`,`json`,`yaml`,`javascript`,`markdown`]).optional(),accept:array(string$2()).optional()}),ComponentEntrySchema=object$1({id:string$2(),displayName:string$2(),description:string$2(),kind:_enum([`jsx-block`,`jsx-void`]),example:string$2(),params:array(ParamSchema)}),OutputSchema$5={version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(ComponentEntrySchema).describe(`Full per-entry details for ids that matched.`),notFound:array(string$2()).describe(`Ids that did not match any canonical descriptor.`)};function register$20(e,t){e.registerTool(`get_components`,{description:DESCRIPTION$20,inputSchema:InputSchema$5,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t=getAgentCanonicalDescriptors(),S=new Map(t.map(e=>[e.name,e])),w=[],E=[],D=new Set;for(let t of e.ids){if(D.has(t))continue;D.add(t);let e=S.get(t);if(e===void 0){E.push(t);continue}w.push(projectFull(e))}let O={version:1,components:w,notFound:E};return textPlusStructured(JSON.stringify(O,null,2),O)})}const DESCRIPTION$19=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, `github.*`, and `preview.*` config sub-trees were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or hardcoded behavior, in the case of `preview.*`). Reading those paths returns `exists: false`.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["content"]` returns the content sub-tree; `["appearance", "theme"]` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2789
|
-
`),InputSchema$4={path:array(string$2()).optional().describe(`Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4={value:unknown$2().describe(`Resolved config value at the requested path (or full config).`),exists:boolean$1().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:array(string$2()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)};function readConfigPath(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S)return;S=S[e]}return S}function register$19(e,t){e.registerTool(`get_config`,{description:DESCRIPTION$19,inputSchema:InputSchema$4,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let w=e.path??[],E=w.length>0?readConfigPath(S.config,w):S.config;return w.length>0&&E===void 0?textPlusStructured(`(no value at ${w.join(`.`)})`,{value:null,exists:!1,path:w}):textPlusStructured(JSON.stringify(E,null,2),{value:E,exists:!0,path:w})})}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
|
|
2788
|
+
`),InputSchema$5={ids:array(string$2().min(1)).max(ID_CARDINALITY_CAP).describe(`Array of canonical ids to fetch. Max ${ID_CARDINALITY_CAP} ids per call. Empty array returns an empty components list.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},ParamSchema=object$1({name:string$2(),type:_enum([`string`,`boolean`,`number`,`enum`,`reactnode`]),values:array(string$2()).optional(),required:boolean$1(),defaultValue:union([string$2(),boolean$1(),number$1()]).optional(),description:string$2().optional(),omitOnDefault:literal(!0).optional(),advanced:literal(!0).optional(),language:_enum([`mermaid`,`latex`,`html`,`json`,`yaml`,`javascript`,`markdown`]).optional(),accept:array(string$2()).optional()}),ComponentEntrySchema=object$1({id:string$2(),displayName:string$2(),description:string$2(),kind:_enum([`jsx-block`,`jsx-void`]),example:string$2(),params:array(ParamSchema)}),OutputSchema$5=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(ComponentEntrySchema).describe(`Full per-entry details for ids that matched.`),notFound:array(string$2()).describe(`Ids that did not match any canonical descriptor.`)});function register$20(e,t){e.registerTool(`get_components`,{description:DESCRIPTION$20,inputSchema:InputSchema$5,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t=getAgentCanonicalDescriptors(),S=new Map(t.map(e=>[e.name,e])),w=[],E=[],D=new Set;for(let t of e.ids){if(D.has(t))continue;D.add(t);let e=S.get(t);if(e===void 0){E.push(t);continue}w.push(projectFull(e))}let O={version:1,components:w,notFound:E};return textPlusStructured(JSON.stringify(O,null,2),O)})}const DESCRIPTION$19=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, `github.*`, and `preview.*` config sub-trees were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or hardcoded behavior, in the case of `preview.*`). Reading those paths returns `exists: false`.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["content"]` returns the content sub-tree; `["appearance", "theme"]` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2789
|
+
`),InputSchema$4={path:array(string$2()).optional().describe(`Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({value:unknown$2().describe(`Resolved config value at the requested path (or full config).`),exists:boolean$1().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:array(string$2()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)});function readConfigPath(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S)return;S=S[e]}return S}function register$19(e,t){e.registerTool(`get_config`,{description:DESCRIPTION$19,inputSchema:InputSchema$4,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let w=e.path??[],E=w.length>0?readConfigPath(S.config,w):S.config;return w.length>0&&E===void 0?textPlusStructured(`(no value at ${w.join(`.`)})`,{value:null,exists:!1,path:w}):textPlusStructured(JSON.stringify(E,null,2),{value:E,exists:!0,path:w})})}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Find missing internal page targets across the corpus.`,`Returns grouped dead links keyed by missing target with source-doc rows as JSON.`,``,`**Parameters:**`,"- `sourceDocNames` (optional) — Referring source docs to narrow the audit with OR semantics"].join(`
|
|
2790
2790
|
`);function register$18(e,t){e.tool(`get_dead_links`,DESCRIPTION$18,{sourceDocNames:array(string$2()).optional().describe(`Referring source docs to narrow the audit with OR semantics`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=new URLSearchParams;for(let t of e.sourceDocNames??[]){let e=normalizeDocName(t);if(!e.ok)return textResult(e.error,!0);D.append(`sourceDocName`,e.docName)}let O=D.toString(),k=await httpGet(E,`/api/dead-links${O?`?${O}`:``}`);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{ok:j,...F}=k,L=F,{resolve:B,ui:H}=await buildListResolver(t,w),q=(L.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,S=t?B(t):null,w=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,S=t?B(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}});return{...e,sources:w,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),J={...L,deadLinks:q,ui:H,cwd:w};return textPlusStructured(JSON.stringify(J,null,2),J)})}const DESCRIPTION$17=[`[Requires: Hocuspocus server] Find all pages that a given page links to.`,`Returns forward links as JSON.`,``,`**Parameters:**`,"- `docName` — Source page docName, typically without extension. A trailing `.md` or `.mdx` is stripped automatically."].join(`
|
|
2791
2791
|
`);function register$17(e,t){e.tool(`get_forward_links`,DESCRIPTION$17,{docName:string$2().describe(`Source page docName`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=await httpGet(E,`/api/forward-links?docName=${encodeURIComponent(D.docName)}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=j,{resolve:L,ui:B}=await buildListResolver(t,w),H=(F.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,S=t?L(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),q={...F,forwardLinks:H,ui:B,cwd:w};return textPlusStructured(JSON.stringify(q,null,2),q)})}const DESCRIPTION$16=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry includes a commit SHA that can be passed to `rollback_to_version`.",``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
|
|
2792
2792
|
`);function register$16(e,t){e.tool(`get_history`,DESCRIPTION$16,{docName:string$2().describe(`Document name to query history for`),branch:string$2().optional().describe(`Branch name (default: current branch)`),limit:number$1().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number$1().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:string$2().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string$2().optional().describe(`Exclude entries by this author name or email`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=new URLSearchParams;O.set(`docName`,D.docName),e.branch&&O.set(`branch`,e.branch),e.limit!=null&&O.set(`limit`,String(e.limit)),e.offset!=null&&O.set(`offset`,String(e.offset)),e.type&&O.set(`type`,e.type),e.author&&O.set(`author`,e.author),e.excludeAuthor&&O.set(`excludeAuthor`,e.excludeAuthor);let k=await httpGet(E,`/api/history?${O.toString()}`);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{ok:j,...F}=k,L=await resolvePreviewUrlForTool(D.docName,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(JSON.stringify(F,null,2),{...F,previewUrl:L?.url??null,...L?{previewUrlSource:L.source}:{}})})}const DESCRIPTION$15=[`[Requires: Hocuspocus server] Find the most-linked pages in the knowledge graph.`,`Returns hub pages ordered by inbound link count as JSON.`,``,`**Parameters:**`,"- `limit` (optional) — Maximum number of hubs to return (default 20)"].join(`
|
|
@@ -2794,7 +2794,7 @@ Link-graph activation:
|
|
|
2794
2794
|
`);function register$14(e,t){e.tool(`get_orphans`,DESCRIPTION$14,{mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=await httpGet(E,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let{ok:O,...k}=D,j=k,{resolve:F,ui:L}=await buildListResolver(t,w),B=(j.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,S=t?F(t):null;return{...e,previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}}),H={...j,orphans:B,ui:L,cwd:w};return textPlusStructured(JSON.stringify(H,null,2),H)})}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`Library`,`Applications`,`.Trash`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function createContentFilter(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O,k,j,F=0,L=0,B=0;function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[],H=0,q=0;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=readFileSync(E,`utf-8`);H+=t.length;let S=parseIgnorePatterns(t);w.push(...S),e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);H+=t.length,q++;let S=parseIgnorePatterns(t).map(e=>prefixPattern(e,E));e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let J={value:H};q+=loadNestedIgnoreFiles(S,t,e,J),H=J.value;let Y=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return O=e,k=w,j=Y,F=w.length,L=q,B=H,{patternCount:F,nestedFileCount:L,bytes:B}}H();let q=new Map;function J(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}populateDirCount(S,``,J,q);function Y(e){let t=stripDocExtension(e);if(isSystemDoc(t)||isConfigDoc(t))return!0;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:J(e)}return{isExcluded(e){if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),S=t===`.`?``:t;if((q.get(S)??0)>0)return!1}return!0},isDirExcluded(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)||O.ignores(`${t}/`)},isPathIgnored(e){return Y(e)},getWatcherIgnoreGlobs(){return j},incrementMdDir(e){let t=e===`.`?``:e;q.set(t,(q.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=q.get(t)??0;S<=1?q.delete(t):q.set(t,S-1)},rebuildDirCount(){let e=new Map(q);q.clear();try{populateDirCount(S,``,J,q)}catch(t){for(let[t,S]of e)q.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,E=k,D=j,Y=F,ee=L,te=B,ne=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async ae=>{try{let t=H();q.clear(),populateDirCount(S,``,J,q);let E=Date.now()-ne;if(ae.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E},`content-filter rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E}}catch(w){O=t,k=E,j=D,F=Y,L=ee,B=te,q.clear();try{populateDirCount(S,``,J,q)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let H=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(H)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:H}}}})}}}function populateDirCount(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let D of E){let E=t?`${t}/${D.name}`:D.name;if(D.isDirectory()){if(BUILTIN_SKIP_DIRS.has(D.name)||S(E)||S(`${E}/`))continue;populateDirCount(join(e,D.name),E,S,w)}else D.isFile()&&isSupportedDocFile(D.name)&&!S(E)&&w.set(t,(w.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
2795
2795
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let D=0;for(let O of E){if(!O.isDirectory()||BUILTIN_SKIP_DIRS.has(O.name))continue;let E=join(e,O.name),k=relative(t,E);if(!k.startsWith(`..`)&&!(S.ignores(k)||S.ignores(`${k}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(E,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);w.value+=e.length;let E=parseIgnorePatterns(e).map(e=>prefixPattern(e,k));S.add(E),D++}catch(S){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,S)}}D+=loadNestedIgnoreFiles(E,t,S,w)}}return D}async function initContentDirStateAsync(e,t,S,w,E,D,O){let k;try{k=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let j of k){let k=t?`${t}/${j.name}`:j.name;if(j.isDirectory()){if(BUILTIN_SKIP_DIRS.has(j.name))continue;let t=join(e,j.name);if(!D){let e=relative(S,t);if(e.startsWith(`..`)||w.ignores(e)||w.ignores(`${e}/`))continue;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${S} at ${E}:`,e)}}}await initContentDirStateAsync(t,k,S,w,E,D,O)}else if(j.isFile()&&isSupportedDocFile(j.name)){if(!D){let e=E?`${E}/${k}`:k;if(w.ignores(e))continue}O.set(t,(O.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O=(0,import_ignore.default)(),k=[],j=new Map;function F(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}function L(e){let t=stripDocExtension(e);if(isSystemDoc(t)||isConfigDoc(t))return!0;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:F(e)}async function B(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[];for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=parseIgnorePatterns(await readFile$1(w,`utf-8`));e.add(t.map(e=>prefixPattern(e,E)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let F=new Map;await initContentDirStateAsync(S,``,t,e,E,D,F),O=e,k=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),j.clear();for(let[e,t]of F)j.set(e,t)}return await B(),{isExcluded(e){if(L(e))return!0;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),S=t===`.`?``:t;if((j.get(S)??0)>0)return!1}return!0},isDirExcluded(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)||O.ignores(`${t}/`)},isPathIgnored(e){return L(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;j.set(t,(j.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=j.get(t)??0;S<=1?j.delete(t):j.set(t,S-1)},rebuildDirCount(){let e=new Map(j);j.clear();try{populateDirCount(S,``,F,j)}catch(t){for(let[t,S]of e)j.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,S=k,E=new Map(j),D=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async F=>{try{await B();let t=Date.now()-D;if(F.setAttributes({"ok.ignore.pattern_count":k.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:k.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(w){O=t,k=S,j.clear();for(let[e,t]of E)j.set(e,t);let D=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(D)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:D}}}})}}}const DESCRIPTION$13=["Find every line that literally contains a string, grouped by file with frontmatter metadata. For ranked retrieval that mirrors cmd-K, use `search`.",``,`Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding every occurrence of a literal phrase across the wiki`,`- Auditing a term, identifier, or quote — coverage matters more than ranking`,``,"**When the project has `.ok/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.ok/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match","- `cwd` (optional) — Project root the grep runs against. Defaults only when the MCP client advertises exactly one root."].join(`
|
|
2796
2796
|
`);function groupByFile(e){let t=new Map;for(let S of e){let e=t.get(S.path);e?e.push(S):t.set(S.path,[S])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function buildGrepResult(e,t){let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)throw Error(S.error);let{cwd:w,config:E,url:D}=S,O=50,k=await grep(e.query,w,{caseInsensitive:!(e.case_sensitive??!1),include:[`**/*.md`,`**/*.mdx`],exclude:[`node_modules`,`.git`,`.claude`,`.changeset`,`.ok`],maxResults:51}),j=resolveContentDir(E,w),F=createContentFilter({projectDir:w,contentDir:j}),L=k.filter(e=>{let t=relative(j,resolve(w,e.path));return t.startsWith(`..`)?!1:!F.isExcluded(t)}),B=k.length>50,H=L.slice(0,50),{resolve:q,ui:J}=await buildListResolver({config:E,resolveCwd:async()=>w},w);if(H.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:J,cwd:w}};let Y=groupByFile(H),ee=new Map;await Promise.all(Y.map(async e=>{try{let t=await enrichPath(e.path,{projectDir:w,serverUrl:D});ee.set(e.path,t)}catch{}}));let te=[];te.push(`## Grep results for "${e.query}" (${H.length} match${H.length===1?``:`es`} in ${Y.length} file${Y.length===1?``:`s`})`,``);let ne=[];for(let e of Y){let t=ee.get(e.path),S=t?.title??e.path;te.push(`### ${S} (${e.path})`),t?.tags?.length&&te.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&te.push(`${t.description}`);for(let t of e.matches)te.push(`- Line ${t.line}: ${t.text}`);te.push(``);let w=docNameFromPath(e.path),E=q(w);ne.push({path:e.path,docName:w,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:E?.url??null,...E?{previewUrlSource:E.source}:{}})}return B&&te.push(`_${H.length} of ${k.length}+ matches shown (max 50). Refine your query to narrow results._`),{text:te.join(`
|
|
2797
|
-
`),structured:{query:e.query,matchCount:H.length,fileCount:Y.length,truncated:B,results:ne,ui:J,cwd:w}}}const InputSchema$3={query:string$2().describe(`Literal text to search for`),case_sensitive:boolean$1().optional().describe(`Case-sensitive search (default false)`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},GrepResultRowSchema=object$1({path:string$2(),docName:string$2(),title:string$2().nullable(),description:string$2().nullable(),tags:array(string$2()),matches:array(object$1({line:number$1().int(),text:string$2()})),previewUrl:string$2().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$3={cwd:string$2(),query:string$2(),matchCount:number$1().int(),fileCount:number$1().int(),truncated:boolean$1(),results:array(GrepResultRowSchema),ui:object$1({baseUrl:string$2().nullable(),port:number$1().nullable()})};function register$13(e,t){e.registerTool(`grep`,{description:DESCRIPTION$13,inputSchema:InputSchema$3,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let{text:S,structured:w}=await buildGrepResult(e,t);return w?textPlusStructured(S,w):textResult(S)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}function buildBody$1(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
|
|
2797
|
+
`),structured:{query:e.query,matchCount:H.length,fileCount:Y.length,truncated:B,results:ne,ui:J,cwd:w}}}const InputSchema$3={query:string$2().describe(`Literal text to search for`),case_sensitive:boolean$1().optional().describe(`Case-sensitive search (default false)`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},GrepResultRowSchema=object$1({path:string$2(),docName:string$2(),title:string$2().nullable(),description:string$2().nullable(),tags:array(string$2()),matches:array(object$1({line:number$1().int(),text:string$2()})),previewUrl:string$2().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$3=outputSchemaWithText({cwd:string$2(),query:string$2(),matchCount:number$1().int(),fileCount:number$1().int(),truncated:boolean$1(),results:array(GrepResultRowSchema),ui:object$1({baseUrl:string$2().nullable(),port:number$1().nullable()})});function register$13(e,t){e.registerTool(`grep`,{description:DESCRIPTION$13,inputSchema:InputSchema$3,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let{text:S,structured:w}=await buildGrepResult(e,t);return w?textPlusStructured(S,w):textResult(S)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}function buildBody$1(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
|
|
2798
2798
|
|
|
2799
2799
|
Source: ${e}
|
|
2800
2800
|
|
|
@@ -3242,13 +3242,13 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3242
3242
|
`);function register$6(e,t){e.tool(`rollback_to_version`,DESCRIPTION$6,{docName:string$2().describe(`Document name to restore`),commitSha:string$2().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=D.docName,k=await httpGet(E,`/api/history/${e.commitSha}?docName=${encodeURIComponent(O)}`);if(!k.ok)return textResult(`Error: ${k.error??`Version not found`}`,!0);let j=t.identityRef?.current,F=await httpPost(E,`/api/rollback`,{docName:O,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...j?{agentId:j.connectionId,agentName:j.displayName,clientName:j.clientInfo?.name,colorSeed:j.colorSeed}:{}});if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=F.summary&&typeof F.summary==`object`?F.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H=[`Restored "${O}" to version ${e.commitSha.slice(0,8)} (${k.author}, ${k.timestamp}). The change has been applied to all connected editors.`];B&&H.push(B);let q=await resolvePreviewUrlForTool(O,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(H.join(`
|
|
3243
3243
|
`),{previewUrl:q?.url??null,...q?{previewUrlSource:q.source}:{},...L?{summary:L}:{}})})}const DESCRIPTION$5=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
|
|
3244
3244
|
`);function register$5(e,t,S,w,E){e.tool(`save_version`,DESCRIPTION$5,{cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async(e={})=>{let D=await resolveProjectServerContext(w,t,S,e.cwd);if(!D.ok)return textResult(`Error: ${D.error}`,!0);if(!D.url)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let{url:O}=D,k=E?.current,j=await httpPost(O,`/api/save-version`,{...k?{writers:[{id:`agent-${k.connectionId}`,name:k.displayName,email:`agent-${k.connectionId}@openknowledge.local`}]}:{}});return j.ok?textPlusStructured(`Checkpoint saved. Checkpoint ref: ${j.checkpointRef}`,{checkpointRef:j.checkpointRef,previewUrl:null}):textResult(`Error: ${j.error}`,!0)})}const DESCRIPTION$4=["Find the most relevant pages for a query (ranked: title boost + body BM25 + recency). For literal-string matching across every line, use `grep`.",``,"Same engine and ranking the cmd-K palette uses. Returns a sorted list of page (and folder, with `omnibar` intent) hits with score signals plus a body snippet per page.",``,`**Use when:**`,`- Hunting for the canonical page on a topic`,`- Locating a doc by partial title or path segments`,`- Picking the best entry point before reading`,``,`**Parameters:**`,"- `query` — Search query (free-form; tokenized across title, name, path segments, and optionally body content).","- `intent` (optional) — `'omnibar'` searches title/path/folders only (fast); `'full_text'` includes body content. Default `'full_text'`.","- `scopes` (optional) — Override the result scope. Members: `'page'`, `'folder'`, `'content'`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `cwd` (optional) — Project root the query runs against.",``,"**Server requirement:** the Hocuspocus server must be running (`open-knowledge start`). If not, this tool returns a recovery hint; use `grep` as a server-free fallback."].join(`
|
|
3245
|
-
`),InputSchema$2={query:string$2().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number$1().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string$2(),docName:string$2(),title:string$2().nullable(),score:number$1(),signals:object$1({lexical:number$1(),fullText:number$1(),recency:number$1()}),snippet:string$2().optional(),previewUrl:string$2().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$2={cwd:string$2(),query:string$2(),intent:string$2(),resultCount:number$1().int(),results:array(SearchResultRowSchema),elapsedMs:number$1().nullable(),ui:object$1({baseUrl:string$2().nullable(),port:number$1().nullable()})};function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0}}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let S of e){let e=S.title?.trim()||S.path;t.push(`### ${e} (${S.path})`),t.push(`Score ${S.score.toFixed(2)} — kind: ${S.kind}`),S.snippet&&t.push(S.snippet),t.push(``)}return t.join(`
|
|
3245
|
+
`),InputSchema$2={query:string$2().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number$1().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string$2(),docName:string$2(),title:string$2().nullable(),score:number$1(),signals:object$1({lexical:number$1(),fullText:number$1(),recency:number$1()}),snippet:string$2().optional(),previewUrl:string$2().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$2=outputSchemaWithText({cwd:string$2(),query:string$2(),intent:string$2(),resultCount:number$1().int(),results:array(SearchResultRowSchema),elapsedMs:number$1().nullable(),ui:object$1({baseUrl:string$2().nullable(),port:number$1().nullable()})});function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0}}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let S of e){let e=S.title?.trim()||S.path;t.push(`### ${e} (${S.path})`),t.push(`Score ${S.score.toFixed(2)} — kind: ${S.kind}`),S.snippet&&t.push(S.snippet),t.push(``)}return t.join(`
|
|
3246
3246
|
`)}function register$4(e,t){e.registerTool(`search`,{description:DESCRIPTION$4,inputSchema:InputSchema$2,outputSchema:OutputSchema$2,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`grep\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let O=e.intent??`full_text`,k=e.limit??20,j={query:e.query,intent:O,limit:k};e.scopes&&(j.scopes=e.scopes);let F=await httpPost(D,`/api/search`,j);if(!F.ok)return textResult(`Error: ${F.error}`,!0);let{resolve:L,ui:B}=await buildListResolver({config:E,resolveCwd:async()=>w},w),H=(F.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),S=L(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}}]}),q={cwd:w,query:e.query,intent:O,resultCount:H.length,results:H,elapsedMs:typeof F.elapsedMs==`number`?F.elapsedMs:null,ui:B},J=`## Search results for "${e.query}" (${H.length} hit${H.length===1?``:`s`}, intent: ${O})`;return textPlusStructured(H.length===0?`No matches for "${e.query}".`:`${J}\n\n${formatResultsBlock(H)}`,q)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$3=["[Operates on disk; no running OK server required] Upsert one or more folder rules — writes nested `<folder>/.ok/frontmatter.yml` files.",``,"Folder rules apply default frontmatter to every doc inside `<folder>/` (and its descendants via cascade). Open shape — any YAML-representable key is accepted. Common keys: `title`, `description`, `tags` (the well-known three) plus arbitrary additions like `status`, `team`, `owners`, `review_cycle`. Use this tool to add a new rule, replace an existing one keyed by `match`, or rename via `new_match`.",``,`**Cascade merge semantics (D6 generalized):** scalars (string / number / boolean / null) replace last-wins along the leaf → root walk; arrays union-and-dedup with first-occurrence preserved; objects replace last-wins.`,``,'Each `match` glob must resolve to a SINGLE target folder by walking leading literal segments — `"specs/**"` writes `specs/.ok/frontmatter.yml`. Multi-folder globs (e.g. `"specs/*/evidence/**"`, where the literal `evidence` follows `*`) are rejected with `MULTI_FOLDER_GLOB`; split into per-folder rules instead.',``,"Always pass an array — even for a single rule. Validation runs against every rule first; if any fails (e.g. `MULTI_FOLDER_GLOB`, `PATH_ESCAPE`), NO rules are applied to disk. Filesystem-level errors during the write phase (disk full, permissions) may leave a partial result — the error response includes `partiallyApplied` listing which rules already landed.",``,'**To remove a rule**, pass an empty `frontmatter: {}` — the merge collapses, the file is deleted, and `<folder>/.ok/` is auto-cleaned if no other tenant remains. To clear a SPECIFIC key while keeping others, set that key to `null` / `""` / `[]` in the patch.',``,`**Parameters:**`,"- `rules` — Array of `{match, frontmatter, new_match?}`.",' - `match` — Glob pattern that identifies the target folder (e.g. `"specs/**"`, `"meetings/prep-notes/**"`). Required.'," - `frontmatter` — Open `Record<string, unknown>` of key/value defaults. Common: `{title?, description?, tags?: string[]}`. Any other key persists too (`status`, `team`, etc.)."," - `new_match` — If set, move the rule from `match` to this new glob (deletes the old folder's frontmatter.yml + auto-cleans).","- `cwd` (optional) — Project root."].join(`
|
|
3247
|
-
`),FolderRuleUpsertInputSchema=object$1({match:string$2().min(1).describe(`Glob pattern (e.g. "specs/**", "meetings/prep-notes/**") that identifies the target folder.`),frontmatter:record(string$2(),unknown$2()).refine(e=>!(`title`in e&&e.title!==null&&typeof e.title!=`string`||`description`in e&&e.description!==null&&typeof e.description!=`string`||`tags`in e&&e.tags!==null&&!Array.isArray(e.tags)),{message:"Well-known keys must match expected types when present: `title` (string|null), `description` (string|null), `tags` (string[]|null)."}).describe('Default frontmatter to apply to matched docs. Open shape — any YAML-representable key. Common: `{title?, description?, tags?: string[]}`; arbitrary keys (`status`, `team`, `owners`, `review_cycle`, …) also persist. Pass `{}` to remove the rule (auto-cleans `.ok/` if empty). Pass `key: null | "" | []` to clear that specific key while keeping others.'),new_match:string$2().min(1).optional().describe("If set, move the rule from `match` to this new folder (deletes the old folder's frontmatter.yml + auto-cleans).")}),InputSchema$1={rules:array(FolderRuleUpsertInputSchema).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},AppliedEntrySchema=object$1({match:string$2(),path:string$2(),action:_enum([`written`,`deleted`])}),SuccessOutputSchema=object$1({ok:literal(!0),applied:array(AppliedEntrySchema)}),ErrorOutputSchema=object$1({ok:literal(!1),error:object$1({code:_enum([`MULTI_FOLDER_GLOB`,`PATH_ESCAPE`,`BAD_PROJECT_DIR`,`WRITE_ERROR`]),message:string$2(),rule:string$2().optional()}),partiallyApplied:array(AppliedEntrySchema).optional()}),OutputSchema$1={result:union([SuccessOutputSchema,ErrorOutputSchema])};function register$3(e,t){e.registerTool(`set_folder_rule`,{description:DESCRIPTION$3,inputSchema:InputSchema$1,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E=applyNestedFolderRulesUpsert({projectDir:w,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter??{},...e.new_match===void 0?{}:{new_match:e.new_match}}))});return E.ok?textPlusStructured(JSON.stringify(E,null,2),{result:E}):{isError:!0,structuredContent:{result:E},content:[{type:`text`,text:`${E.error.code}: ${E.error.message}`}]}})}const DESCRIPTION$2=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
3247
|
+
`),FolderRuleUpsertInputSchema=object$1({match:string$2().min(1).describe(`Glob pattern (e.g. "specs/**", "meetings/prep-notes/**") that identifies the target folder.`),frontmatter:record(string$2(),unknown$2()).refine(e=>!(`title`in e&&e.title!==null&&typeof e.title!=`string`||`description`in e&&e.description!==null&&typeof e.description!=`string`||`tags`in e&&e.tags!==null&&!Array.isArray(e.tags)),{message:"Well-known keys must match expected types when present: `title` (string|null), `description` (string|null), `tags` (string[]|null)."}).describe('Default frontmatter to apply to matched docs. Open shape — any YAML-representable key. Common: `{title?, description?, tags?: string[]}`; arbitrary keys (`status`, `team`, `owners`, `review_cycle`, …) also persist. Pass `{}` to remove the rule (auto-cleans `.ok/` if empty). Pass `key: null | "" | []` to clear that specific key while keeping others.'),new_match:string$2().min(1).optional().describe("If set, move the rule from `match` to this new folder (deletes the old folder's frontmatter.yml + auto-cleans).")}),InputSchema$1={rules:array(FolderRuleUpsertInputSchema).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},AppliedEntrySchema=object$1({match:string$2(),path:string$2(),action:_enum([`written`,`deleted`])}),SuccessOutputSchema=object$1({ok:literal(!0),applied:array(AppliedEntrySchema)}),ErrorOutputSchema=object$1({ok:literal(!1),error:object$1({code:_enum([`MULTI_FOLDER_GLOB`,`PATH_ESCAPE`,`BAD_PROJECT_DIR`,`WRITE_ERROR`]),message:string$2(),rule:string$2().optional()}),partiallyApplied:array(AppliedEntrySchema).optional()}),OutputSchema$1=outputSchemaWithText({result:union([SuccessOutputSchema,ErrorOutputSchema])});function register$3(e,t){e.registerTool(`set_folder_rule`,{description:DESCRIPTION$3,inputSchema:InputSchema$1,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E=applyNestedFolderRulesUpsert({projectDir:w,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter??{},...e.new_match===void 0?{}:{new_match:e.new_match}}))});return E.ok?textPlusStructured(JSON.stringify(E,null,2),{result:E}):{isError:!0,structuredContent:{result:E},content:[{type:`text`,text:`${E.error.code}: ${E.error.message}`}]}})}const DESCRIPTION$2=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
|
|
3248
3248
|
`);function register$2(e,t){e.tool(`suggest_links`,DESCRIPTION$2,{docName:string$2().describe(`Target page docName`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=await httpGet(E,`/api/suggest-links?docName=${encodeURIComponent(D.docName)}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=await resolvePreviewUrlForTool(D.docName,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(JSON.stringify(j,null,2),{...j,previewUrl:F?.url??null,...F?{previewUrlSource:F.source}:{}})})}const DESCRIPTION$1=`${[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Frontmatter.** The markdown payload may include a YAML frontmatter block (`---`-fenced). To change frontmatter, call this tool with `position: "replace"` and a payload that includes the new YAML block — per-property MCP editing is currently unavailable. `edit_document` rejects frontmatter-intersecting find/replace calls.',``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,"**Templates.** When creating a new doc, pass `template: \"<name>\"` to instantiate from a folder-scoped template. The name resolves against `templates_available` for the doc's parent folder (leaf → root walk-up; check `list_documents({ dir, depth: 1 })` to see the menu). The template's body + frontmatter become the doc's starting content; folder cascade merges naturally at read time. Templates scoped to a descendant subfolder are rejected for parent-folder targets. **`template` and `markdown` are mutually exclusive** — pass exactly one. To start from the template body and then customize, instantiate via `template` first, then call `edit_document` to fill placeholders.",``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write. Required unless `template` is set (mutually exclusive — pass exactly one).","- `template` (optional) — Template name resolved against the parent folder's `templates_available`. The template body becomes the new doc verbatim. Cannot be combined with `markdown`.",'- `position` — Where to insert: "append", "prepend", or "replace". When `template` is set, `position` is forced to "replace".','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
|
|
3249
3249
|
`)}\n${renderInventoryFooter()}`;function register$1(e,t){e.tool(`write_document`,DESCRIPTION$1,{docName:string$2().describe(`Document name to write to`),markdown:string$2().optional().describe("Markdown content to write. Optional when `template` is set — the template body is used."),template:string$2().min(1).optional().describe(`Template name resolved against parent folder's templates_available (leaf → root walk-up; closest-wins on collision). See list_documents({ dir, depth: 1 }) to inspect the menu.`),position:_enum([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current;if(e.template===void 0&&e.markdown===void 0)return textResult("Error: either `markdown` or `template` must be provided. Omitting both would write empty content.",!0);if(e.template!==void 0&&e.markdown!==void 0)return textResult("Error: TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one. The template body becomes the new doc verbatim; fill placeholders via subsequent `edit_document` calls.",!0);let k=e.markdown??``,j=e.position;if(e.template!==void 0){let t=parentFolderOf(D.docName),S=resolveTemplatesAvailable(w,t,{depth:1}),E=S.find(t=>t.name===e.template);if(!E)return textResult(`Error: template "${e.template}" not found for folder "${t||`.`}". Available: ${S.length===0?`(none)`:S.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check list_documents({ dir, depth: 1 }) at the parent folder to see the menu.`,!0);let F;try{F=readFileSync(resolve(w,E.path),`utf-8`)}catch(e){return textResult(`Error: failed to read template at ${E.path}: ${e.message}`,!0)}k=applySubstitution(F,{date:todayIsoUtc(),user:O?.displayName??``}),j=`replace`}let F=await httpPost(E,`/api/agent-write-md`,{docName:D.docName,markdown:k,position:j,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=resolveLockDir(w),B=resolvePreviewUrl(D.docName,{lockDir:L}),H=typeof F.subscriberCount==`number`?F.subscriberCount:void 0,q=(typeof F.systemSubscriberCount==`number`?F.systemSubscriberCount:void 0)===0,J=H===0,Y=Array.isArray(F.hints)?F.hints:void 0,ee=F.summary&&typeof F.summary==`object`?F.summary:void 0,te=typeof ee?.hint==`string`?ee.hint:void 0,ne=[e.template===void 0?`Written successfully (${j}).`:`Written successfully (instantiated from template "${e.template}").`];if(B&&ne.push(`Preview: ${B.url}`),q&&ne.push(B?`Open ${B.url} in your preview browser.`:`No preview attached. Start the UI.`),te&&ne.push(te),Y)for(let e of Y)e.message&&ne.push(e.message);let ae=ne.join(`
|
|
3250
3250
|
`);if(!B&&!q&&!J&&!Y&&!ee)return textResult(ae);let oe={};return B&&(oe.previewUrl=B.url,oe.previewUrlSource=B.source),q&&(oe.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:B?.url??null}),Y&&(oe.hints=Y),ee&&(oe.summary=ee),textPlusStructured(ae,oe)})}const DESCRIPTION=[`[Operates on disk; no running OK server required] Create or update a template.`,``,"Templates are markdown starter shapes that agents pick from when creating a new doc — `write_document({ template: <name> })` resolves the name against the folder cascade and instantiates the body + frontmatter.",``,`**Targets.** A template can live in one of two locations:`,'- `target: "project"` (default) — folder-scoped within the current project at `<folder>/.ok/templates/<name>.md`. The `folder` argument selects which project folder owns it (project-wide via `folder: ""`, or scoped to a subfolder).','- `target: "user"` — user-global at `~/.ok/templates/<name>.md`, available across every OK project the same user opens. The `folder` argument is ignored when `target` is `"user"` — user templates live in a single flat location.',``,"**`title` is required** in the frontmatter — it is the menu surface agents pick from. Missing or empty title returns `TEMPLATE_TITLE_REQUIRED`. `description` is recommended (soft warning when absent) — it disambiguates similarly-named templates.",``,"**Substitution allowlist.** The body MAY contain `{{date}}` (today, ISO-8601) and `{{user}}` (calling principal display name). Any other `{{...}}` token is rejected at write time with `TEMPLATE_UNKNOWN_VARIABLE`. Substitution happens at instantiation time (when `write_document({ template })` materializes the doc), not at template-write time — templates on disk show the raw `{{date}}` token.",``,`**Parameters:**`,'- `folder` — Project-root-relative folder (e.g. `"meetings"`, `"meetings/prep-notes"`). Empty / `.` means project root. Ignored when `target` is `"user"`.',"- `name` — Template filename without `.md`. Letters, digits, `_`, `-` only.","- `body` — Markdown body. May use `{{date}}` / `{{user}}` substitution tokens. Other placeholder text in `{shape}` form (e.g. `{Meeting Title}`) is LITERAL — agents fill it in via subsequent `edit_document` calls.","- `frontmatter` — `{title (required), description?, tags?: string[]}` for the template menu.",'- `target` (optional) — `"project"` (default) or `"user"`. Selects where the template lives.'].join(`
|
|
3251
|
-
`),InputSchema={folder:string$2().describe('Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.'),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).").describe("Template filename without `.md` extension."),body:string$2().describe(`Markdown body for the template.`),frontmatter:object$1({title:string$2().min(1,"Template `title` is required — it is the menu surface agents pick from.").describe(`Required. The menu surface agents pick from. Empty / missing returns TEMPLATE_TITLE_REQUIRED.`),description:string$2().optional().describe(`Recommended. Disambiguates similarly-named templates. Soft warning when absent.`),tags:array(string$2()).optional().describe(`Optional. Concatenated with cascade tags at instantiation time.`)}).describe("Template menu metadata. `title` MUST be present (hard error if missing). `description` SHOULD be present (warning)."),target:_enum([`project`,`user`]).optional().describe('Where the template lives. `"project"` (default) writes to `<folder>/.ok/templates/`; `"user"` writes to `~/.ok/templates/` (folder ignored).'),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema={result:union([object$1({ok:literal(!0),path:string$2(),created:boolean$1(),warnings:array(string$2())}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])};function register(e,t){e.registerTool(`write_template`,{description:DESCRIPTION,inputSchema:InputSchema,outputSchema:OutputSchema,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E={projectDir:w,folder:e.folder,name:e.name,body:e.body,frontmatter:e.frontmatter};e.target!==void 0&&(E.target=e.target);let D=applyTemplateWrite(E);if(!D.ok)return{isError:!0,structuredContent:{result:D},content:[{type:`text`,text:`${D.error.code}: ${D.error.message}`}]};let O=[`${D.created?`Created`:`Updated`} template at ${D.path}`];if(D.warnings.length>0){O.push(``,`Warnings:`);for(let e of D.warnings)O.push(` - ${e}`)}return textPlusStructured(O.join(`
|
|
3251
|
+
`),InputSchema={folder:string$2().describe('Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.'),name:string$2().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).").describe("Template filename without `.md` extension."),body:string$2().describe(`Markdown body for the template.`),frontmatter:object$1({title:string$2().min(1,"Template `title` is required — it is the menu surface agents pick from.").describe(`Required. The menu surface agents pick from. Empty / missing returns TEMPLATE_TITLE_REQUIRED.`),description:string$2().optional().describe(`Recommended. Disambiguates similarly-named templates. Soft warning when absent.`),tags:array(string$2()).optional().describe(`Optional. Concatenated with cascade tags at instantiation time.`)}).describe("Template menu metadata. `title` MUST be present (hard error if missing). `description` SHOULD be present (warning)."),target:_enum([`project`,`user`]).optional().describe('Where the template lives. `"project"` (default) writes to `<folder>/.ok/templates/`; `"user"` writes to `~/.ok/templates/` (folder ignored).'),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema=outputSchemaWithText({result:union([object$1({ok:literal(!0),path:string$2(),created:boolean$1(),warnings:array(string$2())}),object$1({ok:literal(!1),error:object$1({code:string$2(),message:string$2()})})])});function register(e,t){e.registerTool(`write_template`,{description:DESCRIPTION,inputSchema:InputSchema,outputSchema:OutputSchema,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{cwd:w}=S,E={projectDir:w,folder:e.folder,name:e.name,body:e.body,frontmatter:e.frontmatter};e.target!==void 0&&(E.target=e.target);let D=applyTemplateWrite(E);if(!D.ok)return{isError:!0,structuredContent:{result:D},content:[{type:`text`,text:`${D.error.code}: ${D.error.message}`}]};let O=[`${D.created?`Created`:`Updated`} template at ${D.path}`];if(D.warnings.length>0){O.push(``,`Warnings:`);for(let e of D.warnings)O.push(` - ${e}`)}return textPlusStructured(O.join(`
|
|
3252
3252
|
`),{result:D})})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$22(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$12(w,{config:t.config,resolveCwd:E(`ingest`)}),register$7(w,{config:t.config,resolveCwd:E(`research`)}),register$27(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$24(w,{config:t.config,resolveCwd:E(`discover`)}),register$10(w,{resolveCwd:E(`read_document`),config:t.config,serverUrl:t.serverUrl}),register$4(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$13(w,{resolveCwd:E(`grep`),config:t.config,serverUrl:t.serverUrl}),register$2(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`suggest_links`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$23(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$26(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$9(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_document`),identityRef:t.identityRef}),register$8(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename_folder`),identityRef:t.identityRef}),register$16(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$5(w,t.config,t.serverUrl,E(`save_version`),t.identityRef),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rollback_to_version`),identityRef:t.identityRef}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_documents`)}),register$21(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_backlinks`)}),register$20(w,{resolveCwd:E(`get_components`),config:t.config}),register$17(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_forward_links`)}),register$14(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_orphans`)}),register$15(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_hubs`)}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_dead_links`)}),register$19(w,{config:t.config,resolveCwd:E(`get_config`)}),register$3(w,{config:t.config,resolveCwd:E(`set_folder_rule`)}),register(w,{config:t.config,resolveCwd:E(`write_template`)}),register$25(w,{config:t.config,resolveCwd:E(`delete_template`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)}),D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}if(j!==void 0){try{j(e,t,()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})})}catch(e){E.error({err:e},`Unhandled content-asset middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=B.get(S);e!==void 0&&(clearTimeout(e),B.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(B.delete(S),q)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(S,e),E.info({connectionId:S,graceMs:F},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),L.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled([...H])}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let S=resolve(e,t.slice(5));try{return readFileSync(S,`utf-8`).trim()}catch{try{let S=readFileSync(resolve(e,`packed-refs`),`utf-8`),w=t.slice(5),E=S.split(`
|
|
3253
3253
|
`).find(e=>e.endsWith(` ${w}`));if(E)return E.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,S){let w=resolveGitDir(e);if(!w)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let E=w,D=!1,O=null,k=null,j=null,F=null;async function L(e){if(H&&await H,!D)return;O&&=(clearTimeout(O),null),k&&=(clearTimeout(k),null);let t=readHeadSha(E),w=j!==t,L=readBranchFromHead(E),B;B=L?.startsWith(`detached-`)?`detached-head`:F===L?`within-branch`:`cross-branch`;let q=F;try{await S({headMoved:w,oldHead:j,newHead:t,timeout:e,batchKind:B,oldBranch:q,newBranch:L})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{D=!1,j=t,F=L}}function B(){O&&clearTimeout(O),O=setTimeout(()=>{O=null,L(!1)},QUIET_WINDOW_MS)}let H=null;async function q(e){if(!D){D=!0,j=readHeadSha(E);let S=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();H=S,await S,H=null,k=setTimeout(()=>{k=null,L(!0)},BATCH_TIMEOUT_MS)}B()}let J,Y;try{Y=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await Y.subscribe(E,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){q(t);break}}});J=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return j=readHeadSha(E),F=readBranchFromHead(E),console.log(`[head-watcher] Watching ${E} for HEAD changes`),{unsubscribe:async()=>{D&&await L(!1),O&&clearTimeout(O),k&&clearTimeout(k),await J()},getLastKnownBranch:()=>F}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:S,signalChannel:w,debounceMs:E=100}=e,D=new Map;function O(e){let t=D.get(e);t&&(clearTimeout(t),D.delete(e))}function k(e,k){O(e),D.set(e,setTimeout(()=>{D.delete(e);try{let E=serializeLiveDocument(k);t.updateDocumentFromMarkdown(e,E),w?.(`backlinks`),w?.(`graph`),S&&(S.updateDocumentFromMarkdown(e,E),w?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},E))}return{async onChange({documentName:e,document:t,transactionOrigin:S}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(S)&&S.context?.origin===`file-watcher`||k(e,t)},async beforeUnloadDocument({documentName:e}){O(e)},async onDestroy(){for(let e of D.values())clearTimeout(e);D.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),S=resolve(t,PRINCIPAL_FILE),{name:w,email:E}=await readGitConfig(e);if(existsSync(S)){let e;try{e=JSON.parse(readFileSync(S,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,D=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),O=t.slice(10,18),k={id:t,display_name:w?sanitizeGitIdentity(w):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:E?sanitizeGitIdentity(E):typeof e.display_email==`string`?e.display_email:`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:D};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}mkdirSync(t,{recursive:!0});let D=`principal-${randomUUID()}`,O=D.slice(10,18),k={id:D,display_name:w?sanitizeGitIdentity(w):`Local User`,display_email:E?sanitizeGitIdentity(E):`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let S=e.resolveFilePath(t);return S!==null&&e.fileExists(S)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let S=t.recentlyRemovedDocs.get(e);if(S===void 0)return;if(S.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let w=new Set([e]),E=S.newDocName;for(;;){if(w.has(E)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:E}));return}w.add(E);let S=t.recentlyRemovedDocs.get(E);if(S===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E);if(S.kind===`deleted`)throw fileExistsForDocName(t,E)?(t.recentlyRemovedDocs.delete(E),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));E=S.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,S=new Map;return{async afterLoadDocument({documentName:w,document:E}){if(isSystemDoc(w)||isConfigDoc(w)||t.has(w))return;let D=E,O=D.getXmlFragment(`default`),k=D.getText(`source`),j=()=>{try{let S=setupServerObservers({doc:D,xmlFragment:O,ytext:k,mdManager:e.mdManager,schema:e.schema,docName:w,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(w,S),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${w}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!j()){let e=setTimeout(()=>{S.delete(w),!t.has(w)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${w}'`),j())},5e3);S.set(w,e)}},async afterUnloadDocument({documentName:e}){let w=S.get(e);w&&(clearTimeout(w),S.delete(e));let E=t.get(e);E&&(E(),t.delete(e))},async onDestroy(){for(let e of S.values())clearTimeout(e);S.clear();for(let[e,S]of t.entries())try{S()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let S=t.createdBy;return!(typeof S.runtimeVersion!=`string`||S.protocolVersion!==void 0&&typeof S.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let S;try{S=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let w;try{w=JSON.parse(S)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(w))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:w}}function writeStateManifest(e,t){let S=manifestPath(e);mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),S=e.currentStateSchemaVersion??1,w=e.currentRuntimeVersion??RUNTIME_VERSION,E=e.currentProtocolVersion??1,D=(e.now??(()=>new Date))().toISOString(),O=manifestPath(e.lockDir),k=readStateManifest(e.lockDir);if(k.status===`present`){let j=k.manifest;if(!isCompatibleSchema(j.stateSchemaVersion,S))throw new StateManifestError({kind:`incompatible`,path:O,message:`State manifest at ${O} declares stateSchemaVersion=${j.stateSchemaVersion} but this binary supports ${S}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${j.createdBy.runtimeVersion}, protocol ${j.createdBy.protocolVersion}.)`});try{let t={...j,lastWriteBy:{runtimeVersion:w,protocolVersion:E,at:D}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),j}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let k={stateSchemaVersion:S,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E}};return writeStateManifest(e.lockDir,k),t.info({path:O,stateSchemaVersion:S},`[state-manifest] fresh project — wrote manifest`),k}let j={stateSchemaVersion:0,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E,adoptedAt:D}};return writeStateManifest(e.lockDir,j),t.warn({path:O,runtimeVersion:w},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),j}const log$1=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$1.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$1.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-DwfYp_z--DreW3fNC.mjs`).then(e=>e.n),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(!S)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$1.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
3254
3254
|
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=e instanceof Error?e:Error(String(e)),S=extractStderr(t),w=`${t.message}\n${S}`.toLowerCase();return matchesAny(w,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:S}:matchesAny(w,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:S}:matchesAny(w,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:S}:matchesAny(w,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:S}:matchesAny(w,AUTH_PATTERNS)?/\b401\b/.test(w)||/token.*expired/i.test(w)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:S}:/\b403\b/.test(w)?matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:S}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:S}:matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:matchesAny(w,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:S}:matchesAny(w,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:S}:matchesAny(w,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:S}:matchesAny(w,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:S}:matchesAny(w,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:S}:matchesAny(w,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:S}:matchesAny(w,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:S}:matchesAny(w,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:S}:matchesAny(w,NETWORK_PATTERNS)?/timed? out/i.test(w)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:S}:/refused/i.test(w)||/econnrefused/i.test(w)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:S}:/resolve.*host/i.test(w)||/enotfound/i.test(w)||/getaddrinfo/i.test(w)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:S}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:S}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:S}}function computeRemainingMs(e,t,S=Date.now()){if(!e)return 0;let w=new Date(e).getTime();if(Number.isNaN(w))return 0;let E=w+t*1e3;return Math.max(0,E-S)}const log=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function jitteredMs(e){let t=e*1e3,S=t*.15*(2*Math.random()-1);return Math.round(t+S)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let S=readFileSync(t,`utf-8`).trim(),w=/^ref:\s+(refs\/.+)$/.exec(S);if(!w)return!1;let E=w[1];if(existsSync(join(e,`.git`,E)))return!1;let D=join(e,`.git`,`packed-refs`);if(existsSync(D)){let e=readFileSync(D,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${E}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=existsSync(join(this.projectDir,`.git`,`MERGE_HEAD`));if(this.conflictCount>0&&!t)log.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&t)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
@@ -3261,4 +3261,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3261
3261
|
`).split(`
|
|
3262
3262
|
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Lt?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Lt?Lt.getFileIndex():new Map,getFolderIndex:()=>Lt?Lt.getFolderIndex():new Map,getAliasMap:()=>Lt?Lt.getAliasMap():new Map,rescanFiles:()=>Lt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>zt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce),vt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Tt=null,Et=e=>{e&&(Tt===null&&(Tt=new Set,setImmediate(()=>{let e=Tt;if(Tt=null,e)try{for(let t of e)vt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Tt.add(e))};function Dt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function jt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=Rt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=S.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Et(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Et(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=Dt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Mt=[];async function Ft(e){if(isBatchInProgress()){Mt.push(e);return}await jt(e)}async function It(){let e=Mt.splice(0,Mt.length);for(let t of e)await jt(t)}let Lt=null,Rt=null,zt=null,Bt=null;async function Vt(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ht(){return Bt||(Bt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{Rt&&=(await Rt.unsubscribe(),null),Lt&&=(await Lt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Vt(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{zt&&=(await zt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Bt)}let Ut=[];async function Wt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Ut.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Ut.includes(`shadow-repo`)||Ut.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Ut.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Ut.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Ut.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Ut.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();zt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Ut.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Ut.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Lt=await startWatcher(t,Ft,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Ut.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Ut.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Ut.push(`file-watcher`)}try{Rt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Mt.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await It(),await ge.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Mt.splice(0,Mt.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Ut.includes(`basename-index-partial`)||Ut.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3263
3263
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Ut.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{zt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await zt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),zt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Wt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ht,ready:Re,degraded:Ut,lockDir:ae,get syncEngine(){return zt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me}),_e=null;w!==null&&(_e=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await Y()})})),await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})});let ve=fe.address(),ye=typeof ve==`object`&&ve?ve.port:e.port??0;if(ue=ye,j(ne,ye),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let Ce=!1,we=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return{httpServer:fe,destroy:async()=>{if(Ce)return;Ce=!0;let e=[],t=async(t,S)=>{try{await we(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{_e?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ge.shutdown()),await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ge.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>Y()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},lockDir:ne,contentDir:e.contentDir,port:ye,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{applySeed as $,rewriteWikiLinksForDocumentRename as $n,ASSET_EXTENSIONS as $r,incrementCollabSocketFilteredError as $t,MissingOkConfigError as A,NEVER as Ai,readBranchFromHead as An,updateLastKnownHash as Ar,createServer$1 as At,STARTER_FOLDER_FRONTMATTER_FILENAME as B,registerAllTools as Bn,writeTracker as Br,findEnclosingGitRoot as Bt,LOG_MD_TEMPLATE as C,literal as Ci,parseAuthRejectionWire as Cn,tracedRename as Cr,createContentFilter as Ct,MCP_SERVER_NAME as D,string$2 as Di,planPersonalTemplates as Dn,tracedUnlinkSync as Dr,createMcpHttpHandler as Dt,MCP_CONNECTION_ID_HEADER as E,object$1 as Ei,pathToDocName as En,tracedRmdirSync as Er,createLiveDerivedIndexExtension as Et,ProjectGitInitError as F,readTargetVersion as Fn,withSpan as Fr,detectProjectShape as Ft,SeedPrerequisiteError as G,resolveBundledSkillDir as Gn,isJSONRPCRequest as Gr,getCurrentMcpLogger as Gt,STARTER_PACK_IDS as H,releaseUiLock as Hn,JSONRPCMessageSchema as Hr,formatAuthRejectionWire as Ht,ROLLBACK_ORIGIN as I,readUiLock as In,withSpanSync as Ir,ensureProjectGit as It,TagIndex as J,resolveCursorSpawnInvocation as Jn,resolveConfigPath as Jr,getMeter as Jt,SeedRootDirError as K,resolveContentDir as Kn,isJSONRPCResultResponse as Kr,getLocalDir as Kt,SERVICE_WRITER as L,reconcile as Ln,writePersonalTemplates as Lr,errorResponse as Lt,PERSONAL_TEMPLATES as M,readSkillInstallStateSnapshot as Mn,validateAgentId as Mr,createStreamingErrorWriter as Mt,PERSONAL_TEMPLATE_NAMES as N,readStateManifest as Nn,validateCloneInputs as Nr,createTestLogger as Nt,MISSING_OK_CONFIG_MESSAGE as O,url as Oi,planSeed as On,tracedWriteFile as Or,createOsProbe as Ot,PinoLogger as P,readTargetRecordedAt as Pn,validateSkillZip as Pr,detectClaudeDesktopPresence as Pt,applyExternalChange as Q,rewriteMarkdownLinksForDocumentRename as Qn,ALL_EDITOR_IDS as Qr,handleSpawnCursor as Qt,SKILL_INSTALL_EVENTS_FILE_REL as R,recordContributor as Rn,writeStateManifest as Rr,evictStaleTrackerEntries as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,boolean$1 as Si,normalizeFsPath as Sn,tracedMkdirSync as Sr,createAssetServeMiddleware as St,MAX_AGENT_SESSIONS as T,number$1 as Ti,parseKeepaliveConnectionId as Tn,tracedRmSync as Tr,createExternalChangeHandler as Tt,STARTER_TEMPLATES as U,removeLastKnownHash as Un,LATEST_PROTOCOL_VERSION as Ur,formatContributors as Ut,STARTER_PACKS as V,registerWrite as Vn,McpServer as Vr,findEnclosingProjectRoot as Vt,STATE_MANIFEST_FILENAME as W,resetMetrics as Wn,isInitializedNotification as Wr,gcCheckpointRefs as Wt,acquireUiLock as X,resolvePack as Xn,GitDirAccessError as Xr,getTracer as Xt,UiLockCollisionError as Y,resolveLockDir as Yn,writeConfigPatch as Yr,getMetrics as Yt,applyAgentMarkdownWrite as Z,resolvePackageVersion as Zn,MalformedGitPointerError as Zr,handleCollabSocketError as Zt,GIT_UPSTREAM_WRITER as _,OK_PROJECT_MARKER as _i,listRescueCheckpoints as _n,streamingProblemEvent as _r,commitWipFromTree as _t,AgentPresenceBroadcaster as a,INLINE_RENDERABLE_EXTENSIONS as ai,isAllowedApiOrigin as an,safeContentPath as ar,buildExecResult as at,HocuspocusAuthTokenSchema as b,any$1 as bi,loggerFactory as bn,tracedLinkSync as br,contributorCount as bt,BacklinkIndex as c,SKILL_STATE_TARGETS as ci,isHocuspocusAuthRejectionReason as cn,sanitizeClientName as cr,buildSkillZip as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,defaultScheduler as di,isPairedWriteOrigin as dn,seedBasenameIndex as dr,classifyEvents as dt,CC1_CONTRACT_VERSION as ei,incrementServerObserverFire as en,runAuthReposSubprocess as er,assertCompatibleStateManifest as et,ConfigSchema as f,humanFormat as fi,isPathWithinDir as fn,setActiveSpanAttributes as fr,classifyFsPath as ft,FILE_WATCHER_ORIGIN as g,LOCAL_DIR as gi,lastKnownHash as gn,startWatcher as gr,commitWip as gt,FILE_SYSTEM_WRITER as h,CONFIG_SCHEMA_MAJOR_PATH as hi,isSystemDoc as hn,splitMarkdownBlocks as hr,commitUpstreamImport as ht,AgentFocusBroadcaster as i,EXECUTABLE_BLOCKLIST_EXTENSIONS as ii,installUserSkill as in,runWithMcpLogger as ir,buildAndOpenSkill as it,OBSERVER_SYNC_ORIGIN as j,require_dist$2 as ji,readServerPackageVersion as jn,updateUiLockPort as jr,createServerObserverExtension as jt,McpLogger as k,_coercedNumber as ki,readAllTargets as kn,tracedWriteFileSync as kr,createPersistenceExtension as kt,CC1Broadcaster as l,SYSTEM_DOC_NAME as li,isKnownPackId as ln,saveInMemoryCheckpoint as lr,buildStarterFolderFrontmatterYaml as lt,DEFAULT_PACK_ID as m,isOrphanMode as mi,isSelfWrite as mn,shutdownTelemetry as mr,coercePackId as mt,AGENT_ID_RE as n,DEFAULT_SERVER_HOST as ni,initTelemetry as nn,runCloneSubprocess as nr,attachIdleShutdown as nt,AgentSessionCapacityError as o,ORPHAN_MODES as oi,isAllowedWorkspaceHostHeader as on,safeSubdir as or,buildInstructions as ot,DEFAULT_CHECKPOINT_RETENTION as p,iconFromClientName as pi,isProjectRoot as pn,shadowGit as pr,clearContributors as pt,StateManifestError as q,resolveCursorBinaryDefault as qn,readConfigSafely as qr,getLogger as qt,AGENT_WRITE_ORIGIN as r,EDITOR_LABELS as ri,installTestLoggers as rn,runDeviceFlowSubprocess as rr,bootServer as rt,AgentSessionManager as s,ProblemDetailsSchema as si,isConfigDoc as sn,safetyCheckpoint as sr,buildReadResult as st,AGENT_ID_MAX_LEN as t,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ti,initShadowRepo as tn,runAuthStatusSubprocess as tr,assertNeverDiskEvent as tt,CONFLICT_MARKER_RE as u,colorFromSeed as ui,isLoopbackAddress as un,saveVersion as ur,buildWipTree as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,locateIssue as vi,listStarterPacks as vn,toBroadcasterKey as vr,containsConflictMarkers as vt,MANAGED_RENAME_ORIGIN as w,looseObject as wi,parseHocuspocusAuthToken as wn,tracedRenameSync as wr,createContentFilterAsync as wt,INSTALLED_AGENTS_SCHEMES as x,array as xi,mountMcpAndApi as xn,tracedMkdir as xr,createApiExtension as xt,HocuspocusAuthRejection as y,ZodNumber$1 as yi,loadPrincipal as yn,tracedAppendFileSync as yr,contentHash as yt,STARTER_FOLDERS as z,recordSkillInstallEvent as zn,writeTargetVersion as zr,extractWikiLinksFromMarkdown as zt};
|
|
3264
|
-
//# sourceMappingURL=dist-
|
|
3264
|
+
//# sourceMappingURL=dist-C0nimAjR.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qt as de,R as fe,Rn as pe,Rr as me,Rt as he,S as ge,Sn as _e,Sr as ve,St as ye,T as be,Tn as xe,Tr as Se,Tt as Ce,U as we,Un as Te,Ut as Ee,V as De,Vn as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xn as Pe,Xr as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zr as He,Zt as Ue,_ as We,_n as Ge,_r as Ke,_t as qe,a as Je,an as Ye,ar as Xe,at as Ze,b as Qe,bn as $e,br as et,bt as tt,c as nt,ci as rt,cn as it,cr as at,ct as ot,d as st,dn as ct,dr as lt,dt as ut,ei as dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gn as bt,gr as xt,gt as St,h as Ct,hn as wt,hr as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jr as Nt,jt as Pt,k as Ft,kn as It,kr as Lt,kt as Rt,l as zt,li as Bt,ln as Vt,lr as Ht,lt as Ut,m as Wt,mi as Gt,mn as Kt,mr as qt,mt as Jt,n as Yt,nn as Xt,nr as Zt,nt as Qt,o as $t,oi as en,on as tn,or as nn,ot as rn,p as an,pi as on,pn as sn,pr as cn,pt as ln,q as un,qn as dn,qt as fn,r as pn,rn as mn,rr as hn,rt as gn,s as _n,sn as vn,sr as yn,st as bn,t as xn,tn as Sn,tr as Cn,tt as wn,u as Tn,ui as En,un as Dn,ur as On,ut as kn,v as An,vn as jn,vr as Mn,vt as Nn,w as Pn,wn as Fn,wr as In,wt as Ln,x as Rn,xn as zn,xr as Bn,xt as Vn,y as Hn,yn as Un,yr as Wn,yt as Gn,z as Kn,zn as qn,zr as Jn,zt as Yn}from"./dist-
|
|
1
|
+
import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qt as de,R as fe,Rn as pe,Rr as me,Rt as he,S as ge,Sn as _e,Sr as ve,St as ye,T as be,Tn as xe,Tr as Se,Tt as Ce,U as we,Un as Te,Ut as Ee,V as De,Vn as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xn as Pe,Xr as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zr as He,Zt as Ue,_ as We,_n as Ge,_r as Ke,_t as qe,a as Je,an as Ye,ar as Xe,at as Ze,b as Qe,bn as $e,br as et,bt as tt,c as nt,ci as rt,cn as it,cr as at,ct as ot,d as st,dn as ct,dr as lt,dt as ut,ei as dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gn as bt,gr as xt,gt as St,h as Ct,hn as wt,hr as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jr as Nt,jt as Pt,k as Ft,kn as It,kr as Lt,kt as Rt,l as zt,li as Bt,ln as Vt,lr as Ht,lt as Ut,m as Wt,mi as Gt,mn as Kt,mr as qt,mt as Jt,n as Yt,nn as Xt,nr as Zt,nt as Qt,o as $t,oi as en,on as tn,or as nn,ot as rn,p as an,pi as on,pn as sn,pr as cn,pt as ln,q as un,qn as dn,qt as fn,r as pn,rn as mn,rr as hn,rt as gn,s as _n,sn as vn,sr as yn,st as bn,t as xn,tn as Sn,tr as Cn,tt as wn,u as Tn,ui as En,un as Dn,ur as On,ut as kn,v as An,vn as jn,vr as Mn,vt as Nn,w as Pn,wn as Fn,wr as In,wt as Ln,x as Rn,xn as zn,xr as Bn,xt as Vn,y as Hn,yn as Un,yr as Wn,yt as Gn,z as Kn,zn as qn,zr as Jn,zt as Yn}from"./dist-C0nimAjR.mjs";import{_ as Xn,a as Zn,c as Qn,d as $n,f as er,g as tr,i as nr,l as rr,m as ir,n as ar,o as or,p as sr,r as cr,s as lr,t as ur,u as dr}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";export{xn as AGENT_ID_MAX_LEN,Yt as AGENT_ID_RE,pn as AGENT_WRITE_ORIGIN,Dt as AgentFocusBroadcaster,Je as AgentPresenceBroadcaster,$t as AgentSessionCapacityError,_n as AgentSessionManager,nt as BacklinkIndex,zt as CC1Broadcaster,dt as CC1_CONTRACT_VERSION,Tn as CONFLICT_MARKER_RE,st as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ht as ConfigSchema,an as DEFAULT_CHECKPOINT_RETENTION,Wt as DEFAULT_PACK_ID,Ct as FILE_SYSTEM_WRITER,yt as FILE_WATCHER_ORIGIN,We as GIT_UPSTREAM_WRITER,Fe as GitDirAccessError,An as HOCUSPOCUS_AUTH_REJECTION_REASONS,Hn as HocuspocusAuthRejection,Qe as HocuspocusAuthTokenSchema,Rn as INSTALLED_AGENTS_SCHEMES,ge as LIVE_DERIVED_INDEX_DEBOUNCE_MS,d as LOG_MD_TEMPLATE,Pn as MANAGED_RENAME_ORIGIN,be as MAX_AGENT_SESSIONS,y as MCP_CONNECTION_ID_HEADER,h as MCP_SERVER_NAME,te as MISSING_OK_CONFIG_MESSAGE,He as MalformedGitPointerError,Ft as McpLogger,r as MissingOkConfigError,jt as OBSERVER_SYNC_ORIGIN,en as ORPHAN_MODES,q as PERSONAL_TEMPLATES,Z as PERSONAL_TEMPLATE_NAMES,ae as PinoLogger,ur as ProcessLockCollisionError,C as ProjectGitInitError,N as ROLLBACK_ORIGIN,ar as RUNTIME_VERSION,U as SERVICE_WRITER,fe as SKILL_INSTALL_EVENTS_FILE_REL,rt as SKILL_STATE_TARGETS,Kn as STARTER_FOLDERS,s as STARTER_FOLDER_FRONTMATTER_FILENAME,De as STARTER_PACKS,A as STARTER_PACK_IDS,we as STARTER_TEMPLATES,Ae as STATE_MANIFEST_FILENAME,cr as STATE_SCHEMA_VERSION,Bt as SYSTEM_DOC_NAME,D as SeedPrerequisiteError,B as SeedRootDirError,nr as ServerLockCollisionError,un as StateManifestError,L as TagIndex,Le as UiLockCollisionError,Zn as acquireProcessLock,or as acquireServerLock,Ne as acquireUiLock,Be as applyAgentMarkdownWrite,le as applyExternalChange,e as applySeed,mt as assertCompatibleStateManifest,wn as assertNeverDiskEvent,Qt as attachIdleShutdown,gn as bootServer,At as buildAndOpenSkill,Ze as buildExecResult,rn as buildInstructions,bn as buildReadResult,ot as buildSkillZip,Ut as buildStarterFolderFrontmatterYaml,kn as buildWipTree,ut as classifyEvents,vt as classifyFsPath,ln as clearContributors,Jt as coercePackId,En as colorFromSeed,Et as commitUpstreamImport,St as commitWip,qe as commitWipFromTree,Nn as containsConflictMarkers,Gn as contentHash,tt as contributorCount,Vn as createApiExtension,ye as createAssetServeMiddleware,m as createContentFilter,Ln as createContentFilterAsync,Ce as createExternalChangeHandler,S as createLiveDerivedIndexExtension,v as createMcpHttpHandler,ie as createOsProbe,Rt as createPersistenceExtension,o as createServer,Pt as createServerObserverExtension,X as createStreamingErrorWriter,ee as createTestLogger,ce as detectClaudeDesktopPresence,E as detectProjectShape,I as ensureProjectGit,K as errorResponse,he as evictStaleTrackerEntries,Yn as extractWikiLinksFromMarkdown,u as findEnclosingGitRoot,ke as findEnclosingProjectRoot,M as formatAuthRejectionWire,Ee as formatContributors,Me as gcCheckpointRefs,k as getCurrentMcpLogger,H as getLocalDir,fn as getLogger,z as getMeter,ze as getMetrics,Ie as getTracer,Ue as handleCollabSocketError,de as handleSpawnCursor,on as iconFromClientName,n as incrementCollabSocketFilteredError,ft as incrementServerObserverFire,Sn as initShadowRepo,Xt as initTelemetry,mn as installTestLoggers,Ot as installUserSkill,Ye as isAllowedApiOrigin,tn as isAllowedWorkspaceHostHeader,vn as isConfigDoc,it as isHocuspocusAuthRejectionReason,Vt as isKnownPackId,Dn as isLoopbackAddress,Gt as isOrphanMode,ct as isPairedWriteOrigin,gt as isPathWithinDir,lr as isProcessAlive,sn as isProjectRoot,Kt as isSelfWrite,wt as isSystemDoc,Qn as isValidLockPid,bt as lastKnownHash,Ge as listRescueCheckpoints,jn as listStarterPacks,Un as loadPrincipal,rr as lockFilePath,$e as loggerFactory,zn as mountMcpAndApi,_e as normalizeFsPath,f as parseAuthRejectionWire,Fn as parseHocuspocusAuthToken,xe as parseKeepaliveConnectionId,b as pathToDocName,g as planPersonalTemplates,ne as planSeed,It as readAllTargets,i as readBranchFromHead,dr as readProcessLock,$n as readProcessLockDetailed,er as readServerLock,Mt as readServerPackageVersion,J as readSkillInstallStateSnapshot,Q as readStateManifest,oe as readTargetRecordedAt,w as readTargetVersion,P as readUiLock,W as reconcile,pe as recordContributor,qn as recordSkillInstallEvent,c as registerAllTools,Oe as registerWrite,sr as releaseProcessLock,ir as releaseServerLock,j as releaseUiLock,Te as removeLastKnownHash,je as resetMetrics,O as resolveBundledSkillDir,V as resolveContentDir,dn as resolveCursorBinaryDefault,R as resolveCursorSpawnInvocation,Re as resolveLockDir,Pe as resolvePack,Ve as resolvePackageVersion,ue as rewriteMarkdownLinksForDocumentRename,t as rewriteWikiLinksForDocumentRename,pt as runAuthReposSubprocess,Cn as runAuthStatusSubprocess,Zt as runCloneSubprocess,hn as runDeviceFlowSubprocess,kt as runWithMcpLogger,Xe as safeContentPath,nn as safeSubdir,yn as safetyCheckpoint,at as sanitizeClientName,Ht as saveInMemoryCheckpoint,On as saveVersion,lt as seedBasenameIndex,_t as setActiveSpanAttributes,cn as shadowGit,qt as shutdownTelemetry,Tt as splitMarkdownBlocks,xt as startWatcher,Ke as streamingProblemEvent,Mn as toBroadcasterKey,Wn as tracedAppendFileSync,et as tracedLinkSync,Bn as tracedMkdir,ve as tracedMkdirSync,p as tracedRename,In as tracedRenameSync,Se as tracedRmSync,x as tracedRmdirSync,_ as tracedUnlinkSync,re as tracedWriteFile,Lt as tracedWriteFileSync,a as updateLastKnownHash,tr as updateProcessLockPort,Xn as updateServerLockPort,Nt as updateUiLockPort,Y as validateAgentId,$ as validateCloneInputs,se as validateSkillZip,T as withSpan,F as withSpanSync,G as writePersonalTemplates,me as writeStateManifest,Jn as writeTargetVersion,l as writeTracker};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,d as t,h as n,m as r,o as i,p as a,r as o,u as s,v as c}from"./init-
|
|
1
|
+
import{_ as e,d as t,h as n,m as r,o as i,p as a,r as o,u as s,v as c}from"./init-DITZo5MW.mjs";import{n as l}from"./loader-C1XRvFmK.mjs";import{n as u}from"./preview-CNu5ET06.mjs";import{t as d}from"./src-qd3O6KiT.mjs";export{a as ALL_EDITOR_IDS,r as EDITOR_LABELS,n as EDITOR_TARGETS,o as detectInstalledEditors,c as initContent,l as loadConfig,u as previewContent,i as readExistingMcpEntry,e as resolveProjectRoot,s as writeEditorMcpConfig,d as writeProjectAiIntegrations,t as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as e}from"./init-DITZo5MW.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,F as s,Gn as c,It as l,Pt as u,Qr as d,ai as f,an as p,di as m,gi as h,hi as g,ii as _,in as v,on as y,pn as b,ri as x,si as S,un as C}from"./dist-D1HyCuHh.mjs";import{n as w,t as ee}from"./constants-Dy6rDbqx.mjs";import{t as T}from"./is-object-DF0ZeuvD.mjs";import{i as E,o as D,r as te,s as ne,t as O}from"./colors-BNufdynn.mjs";import{t as re}from"./preview-CrCqux1_.mjs";import{execFileSync as ie}from"node:child_process";import k,{basename as A,dirname as j,isAbsolute as ae,join as M,posix as oe,relative as N,resolve as P,sep as se,win32 as ce}from"node:path";import{cpSync as le,existsSync as F,lstatSync as ue,mkdirSync as I,readFileSync as de,realpathSync as fe,rmSync as pe,writeFileSync as L}from"node:fs";import R from"node:process";import{homedir as z}from"node:os";import{AsyncLocalStorage as me,AsyncResource as he}from"node:async_hooks";import{stripVTControlCharacters as ge,styleText as B}from"node:util";import*as _e from"node:readline";import{randomUUID as ve}from"node:crypto";import{createServer as ye,request as be}from"node:http";function xe(){return R.platform.startsWith(`win`)?!!R.env.CI||!!R.env.WT_SESSION||!!R.env.TERMINUS_SUBLIME||R.env.ConEmuTask===`{cmd::Cmder}`||R.env.TERM_PROGRAM===`Terminus-Sublime`||R.env.TERM_PROGRAM===`vscode`||R.env.TERM===`xterm-256color`||R.env.TERM===`alacritty`||R.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:R.env.TERM!==`linux`}const Se={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:`╱`},Ce={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:`⅒`},we={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`},Te={...Se,...Ce},Ee={...Se,...we},V=xe()?Te:Ee;Object.entries(Ce);var De=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 Oe=(()=>{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}})(),ke=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ae=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,je=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Me=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ne=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Pe=/\t{1,1000}/y,Fe=/[\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,Ie=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Le=/\p{M}+/gu,Re={limit:1/0,ellipsis:``},ze=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ze(i,Re,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ie,l],[je,0],[Me,o],[Pe,s],[Fe,c],[Ne,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(Le,``)){let t=e.codePointAt(0)||0;if(S=ke(t)?2:Ae(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===Ne?Oe(e.slice(p,n.lastIndex)):n===Fe?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}},Be={limit:1/0,ellipsis:``,ellipsisWidth:0},H=(e,t={})=>ze(e,Be,t).width,Ve=`]8;;`,He=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ve}(?<uri>.*))`,`y`),Ue=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},We=e=>`[${e}m`,Ge=e=>`${Ve}${e}`,Ke=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:H(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=H(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Ve,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())},qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!H(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Je=(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=H(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=H(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(``),Ke(s,r,t),c=H(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ke(s,r,t),c=H(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ke(s,r,t),c=H(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>qe(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,F as s,Gn as c,It as l,Pt as u,Qr as d,ai as f,an as p,di as m,gi as h,hi as g,ii as _,in as v,on as y,pn as b,ri as x,si as S,un as C}from"./dist-C0nimAjR.mjs";import{n as w,t as ee}from"./constants-9XRv4ouM.mjs";import{t as T}from"./is-object-DF0ZeuvD.mjs";import{i as E,o as D,r as te,s as ne,t as O}from"./colors-BNufdynn.mjs";import{t as re}from"./preview-CNu5ET06.mjs";import{execFileSync as ie}from"node:child_process";import k,{basename as A,dirname as j,isAbsolute as ae,join as M,posix as oe,relative as N,resolve as P,sep as se,win32 as ce}from"node:path";import{cpSync as le,existsSync as F,lstatSync as ue,mkdirSync as I,readFileSync as de,realpathSync as fe,rmSync as pe,writeFileSync as L}from"node:fs";import R from"node:process";import{homedir as z}from"node:os";import{AsyncLocalStorage as me,AsyncResource as he}from"node:async_hooks";import{stripVTControlCharacters as ge,styleText as B}from"node:util";import*as _e from"node:readline";import{randomUUID as ve}from"node:crypto";import{createServer as ye,request as be}from"node:http";function xe(){return R.platform.startsWith(`win`)?!!R.env.CI||!!R.env.WT_SESSION||!!R.env.TERMINUS_SUBLIME||R.env.ConEmuTask===`{cmd::Cmder}`||R.env.TERM_PROGRAM===`Terminus-Sublime`||R.env.TERM_PROGRAM===`vscode`||R.env.TERM===`xterm-256color`||R.env.TERM===`alacritty`||R.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:R.env.TERM!==`linux`}const Se={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:`╱`},Ce={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:`⅒`},we={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`},Te={...Se,...Ce},Ee={...Se,...we},V=xe()?Te:Ee;Object.entries(Ce);var De=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 Oe=(()=>{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}})(),ke=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ae=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,je=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Me=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ne=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Pe=/\t{1,1000}/y,Fe=/[\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,Ie=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Le=/\p{M}+/gu,Re={limit:1/0,ellipsis:``},ze=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ze(i,Re,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ie,l],[je,0],[Me,o],[Pe,s],[Fe,c],[Ne,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(Le,``)){let t=e.codePointAt(0)||0;if(S=ke(t)?2:Ae(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===Ne?Oe(e.slice(p,n.lastIndex)):n===Fe?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}},Be={limit:1/0,ellipsis:``,ellipsisWidth:0},H=(e,t={})=>ze(e,Be,t).width,Ve=`]8;;`,He=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ve}(?<uri>.*))`,`y`),Ue=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},We=e=>`[${e}m`,Ge=e=>`${Ve}${e}`,Ke=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:H(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=H(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Ve,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())},qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!H(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Je=(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=H(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=H(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(``),Ke(s,r,t),c=H(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ke(s,r,t),c=H(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ke(s,r,t),c=H(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>qe(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===``){He.lastIndex=e+1;let t=He.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+=Ge(``));let e=i?Ue(i):void 0;i&&e&&(r+=We(e))}else t===`
|
|
4
4
|
`&&(i&&Ue(i)&&(r+=We(i)),a&&(r+=Ge(a)))}return r},Ye=/\r?\n/;function Xe(e,t,n){return String(e).normalize().split(Ye).map(e=>Je(e,t,n)).join(`
|
|
@@ -400,9 +400,9 @@ last-spawn-error.log
|
|
|
400
400
|
# drafts/ # exclude a directory
|
|
401
401
|
# *.draft.md # exclude files matching a pattern
|
|
402
402
|
# !keep.md # re-include a file .gitignore excluded
|
|
403
|
-
`,`.okignore`)?r.push(`.okignore`):a.push(`.okignore`),{created:r,updated:i,skipped:a}}function $n(e,t){let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!ae(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??z(),r=t.gitTopLevel??er,i=P(e),a;try{a=fe(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=j(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=d,Z=x,rr=[`-y`,`@inkeep/open-knowledge@latest`,`mcp`],ir={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function ar(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=P(e);if(A(t)===`cli.mjs`&&A(j(t))===`dist`)return t;let n=t.split(se),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?se:i.join(se),`packages`,`cli`,`dist`,`cli.mjs`)}function or(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[ar(),`mcp`],env:{...ir}}:{command:`npx`,args:[...rr]}}function sr(e){return e===`win32`?ce:oe}function cr(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.claude.json`)}function lr(e={}){let t=e.platformName??process.platform,n=e.home??z(),r=e.env??process.env;if(t===`darwin`)return oe.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??ce.join(n,`AppData`,`Roaming`);return ce.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function ur(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.cursor`,`mcp.json`)}function dr(e={}){let t=e.platformName??process.platform,n=e.home??z();return(e.env??process.env).CODEX_HOME??sr(t).join(n,`.codex`)}function fr(e={}){return sr(e.platformName??process.platform).join(dr(e),`config.toml`)}function pr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>pr(e,t[n]));if(T(e)&&T(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=>pr(e[n],t[n]))}return!1}function mr(e,t){return Object.entries(t).every(([t,n])=>pr(e[t],n))}function hr(e,t){return{...e,...t}}function gr(e){return{...e,isCompatible(t,n,r){return mr(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return hr(t,e.buildEntry(n,r))}}}const Q={claude:gr({id:`claude`,label:Z.claude,configPath:(e,t)=>cr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>M(t??z(),`.claude`),projectConfigPath:e=>M(e,`.mcp.json`),projectSkillPath:e=>M(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)}),"claude-desktop":gr({id:`claude-desktop`,label:Z[`claude-desktop`],configPath:(e,t)=>lr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(lr({home:t}))}),cursor:gr({id:`cursor`,label:Z.cursor,configPath:(e,t)=>ur({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(ur({home:t})),projectConfigPath:e=>M(e,`.cursor`,`mcp.json`),projectSkillPath:e=>M(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)}),codex:gr({id:`codex`,label:Z.codex,configPath:(e,t)=>fr({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(fr({home:t})),projectConfigPath:e=>M(e,`.codex`,`config.toml`)})};function _r(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:${ve()}`;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=S.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 vr=1e4;function yr(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(!y(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 br=3e4,xr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Sr(e){let t=e.upstreamTimeoutMs??vr,n=ye((n,r)=>{yr(n,r)||wr(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e()),n.closeIdleConnections()})}}function Cr(e,t,n){wr(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??vr)}function wr(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of xr)delete a[e];e.setTimeout(br,()=>{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 ${br/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=be({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of xr)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 Tr=39847,Er=39848;async function Dr(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Or(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-DnmXfGWp.mjs`),{default:d}=await import(`./build-B4ZT2GMK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-DnmXfGWp.mjs`),g=p(e.config,e.cwd),v=h(e.cwd);i(v,{port:0,worktreeRoot:e.cwd});let y=import.meta.dirname??new URL(`.`,import.meta.url).pathname,b=[r(y,`public`),r(y,`../../app/dist`),r(y,`../../../app/dist`)].find(e=>t(e)),x=b?d(b,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,S=t(g)?o({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:d(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:f,assetExtensions:a,blocklistExtensions:_}):null,C=e.port,w=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&yr(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){w?.();let n=c(v),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,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(i);return}if(n?.startsWith(`/api/`)){w?.();let r=c(v);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}Cr(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(S){S(e,t,()=>{x?x(e,t):kr(t,n)});return}if(x){x(e,t);return}kr(t,n)}},T=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],E=[],D=e.port,te=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(E.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},O=async e=>{D=e;for(let e of T){let t=n(ee);E.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(D,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(D=e.port),n()})})}};try{try{await O(e.port)}catch(t){if(e.fallbackToKernel===!0&&te(t))await ne(),await O(0);else throw t}}catch(e){await ne();try{l(v)}catch{}throw e}let re=D;C=re,u(v,re);let ie=e.scheduler??m,k=e.safetyNetMs??432e5,A=null,j=!1,ae=!1,M=()=>{j||(j=!0,A!==null&&(ie.clearTimeout(A),A=null))},oe=()=>{if(M(),!ae){ae=!0;try{l(v)}catch{}}},N=()=>{j||k<=0||(A!==null&&(ie.clearTimeout(A),A=null),A=ie.setTimeout(()=>{A=null,console.warn(`[ui] safety-net (${k}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of E)try{e.close()}catch{}oe()},k))},P=()=>{j||k<=0||N()};return w=P,N(),{httpServers:E,port:re,release:oe,detachSafetyNet:M,nudgeSafetyNet:P}}function kr(e,t){$(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Ar(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:Tr,fallbackToKernel:!0}}async function jr(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-DnmXfGWp.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 Sr({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mr(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Tr}, 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-T3xmlXQT.mjs`),{UiLockCollisionError:r}=await import(`./dist-DnmXfGWp.mjs`),{resolveLockDir:i}=await import(`./dist-DnmXfGWp.mjs`),a=e(),o=t.host,s;try{s=Ar(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 Or({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)}};Dr(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 jr({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 Nr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(T(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 Pr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=In(t);if(T(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 Fr(e,t){I(j(e),{recursive:!0}),L(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ir(e,t){I(j(e),{recursive:!0});let n=Gn(t);L(e,n.endsWith(`
|
|
403
|
+
`,`.okignore`)?r.push(`.okignore`):a.push(`.okignore`),{created:r,updated:i,skipped:a}}function $n(e,t){let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!ae(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??z(),r=t.gitTopLevel??er,i=P(e),a;try{a=fe(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=j(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=d,Z=x,rr=[`-y`,`@inkeep/open-knowledge@latest`,`mcp`],ir={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function ar(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=P(e);if(A(t)===`cli.mjs`&&A(j(t))===`dist`)return t;let n=t.split(se),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?se:i.join(se),`packages`,`cli`,`dist`,`cli.mjs`)}function or(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[ar(),`mcp`],env:{...ir}}:{command:`npx`,args:[...rr]}}function sr(e){return e===`win32`?ce:oe}function cr(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.claude.json`)}function lr(e={}){let t=e.platformName??process.platform,n=e.home??z(),r=e.env??process.env;if(t===`darwin`)return oe.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??ce.join(n,`AppData`,`Roaming`);return ce.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function ur(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.cursor`,`mcp.json`)}function dr(e={}){let t=e.platformName??process.platform,n=e.home??z();return(e.env??process.env).CODEX_HOME??sr(t).join(n,`.codex`)}function fr(e={}){return sr(e.platformName??process.platform).join(dr(e),`config.toml`)}function pr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>pr(e,t[n]));if(T(e)&&T(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=>pr(e[n],t[n]))}return!1}function mr(e,t){return Object.entries(t).every(([t,n])=>pr(e[t],n))}function hr(e,t){return{...e,...t}}function gr(e){return{...e,isCompatible(t,n,r){return mr(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return hr(t,e.buildEntry(n,r))}}}const Q={claude:gr({id:`claude`,label:Z.claude,configPath:(e,t)=>cr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>M(t??z(),`.claude`),projectConfigPath:e=>M(e,`.mcp.json`),projectSkillPath:e=>M(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)}),"claude-desktop":gr({id:`claude-desktop`,label:Z[`claude-desktop`],configPath:(e,t)=>lr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(lr({home:t}))}),cursor:gr({id:`cursor`,label:Z.cursor,configPath:(e,t)=>ur({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(ur({home:t})),projectConfigPath:e=>M(e,`.cursor`,`mcp.json`),projectSkillPath:e=>M(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)}),codex:gr({id:`codex`,label:Z.codex,configPath:(e,t)=>fr({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(fr({home:t})),projectConfigPath:e=>M(e,`.codex`,`config.toml`)})};function _r(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:${ve()}`;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=S.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 vr=1e4;function yr(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(!y(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 br=3e4,xr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Sr(e){let t=e.upstreamTimeoutMs??vr,n=ye((n,r)=>{yr(n,r)||wr(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e()),n.closeIdleConnections()})}}function Cr(e,t,n){wr(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??vr)}function wr(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of xr)delete a[e];e.setTimeout(br,()=>{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 ${br/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=be({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of xr)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 Tr=39847,Er=39848;async function Dr(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Or(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-Cne34K7V.mjs`),{default:d}=await import(`./build-B4ZT2GMK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-Cne34K7V.mjs`),g=p(e.config,e.cwd),v=h(e.cwd);i(v,{port:0,worktreeRoot:e.cwd});let y=import.meta.dirname??new URL(`.`,import.meta.url).pathname,b=[r(y,`public`),r(y,`../../app/dist`),r(y,`../../../app/dist`)].find(e=>t(e)),x=b?d(b,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,S=t(g)?o({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:d(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:f,assetExtensions:a,blocklistExtensions:_}):null,C=e.port,w=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&yr(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){w?.();let n=c(v),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,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(i);return}if(n?.startsWith(`/api/`)){w?.();let r=c(v);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}Cr(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(S){S(e,t,()=>{x?x(e,t):kr(t,n)});return}if(x){x(e,t);return}kr(t,n)}},T=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],E=[],D=e.port,te=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(E.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},O=async e=>{D=e;for(let e of T){let t=n(ee);E.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(D,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(D=e.port),n()})})}};try{try{await O(e.port)}catch(t){if(e.fallbackToKernel===!0&&te(t))await ne(),await O(0);else throw t}}catch(e){await ne();try{l(v)}catch{}throw e}let re=D;C=re,u(v,re);let ie=e.scheduler??m,k=e.safetyNetMs??432e5,A=null,j=!1,ae=!1,M=()=>{j||(j=!0,A!==null&&(ie.clearTimeout(A),A=null))},oe=()=>{if(M(),!ae){ae=!0;try{l(v)}catch{}}},N=()=>{j||k<=0||(A!==null&&(ie.clearTimeout(A),A=null),A=ie.setTimeout(()=>{A=null,console.warn(`[ui] safety-net (${k}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of E)try{e.close()}catch{}oe()},k))},P=()=>{j||k<=0||N()};return w=P,N(),{httpServers:E,port:re,release:oe,detachSafetyNet:M,nudgeSafetyNet:P}}function kr(e,t){$(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Ar(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:Tr,fallbackToKernel:!0}}async function jr(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-Cne34K7V.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 Sr({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mr(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Tr}, 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-T3xmlXQT.mjs`),{UiLockCollisionError:r}=await import(`./dist-Cne34K7V.mjs`),{resolveLockDir:i}=await import(`./dist-Cne34K7V.mjs`),a=e(),o=t.host,s;try{s=Ar(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 Or({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)}};Dr(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 jr({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 Nr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(T(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 Pr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=In(t);if(T(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 Fr(e,t){I(j(e),{recursive:!0}),L(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ir(e,t){I(j(e),{recursive:!0});let n=Gn(t);L(e,n.endsWith(`
|
|
404
404
|
`)?n:`${n}\n`,`utf-8`)}function Lr(e,t){let n;try{n=fe(t)}catch{n=P(t)}let r;try{r=ue(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=j(e);for(;i.length>1&&i!==se;){let t;try{t=fe(i)}catch(e){if(e.code===`ENOENT`){i=j(i);continue}throw e}let r=N(n,t);if(r===``||!r.startsWith(`..`)&&!ae(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 Rr=e=>e!==`project`,zr=e=>e!==`user`;async function Br(){let e=await fn({message:`Where should the MCP server be configured?
|
|
405
405
|
`,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 Vr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Br)():`both`}const Hr=`0.0.1`,Ur=`open-knowledge-ui`,Wr=[`-y`,`@inkeep/open-knowledge@latest`,`ui`];function Gr(e,t={}){let n=M(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:Ur,runtimeExecutable:`node`,runtimeArgs:[ar(),`ui`],port:Er,autoPort:!0}:{name:Ur,runtimeExecutable:`npx`,runtimeArgs:[...Wr],port:Er,autoPort:!0};try{if(Lr(n,e),!F(n))return I(j(n),{recursive:!0}),L(n,`${JSON.stringify({version:Hr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=de(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!T(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>T(e)&&e.name===`open-knowledge-ui`);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Hr,configurations:a};return L(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 Kr(e,t,n){try{return F(e.detectPath?.(t,n)??j(e.configPath(t,n)))}catch{return!1}}function qr(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&&!Kr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Lr(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`?Pr(o):Nr(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`?Ir(o,d):Fr(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 Jr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=c(),i=j(n);Lr(i,t);let a=F(n)?`overwritten`:`written`;return pe(i,{recursive:!0,force:!0}),I(j(i),{recursive:!0}),le(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 Yr(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!F(n)))return{editorId:e.id,label:e.label,path:n}}async function Xr(e){let t=_r(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>qr(t,``,n,e.home))}function Zr(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return null}let a;try{a=e.format===`toml`?Pr(i):Nr(i)}catch{return null}let o=a[e.topLevelKey];if(!T(o))return null;let s=o[e.serverName(t)];return T(s)?s:null}async function Qr(e={}){let t=P(e.cwd??process.cwd()),n=tr(t,{homeDir:e.home}),r=n.projectRoot,i=!F(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 ${N(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await l(r),s;try{s=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 c=await Vr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),d=e.editors??ei(r,e.home),f=e.editors??nr.filter(e=>Q[e].projectConfigPath!==void 0),p=_r(d),m=_r(f),h=e.mcp===!1||c===null,g=Array.from(new Map([...p,...h?[]:m].map(e=>[e.id,e])).values()),_=p.filter(t=>Kr(t,r,e.home)),y=[],b=[],x=new Set;for(let t of g){if(h){let n=``;try{n=t.configPath(r,e.home)}catch{}y.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(Rr(c)&&p.includes(t)&&y.push(qr(t,r,a,e.home)),zr(c)&&m.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=qr(t,r,a,e.home,n);y.push(i),(i.action===`written`||i.action===`overwritten`)&&(x.add(n),b.push(Jr(t,r)))}}let S=!h&&c!==null&&zr(c)?m.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,C=h?[]:_.map(e=>Yr(e,r)).filter(e=>e!==void 0).filter(e=>!x.has(e.path)),w=_.some(e=>e.id===`claude`)&&!h?Gr(r,a):void 0,ee=await(e.installUserSkill??v)({home:e.home}),T=u({home:e.home}),E=h?`skipped-flag`:`skipped-missing`,D=y.find(e=>e.editorId===`claude`)??y[0]??{action:E,configPath:Q.claude.configPath(r,e.home)};return{projectRoot:r,contentCreated:s.created,contentUpdated:s.updated,contentSkipped:s.skipped,editors:y,projectSkills:b,legacyProjectConfigs:C,launchJson:w,skillInstall:ee,didGitInit:o.didInit,claudeDesktopDetected:T,mcpAction:D.action,mcpPath:D.configPath,mcpError:`error`in D?D.error:void 0,projectScopeUnsupportedLabels:S}}function $r(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)?N(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)?N(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${D(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${D(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${te(`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?N(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${D(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${D(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${te(`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} ${N(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 ${D(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${D(`already installed at current version`)}`);break;case`failed`:n.push(` ${ne(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${ne(` 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(`${D(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${E(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${E(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${E(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${E(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${E(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
|
|
406
406
|
`)}function ei(e,t){let n=[];for(let r of nr)Kr(Q[r],e,t)&&n.push(r);return n}function ti(){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 Qr({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof s){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
407
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
408
|
-
//# sourceMappingURL=init-
|
|
407
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-CpsM6Oy_.mjs`),{loadConfig:t}=await import(`./loader-C9nvsl4r.mjs`),{resolveContentDir:r}=await import(`./dist-Cne34K7V.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(`${$r(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{pt as C,Xe as D,Ze as E,De as O,ht as S,ct as T,tr as _,ti as a,dt as b,Qr as c,Xr as d,Mr as f,rr as g,Q as h,$r as i,V as k,Gr as l,Z as m,Wr as n,Zr as o,nr as p,ei as r,Vr as s,Ur as t,qr as u,Qn as v,_t as w,ft as x,mt as y};
|
|
408
|
+
//# sourceMappingURL=init-DITZo5MW.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Jr as e,f as t,fi as n,ji as r,qr as i,vi as a}from"./dist-
|
|
1
|
+
import{Jr as e,f as t,fi as n,ji as r,qr as i,vi as a}from"./dist-C0nimAjR.mjs";import{t as o}from"./constants-9XRv4ouM.mjs";import{t as s}from"./is-object-DF0ZeuvD.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=r();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(r){let a=r??process.cwd(),s=[],l=e(`user`,a),u=i({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(n).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=t.safeParse(d);if(!g.success){let e={code:`SCHEMA_INVALID`,issues:y(g.error.issues,p)};throw Error(n(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-C1XRvFmK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-C1XRvFmK.mjs";export{e as loadConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Ct as e}from"./dist-
|
|
1
|
+
import{Ct as e}from"./dist-C0nimAjR.mjs";import"./constants-9XRv4ouM.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-CNu5ET06.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-CNu5ET06.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-DITZo5MW.mjs";import{t as n}from"./is-object-DF0ZeuvD.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-BE8BhJHf.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-DITZo5MW.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-RaKlR1Tj.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-DITZo5MW.mjs";import"./loader-C1XRvFmK.mjs";import"./preview-CNu5ET06.mjs";function r(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{r as t};
|
|
2
|
+
//# sourceMappingURL=src-qd3O6KiT.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-
|
|
1
|
+
import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-C0nimAjR.mjs";import{n as r}from"./constants-9XRv4ouM.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)"),e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`}).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-Cne34K7V.mjs`),g=e.log??d(`start`);if(!a&&!n(r))throw new C(r);try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-RaKlR1Tj.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-BE8BhJHf.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-KC_FjiUK.mjs`),{dim:i,error:a,warning:o}=await import(`./colors-T3xmlXQT.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-Cne34K7V.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-BzeK2VhT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as e}from"./start-BzeK2VhT.mjs";export{e as startCommand};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inkeep/open-knowledge",
|
|
3
|
-
"version": "0.5.0-beta.
|
|
3
|
+
"version": "0.5.0-beta.29",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@inquirer/checkbox": "^5.0.11",
|
|
46
46
|
"@inquirer/password": "^5.0.11",
|
|
47
|
-
"@modelcontextprotocol/sdk": "
|
|
47
|
+
"@modelcontextprotocol/sdk": "1.29.0",
|
|
48
48
|
"@napi-rs/keyring": "^1.2.0",
|
|
49
49
|
"@octokit/auth-oauth-device": "^8.0.3",
|
|
50
50
|
"@octokit/request": "^10.0.8",
|
package/dist/init-BBRgjZZW.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as e}from"./init-CwWjtnYQ.mjs";export{e as runInit};
|
package/dist/loader-B21ETXD-.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./loader-DI-aJeHv.mjs";export{e as loadConfig};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./preview-CrCqux1_.mjs";export{t as formatPreviewBlock,e as previewContent};
|
package/dist/start-C1vmnar4.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l as e}from"./start-DXb8xQF1.mjs";export{e as startCommand};
|