@inkeep/open-knowledge 0.0.0-dev-20260423222123 → 0.0.0-dev-20260423231521
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/cli.mjs +8 -8
- package/dist/constants-DA7Qh-Kl.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/init-CFVYH-16.mjs +1 -0
- package/dist/{init-BEYJxssT.mjs → init-CODC0Drd.mjs} +2 -2
- package/dist/init-DQNJ_f3z.mjs +1 -0
- package/dist/{init-Ca3oXZ2r.mjs → init-DysAQtCG.mjs} +3 -3
- package/dist/loader-89zKhhvs.mjs +1 -0
- package/dist/{loader-AGQcuG-5.mjs → loader-DfTFnc2z.mjs} +2 -2
- package/dist/{paths-BHyG1wt5.mjs → paths-B9hXoumv.mjs} +2 -2
- package/dist/paths-BhmQnYL9.mjs +1 -0
- package/dist/preview-CULBnUoI.mjs +1 -0
- package/dist/{preview-BNr7OMR-.mjs → preview-jDZwLSul.mjs} +2 -2
- package/dist/server-lock-BI-SqMWk.mjs +2 -0
- package/dist/server-lock-zOHsiWX-.mjs +1 -0
- package/dist/src-CBVTx8JJ.mjs +1 -0
- package/dist/src-DHnGx64r.mjs +1 -0
- package/dist/{src-skP-DoiW.mjs → src-rqPIkHTi.mjs} +3 -3
- package/dist/start-D0wsbZmD.mjs +1 -0
- package/dist/{start-BJ0_AeSA.mjs → start-DAAnFlO5.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-By8TCEux.mjs +0 -2
- package/dist/init-Z_14KXK6.mjs +0 -1
- package/dist/init-t1KAo7Xn.mjs +0 -1
- package/dist/loader-C_Bm1Mam.mjs +0 -1
- package/dist/paths-OkgDVC2Q.mjs +0 -1
- package/dist/preview-BRaI8Ld9.mjs +0 -1
- package/dist/server-lock-B4frNnOB.mjs +0 -2
- package/dist/server-lock-CPmOhzSz.mjs +0 -1
- package/dist/src-Cgf9w34f.mjs +0 -1
- package/dist/src-DB3pnkMU.mjs +0 -1
- package/dist/start-iuBWR-Az.mjs +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,i as t}from"./constants-
|
|
2
|
+
import{a as e,i as t}from"./constants-DA7Qh-Kl.mjs";import{O as n,c as r,k as i}from"./src-CQw-HNNM.mjs";import{n as a,t as o}from"./paths-B9hXoumv.mjs";import{ct as s,lt as c,m as l,nt as u,st as d,ut as f}from"./src-rqPIkHTi.mjs";import{c as p,f as m,r as h}from"./server-lock-BI-SqMWk.mjs";import{i as g}from"./init-CODC0Drd.mjs";import{t as _}from"./is-object-DaHwJLOe.mjs";import{r as v}from"./init-DysAQtCG.mjs";import{i as y,n as ee,t as b}from"./loader-DfTFnc2z.mjs";import{o as x,s as S}from"./start-DAAnFlO5.mjs";import"./src-CBVTx8JJ.mjs";import{Command as C}from"commander";import{appendFileSync as w,closeSync as T,existsSync as E,mkdirSync as D,openSync as te,readFileSync as O,readdirSync as ne,realpathSync as re,statSync as ie,unlinkSync as ae,writeFileSync as oe}from"node:fs";import{homedir as se,hostname as ce}from"node:os";import{basename as le,dirname as ue,isAbsolute as de,join as fe,relative as pe,resolve as k}from"node:path";import{parse as me,stringify as he}from"yaml";import{createOAuthDeviceAuth as ge}from"@octokit/auth-oauth-device";import _e from"@inquirer/password";import{Octokit as ve}from"@octokit/rest";import{fileURLToPath as ye}from"node:url";import{randomUUID as be}from"node:crypto";import{execFileSync as xe,spawn as Se}from"node:child_process";import Ce from"simple-git";import{readFile as we,readdir as Te,stat as Ee}from"node:fs/promises";import{createServer as De,request as Oe}from"node:http";import ke from"picomatch";import{z as A}from"zod";import{McpServer as Ae}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as je}from"@modelcontextprotocol/sdk/server/stdio.js";import{RootsListChangedNotificationSchema as Me}from"@modelcontextprotocol/sdk/types.js";import{AsyncLocalStorage as Ne}from"node:async_hooks";import{Bash as Pe,ReadWriteFs as Fe}from"just-bash";import Ie from"shell-quote";const Le=`open-knowledge`;var Re=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Le,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(Le,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(Le,e).deletePassword()}catch{}}},ze=class{backend=`file`;authFile;constructor(e){this.authFile=e??fe(se(),`.open-knowledge`,`auth.yml`)}read(){if(!E(this.authFile))return{};try{return me(O(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=ue(this.authFile);E(t)||D(t,{recursive:!0,mode:448}),oe(this.authFile,he(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 Be(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Le,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
3
3
|
`),new Re}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
|
|
4
4
|
`),new ze(e)}}async function Ve(e,t,n){let r=He(await Ue(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 He(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 Ue(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 We(e){let t=new C(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Ve(process.stdin,process.stdout,t);process.exit(n)}),t}async function Ge(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=ge({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(`@octokit/request`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Ke(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const qe=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Je(e){let t=e.toLowerCase().replace(/:\d+$/,``);qe.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 Ye(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Xe(e,t,n,r=Ge){let i=Ke(n),{host:a,json:o}=e;Je(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?Ye(!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`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?Ye(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Ze(e,t){return new C(`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 n=>{await Xe(n,await t(),e())})}async function Qe(e,t,n){let{host:r,json:i}=e;Je(r);let a=await(n??(()=>_e({message:`Enter PAT:`})))();a||(process.stderr.write(`No token provided
|
|
@@ -7,7 +7,7 @@ import{a as e,i as t}from"./constants-By8TCEux.mjs";import{O as n,c as r,k as i}
|
|
|
7
7
|
`),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 $e(e){return new C(`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 Qe(t,await e())})}async function et(e,t){let{host:n,json:r}=e;Je(n);let i=await t.get(n);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 ve({auth:i.token,...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 tt(e){return new C(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await et(t,await e())})}async function nt(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function rt(e){return new C(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await nt(t,await e())})}async function it(e,t){let{host:n,json:r}=e;Je(n);let i=await t.get(n);i??(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 ve({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,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`})+`
|
|
8
8
|
`):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function at(e){return new C(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await it(t,await e())})}function ot(e){let t=new C(`auth`);t.description(`GitHub authentication management`);let n=()=>Be(),r=e??(()=>({}));return t.addCommand(Ze(r,n)),t.addCommand(at(n)),t.addCommand(tt(n)),t.addCommand(rt(n)),t.addCommand($e(n)),t.addCommand(We(n)),t}function st(e,t,n={}){let r=p(e,t);if(!E(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(O(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??ce();return a.hostname===o?(n.isAlive??m)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function ct(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 lt(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.unlink??(e=>ae(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=ct(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 ut(e){return new C(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{lt({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function dt(){try{let e=xe(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function ft(e,t,n={},r=dt){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 pt(e){return e.replace(/:\d+$/,``)}function mt(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:pt(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:pt(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:pt(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 ht=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function gt(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 ht)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function _t(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function vt(e,t,n,r=process.cwd()){let i=mt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?k(r,t.dir):k(r,i.name);if(E(a)&&ne(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Be(),s=await ft(i.hostname,o,{}),c=Ce({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;if(c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
|
|
9
9
|
`)){let n=gt(e);n&&n.pct!==l&&(l=n.pct,_t(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(`
|
|
10
|
-
`),!E(k(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-
|
|
10
|
+
`),!E(k(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-DQNJ_f3z.mjs`),import(`./init-CFVYH-16.mjs`)]);await e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function yt(e){return new C(`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 vt(t,{json:r.json,dir:n},i);if(r.json)_t(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-D0wsbZmD.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?_t(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const bt=new Ne;var xt=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??be().slice(0,12),this.corrId=be().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{w(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function St(e=`mcp`){return new xt(e)}function Ct(e,t){return bt.run(e,t)}function wt(){return bt.getStore()}const Tt=new Set([`find`,`markdown`,`replace`]),Et=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],Dt=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ot(e){return j(e)&&`requestId`in e}function kt(e,t){if(Tt.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
11
11
|
`).length};let n=e===`command`?240:120;return t.length<=n?t:{type:`string`,length:t.length,preview:`${t.slice(0,n)}...`}}function At(e,t){if(t===null)return null;if(typeof t==`string`)return kt(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(j(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function jt(e,t){return j(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,At(e,t)])):At(e,t)}function Mt(e){let t={structuredKeys:Object.keys(e).sort()};for(let n of Dt)n in e&&(t[n]=e[n]);for(let n of Et){let r=e[n];Array.isArray(r)&&(t[`${n}Count`]=r.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),j(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),j(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function Nt(e){if(!j(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>j(t)&&typeof t.text==`string`?e+t.text.length:e,0)),j(e.structuredContent)&&Object.assign(t,Mt(e.structuredContent)),t}function Pt(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{},...e.label?{label:e.label}:{}}}function Ft(e){let t=e.at(-1);return Ot(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function It(e,t,n){let r=n.logger;return r?async(...i)=>{let a=r.child(),o=Date.now(),{toolArgs:s,extra:c}=Ft(i);a.info(`tool start`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},...c?.sessionId?{transportSessionId:c.sessionId}:{},...n.identityRef?.current?{agent:Pt(n.identityRef.current)}:{},...s===void 0?{}:{args:jt(e,s)}});try{let n=await Ct(a,async()=>await t(...i));return a.info(`tool finish`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o,result:Nt(n)}),n}catch(t){throw a.error(`tool error`,t,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o}),t}}:t}function Lt(e,t){if(!t.logger)return e;let n=e.tool.bind(e),r=Object.create(e);return r.tool=((...e)=>{let r=String(e[0]),i=e.at(-1);if(typeof i!=`function`)return n(...e);let a=[...e];return a[a.length-1]=It(r,i,t),n(...a)}),r}const M="Absolute host path to resolve the request against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.",Rt=A.string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function N(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function P(e,t,n){return{content:[{type:`text`,text:e}],structuredContent:t,...n?{isError:!0}:{}}}const F="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.";async function zt(e,t){return typeof e==`function`?await e(t):e}async function Bt(e,t){return typeof e==`function`?await e(t):e}async function I(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await Bt(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function L(e,t,n,r){let i=await I(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await zt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function z(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function B(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function Vt(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
|
|
12
12
|
|
|
13
13
|
Topic: ${e}
|
|
@@ -151,15 +151,15 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
151
151
|
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
|
|
152
152
|
|
|
153
153
|
Full convention: read \`${n}/AGENTS.md\`.`}const Ht=[`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(`
|
|
154
|
-
`);function Ut(e,t){e.tool(`consolidate`,Ht,{topic:A.string().describe(`The topic to consolidate into a canonical article`),cwd:A.string().optional().describe(M)},async e=>{let n=await I(t.resolveCwd,t.config,e.cwd);return n.ok?P(Vt(e.topic,n.config.content.dir),{previewUrl:null}):N(`Error: ${n.error}`,!0)})}function Wt(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Gt(e){return e.endsWith(`/`)?e.slice(0,-1):e}function Kt(e){try{return new URL(e),!0}catch{return!1}}async function V(e,t,n){let r=n??await t.resolveCwd(),i=await Bt(t.config,r),s=o(i,r);return U(e,{config:i,lockDir:a(s),contentDir:s})}function qt(e){try{let t=
|
|
154
|
+
`);function Ut(e,t){e.tool(`consolidate`,Ht,{topic:A.string().describe(`The topic to consolidate into a canonical article`),cwd:A.string().optional().describe(M)},async e=>{let n=await I(t.resolveCwd,t.config,e.cwd);return n.ok?P(Vt(e.topic,n.config.content.dir),{previewUrl:null}):N(`Error: ${n.error}`,!0)})}function Wt(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Gt(e){return e.endsWith(`/`)?e.slice(0,-1):e}function Kt(e){try{return new URL(e),!0}catch{return!1}}async function V(e,t,n){let r=n??await t.resolveCwd(),i=await Bt(t.config,r),s=o(i,r);return U(e,{config:i,lockDir:a(s),contentDir:s})}function qt(e){try{let t=u(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 H(e,t){let n=t??await e.resolveCwd(),r=await Bt(e.config,n),i=o(r,n),s={config:r,lockDir:a(i),contentDir:i};return{resolve:e=>U(e,s),ui:qt(s)}}function Jt(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function U(e,t){let n=`/#/${Wt(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=re(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&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`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&Kt(r))return{url:`${Gt(r)}${n}`,source:`env`};try{let e=u(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&Kt(i)?{url:`${Gt(i)}${n}`,source:`config`}:null}const Yt=["**IMPORTANT: Before calling this tool, you MUST first call `get_preview_url` and navigate to the returned URL in your preview browser. If `get_preview_url` returns null, start the server first (`open-knowledge start` or `preview_start`), then call `get_preview_url` again. Do NOT call this tool without the preview open. NEVER manually construct the URL.**",``,`[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.",``,"**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(`
|
|
155
155
|
`);function Xt(e,t){e.tool(`edit_document`,Yt,{docName:A.string().describe(`Document name to edit`),find:A.string().describe(`Text to find (exact match)`),replace:A.string().describe(`Replacement text`),offset:A.number().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:Rt,cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:s}=n;if(!s)return N(F,!0);let c=R(e.docName);if(!c.ok)return N(c.error,!0);let l=t.identityRef?.current,u=await B(s,`/api/agent-patch`,{docName:c.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...l?{agentId:l.connectionId,agentName:l.displayName,clientName:l.clientInfo?.name,colorSeed:l.colorSeed}:{}});if(!u.ok)return N(`Error: ${u.error}`,!0);let d=a(o(i,r)),f=U(c.docName,{config:i,lockDir:d}),p=(typeof u.subscriberCount==`number`?u.subscriberCount:void 0)===0,m=u.summary&&typeof u.summary==`object`?u.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];f&&g.push(`Preview: ${f.url}`),p&&g.push(f?`Warning: no preview is currently attached to "${c.docName}". Open ${f.url} to watch future edits live.`:`Warning: no preview is currently attached to "${c.docName}".`),h&&g.push(h);let _=g.join(`
|
|
156
156
|
`);if(!f&&!p&&!m)return N(_);let v={};return f&&(v.previewUrl=f.url,v.previewUrlSource=f.source),p&&(v.warning={message:`No preview attached to ${c.docName}.`,previewUrl:f?.url??null}),m&&(v.summary=m),P(_,v)})}const Zt=new Set([`cat`,`ls`,`grep`,`find`]),Qt=/\b[\w./-]+\.(md|mdx)\b/g;function W(e){return/\.(md|mdx)$/.test(e)}function G(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 K(e){return e.args.slice(1)}function q(e){return e.filter(e=>!e.startsWith(`-`))}function $t(e){return q(K(e)).filter(W)}function en(e,t){let n=q(K(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?G(r):``,a=[];i&&a.push(i);for(let t of e.split(`
|
|
157
157
|
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!W(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function tn(e){let t=[];for(let n of e.split(`
|
|
158
158
|
`)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=G(n.slice(0,e));W(r)&&t.push(r)}return t}function nn(e){let t=[];for(let n of e.split(`
|
|
159
159
|
`)){let e=G(n);e&&W(e)&&t.push(e)}return t}function rn(e){return q(K(e)).filter(W)}function an(e){return q(K(e)).length>0}function on(e){let t=[],n=e.matchAll(Qt);for(let e of n)t.push(G(e[0]));return t}function sn(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(Zt.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&an(r)){n=r;break}}let r;if(!n)r=on(e);else{switch(n.command){case`cat`:r=$t(n);break;case`ls`:r=en(e,n);break;case`grep`:r=tn(e);break;case`find`:r=nn(e);break;case`head`:case`tail`:r=rn(n);break;default:r=on(e)}r.length===0&&(r=on(e))}let i=new Set,a=[];for(let e of r){let t=G(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}function J(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const cn=16*1024*1024;var ln=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function un(e){if(!de(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Pe({cwd:`/`,fs:new Fe({root:k(e),allowSymlinks:!1})})}async function dn(e,t){let n=await e.exec(t);if(n.stdout.length>cn)throw new ln(cn,n.stdout.length,{stdout:n.stdout.slice(0,cn),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function fn(e){return e.startsWith(`**/`)?e.slice(3):e}async function pn(e,t,n={}){let r=un(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${J(fn(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${J(fn(e))}`),i.push(`--exclude-dir=${J(fn(e))}`);let a=n.paths?.length?n.paths.map(J):[`.`],o=`grep ${i.join(` `)} ${J(e)} ${a.join(` `)}`,s;try{s=await dn(r,o)}catch(e){if(e instanceof ln)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
|
|
160
160
|
`)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const mn=new Set([`.git`,n,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function hn(e){let t=k(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await Te(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&mn.has(s.name))continue;let o=k(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await Ee(o);n.set(pe(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function gn(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}const _n=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,n,`.claude`];function vn(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const yn=[{command:`grep`,applies:e=>e.slice(1).some(vn),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function bn(e){return e.map(e=>{let t=yn.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(_n),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function xn(e){return e.map(e=>e.args.map(J).join(` `)).join(` | `)}const Sn=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),Cn=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),wn=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),Tn=new Set([`-o`,`--output-file`,`--output`]),En=[`-o=`,`--output-file=`,`--output=`],Dn=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),On=/[`]|\$\(|\$\{|\$'/;function kn(e){return typeof e==`object`&&!!e&&`op`in e}function An(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return Cn.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:wn.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function jn(e){let t=[];for(let n of e){if(typeof n==`string`){if(On.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!kn(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:An(n)}}return{args:t}}function Mn(e){if(!Sn.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(Tn.has(t)||En.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&Dn.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function Nn(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=Ie.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(kn(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=jn(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=Mn(n);if(r)return{error:r};a.push(n)}return{stages:a}}const Pn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function Fn(e,t){let n=e.match(Pn);if(!n)return null;try{let e=me(n[1]);if(_(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}const In=new WeakMap;function Ln(e){let t=In.get(e);if(t)return t;let n=e.map(e=>ke(e.match,{dot:!0}));return In.set(e,n),n}function Rn(e,t){if(e.length===0)return{};let n=Ln(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function zn(e){try{return ie(k(e,`.git`)).isDirectory()}catch{return!1}}function Bn(e){return Ce({baseDir:k(e),timeout:{block:5e3}})}async function Vn(e,t,n=5){if(!zn(e))return{commits:[],source:`git-absent`};let r=Bn(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
161
|
-
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const Hn=5e3;async function Un(e){try{let t=(await Ce({baseDir:e,timeout:{block:Hn}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Wn(e,t){return Ce({baseDir:t,timeout:{block:Hn}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Gn(e,t){let n=
|
|
162
|
-
`).map(e=>e.trim()).filter(Boolean);return
|
|
161
|
+
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const Hn=5e3;async function Un(e){try{let t=(await Ce({baseDir:e,timeout:{block:Hn}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Wn(e,t){return Ce({baseDir:t,timeout:{block:Hn}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Gn(e,t){let n=s(t);return e.startsWith(n)?e.slice(n.length):e}async function Kn(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=Gn(t,r),s=c(o),l=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,c=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&l.push({hash:d,date:i,writerName:a,message:c,contributors:f(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return l}async function qn(e,t,n=5){let r=d(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await Un(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Wn(r,k(e)),o=``;try{o=await a.raw(`for-each-ref`,s(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let c=o.split(`
|
|
162
|
+
`).map(e=>e.trim()).filter(Boolean);return c.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(c.map(e=>Kn(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const Jn=1e3,Yn=new Set([`.git`,n,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Xn=/\.(md|mdx)$/i,Zn=A.object({title:A.string().optional(),description:A.string().optional(),tags:A.array(A.string()).default([])});function Qn(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function $n(e){try{let t=Fn(await we(e,`utf-8`),Zn);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function er(e,t){if(!e)return null;let n=await z(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function tr(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await z(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function nr(e,t){if(!e)return null;let n=await z(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function rr(e,t,n){let r=t??[],i=r.length===0?{}:Rn(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function ir(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=k(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=$n(i);if(!o){let e=rr(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,er(t.serverUrl,Qn(r)).catch(()=>null),nr(t.serverUrl,Qn(r)).catch(()=>null),qn(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),Vn(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=rr(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function ar(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=Jn){n.truncated=!0;break}let a;try{a=await Te(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=Jn){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Yn.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Xn.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Ee(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:pe(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function or(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await ar(k(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await $n(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??le(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=Rn(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const sr=50*1024,cr=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,lr=[`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
|
|
163
163
|
`);function ur(e){let t=e.split(`
|
|
164
164
|
`),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=sr)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>sr)break;a++}let o=t.slice(0,a).join(`
|
|
165
165
|
`),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function dr(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||cr.test(e)&&t.push(e);return t}function fr(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function pr(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=fr(n.args),i=t.split(`
|
|
@@ -172,7 +172,7 @@ Full convention: read \`${n}/AGENTS.md\`.`}const Ht=[`Promote research into a ca
|
|
|
172
172
|
`);function Ar(e,t){e.tool(`get_history`,kr,{docName:A.string().describe(`Document name to query history for`),branch:A.string().optional().describe(`Branch name (default: current branch)`),limit:A.number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:A.number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:A.enum([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:A.string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:A.string().optional().describe(`Exclude entries by this author name or email`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=R(e.docName);if(!a.ok)return N(a.error,!0);let o=new URLSearchParams;o.set(`docName`,a.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 s=await z(i,`/api/history?${o.toString()}`);if(!s.ok)return N(`Error: ${s.error}`,!0);let{ok:c,...l}=s,u=await V(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return P(JSON.stringify(l,null,2),{...l,previewUrl:u?.url??null,...u?{previewUrlSource:u.source}:{}})})}const jr=[`[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(`
|
|
173
173
|
`);function Mr(e,t){e.tool(`get_hubs`,jr,{limit:A.number().int().positive().optional().describe(`Maximum number of hubs to return`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=await z(i,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!a.ok)return N(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await H(t,r),d=(c.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,hubs:d,ui:u,cwd:r};return P(JSON.stringify(f,null,2),f)})}const Nr=[`[Requires: Hocuspocus server] Find disconnected pages in the knowledge graph.`,`Returns orphaned pages as JSON.`,``,`**Parameters:**`,"- `mode` (optional) — Orphan lens: `incoming`, `outgoing`, or `both` (default `both`)"].join(`
|
|
174
174
|
`);function Pr(e,t){e.tool(`get_orphans`,Nr,{mode:A.enum(i).optional().describe(`Filter which type of graph disconnection to surface`),cwd:A.string().optional().describe(M)},async e=>{let n=await L(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return N(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return N(F,!0);let a=await z(i,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!a.ok)return N(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await H(t,r),d=(c.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,orphans:d,ui:u,cwd:r};return P(JSON.stringify(f,null,2),f)})}const Fr=["Return a browser URL for the given wiki docName. Agents should call this IMMEDIATELY BEFORE `write_document` / `edit_document` so they can navigate the preview browser to the doc first and watch the CRDT edit land live.",``,`**Parameters:**`,"- `docName` — Wiki doc name, typically without extension.",``,"Returns `{ previewUrl, previewUrlSource }` (source: `env` / `lock` / `config`). When no source is configured, returns `{ previewUrl: null }` and the agent may proceed without navigation."].join(`
|
|
175
|
-
`);async function Ir(e,t){let n=R(e.docName);if(!n.ok)return{ok:!1,error:n.error};let r=n.docName,i=await I(t.resolveCwd,t.config,e.cwd);if(!i.ok)return i;let{cwd:s,config:c}=i,
|
|
175
|
+
`);async function Ir(e,t){let n=R(e.docName);if(!n.ok)return{ok:!1,error:n.error};let r=n.docName,i=await I(t.resolveCwd,t.config,e.cwd);if(!i.ok)return i;let{cwd:s,config:c}=i,u=o(c,s),d;try{d=l({projectDir:s,contentDir:u,includePatterns:c.content.include,excludePatterns:c.content.exclude})}catch(e){return{ok:!1,error:`Cannot evaluate content filter: ${e instanceof Error?e.message:String(e)}`}}if(![`${r}.md`,`${r}.mdx`].some(e=>!d.isExcluded(e)))return{ok:!1,error:`Error: docName "${r}" is not inside content.include globs (${c.content.include.join(`, `)}). This tool only returns URLs for docs that match those globs.`};let f=U(r,{config:c,lockDir:a(u),contentDir:u});return f?{ok:!0,result:{previewUrl:f.url,previewUrlSource:f.source},text:`Preview URL for "${r}" (source: ${f.source}):\n${f.url}`}:{ok:!0,result:{previewUrl:null},text:`No preview URL resolvable for "${r}". The server is likely not running yet. Start it with \`open-knowledge start\` (or \`preview_start\`), then **call \`get_preview_url\` again** — the server writes a lock file that this tool reads to resolve the URL. NEVER guess or manually construct the preview URL. Alternatively, set \`OPEN_KNOWLEDGE_PREVIEW_BASE_URL\` or add \`preview.baseUrl\` to .open-knowledge/config.yml.`}}function Lr(e,t){e.tool(`get_preview_url`,Fr,{docName:A.string().min(1),cwd:A.string().optional().describe(M)},async e=>{let n=await Ir(e,t);return n.ok?P(n.text,n.result):N(n.error,!0)})}function Rr(e,t){return`Capture this external source into the project knowledge base as raw reference material. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
|
|
176
176
|
|
|
177
177
|
Source: ${e}
|
|
178
178
|
|
|
@@ -593,6 +593,6 @@ Folder metadata lives in \`config.yml\`, **not** in content files — this is in
|
|
|
593
593
|
${Object.entries(xi).map(([e,t])=>`### \`${e}\`\n${t}`).join(`
|
|
594
594
|
|
|
595
595
|
`)}
|
|
596
|
-
`}async function Oi(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function ki(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=St(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await Oi(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Ae({name:t,version:e},{instructions:Di(o,{dynamicConfig:typeof a==`function`&&!s})}),l=Ti({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=Ei({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Me,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=be(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},Si(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new je;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-UJIeMtkM.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function Ai(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function ji(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Mi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??Se,a=e.readErrorLog??(e=>E(e)?O(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>te(e,`w`)),s=e.closeFd??(e=>T(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=ji({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};E(e.lockDir)||D(e.lockDir,{recursive:!0});let d=fe(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=S();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),ee=(c/1e3).toFixed(c%1e3==0?0:2),b=p?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${ee}s.${x}${y?` stderr:\n${y}`:``}`)}function Ni(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Mi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function Pi(e){return new C(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=b({startupCwd:r,startupConfig:n}),a=Ai(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Ni({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await ki({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fi(e){return new C(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-
|
|
597
|
-
`)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Li(e){return new C(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Ri(e){return new C(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 zi(e){return new C(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Bi(e,t){return{server:Vi(`server`,e),ui:Vi(`ui`,t)}}function Vi(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Hi(e){return`${Ui(e.server)}\n${Ui(e.ui)}`}function Ui(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Wi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Hi(r)),r}function Gi(e){return new C(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{Wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ki(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function qi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ki(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Ji(e){return new C(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{qi({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Yi=1e4,Xi=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Zi(e){let t=e.upstreamTimeoutMs??Yi,n=De((n,r)=>{$i(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())})}}function Qi(e,t,n){$i(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Yi)}function $i(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Xi)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Oe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Xi)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.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function ea(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ta(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:i}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-DB3pnkMU.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-OkgDVC2Q.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[i(m,`public`),i(m,`../../app/dist`),i(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});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/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Qi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):na(t)});return}if(g){g(e,t);return}na(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(ee);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let C=S;v=C,c(p,C);let w=e.scheduler??r,T=e.safetyNetMs??432e5,E=null,D=!1,te=!1,O=()=>{D||(D=!0,E!==null&&(w.clearTimeout(E),E=null))},ne=()=>{if(O(),!te){te=!0;try{s(p)}catch{}}},re=()=>{D||T<=0||(E!==null&&(w.clearTimeout(E),E=null),E=w.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}ne()},T))},ie=()=>{D||T<=0||re()};return y=ie,re(),{httpServers:x,port:C,release:ne,detachSafetyNet:O,nudgeSafetyNet:ie}}function na(e){e.writeHead(404),e.end(`Not found`)}function ra(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 t}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 e}return 0}async function ia(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-DB3pnkMU.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 Zi({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function aa(e){return new C(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). 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-xJqYhQcY.mjs`),{UiLockCollisionError:r}=await import(`./src-DB3pnkMU.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-OkgDVC2Q.mjs`),o=e(),s=t.host,c;try{c=ra(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ta({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;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)}};ea(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=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await ia({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new C;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ee(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const oa=x(()=>$);Q.addCommand(oa,{isDefault:!0});const sa=Pi(()=>$);Q.addCommand(sa),Q.addCommand(v());const ca=Fi(()=>$);Q.addCommand(ca);const la=aa(()=>$);Q.addCommand(la),Q.addCommand(Ji(()=>$)),Q.addCommand(ut(()=>$)),Q.addCommand(Gi(()=>$)),Q.addCommand(ot(()=>$)),Q.addCommand(yt(()=>$)),Q.addCommand(Li(()=>$)),Q.addCommand(zi(()=>$)),Q.addCommand(Ri(()=>$)),await Q.parseAsync();export{};
|
|
596
|
+
`}async function Oi(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function ki(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=St(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await Oi(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Ae({name:t,version:e},{instructions:Di(o,{dynamicConfig:typeof a==`function`&&!s})}),l=Ti({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=Ei({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Me,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=be(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},Si(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new je;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-UJIeMtkM.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function Ai(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function ji(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function Mi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??Se,a=e.readErrorLog??(e=>E(e)?O(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>te(e,`w`)),s=e.closeFd??(e=>T(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=ji({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};E(e.lockDir)||D(e.lockDir,{recursive:!0});let d=fe(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=S();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),ee=(c/1e3).toFixed(c%1e3==0?0:2),b=p?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${ee}s.${x}${y?` stderr:\n${y}`:``}`)}function Ni(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??Mi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function Pi(e){return new C(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=b({startupCwd:r,startupConfig:n}),a=Ai(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=Ni({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await ki({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fi(e){return new C(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CULBnUoI.mjs`),r=e(),i=process.cwd(),a=o(r,i),s;try{s=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(s,i)}\n`),s.totalCount===0&&s.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ii(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(a(o(t,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.error??`Server responded with ${n.status}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let s=Ce({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await s.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await s.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
597
|
+
`)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Li(e){return new C(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Ri(e){return new C(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 zi(e){return new C(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Ii({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 Bi(e,t){return{server:Vi(`server`,e),ui:Vi(`ui`,t)}}function Vi(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Hi(e){return`${Ui(e.server)}\n${Ui(e.ui)}`}function Ui(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Wi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Hi(r)),r}function Gi(e){return new C(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{Wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ki(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function qi(e){let t=e.inspect??(t=>st(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ki(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Ji(e){return new C(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{qi({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Yi=1e4,Xi=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Zi(e){let t=e.upstreamTimeoutMs??Yi,n=De((n,r)=>{$i(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())})}}function Qi(e,t,n){$i(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Yi)}function $i(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Xi)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Oe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Xi)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.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function ea(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ta(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:i}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-DHnGx64r.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-BhmQnYL9.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[i(m,`public`),i(m,`../../app/dist`),i(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});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/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Qi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):na(t)});return}if(g){g(e,t);return}na(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(ee);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let C=S;v=C,c(p,C);let w=e.scheduler??r,T=e.safetyNetMs??432e5,E=null,D=!1,te=!1,O=()=>{D||(D=!0,E!==null&&(w.clearTimeout(E),E=null))},ne=()=>{if(O(),!te){te=!0;try{s(p)}catch{}}},re=()=>{D||T<=0||(E!==null&&(w.clearTimeout(E),E=null),E=w.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}ne()},T))},ie=()=>{D||T<=0||re()};return y=ie,re(),{httpServers:x,port:C,release:ne,detachSafetyNet:O,nudgeSafetyNet:ie}}function na(e){e.writeHead(404),e.end(`Not found`)}function ra(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 t}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 e}return 0}async function ia(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-DHnGx64r.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 Zi({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function aa(e){return new C(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). 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-xJqYhQcY.mjs`),{UiLockCollisionError:r}=await import(`./src-DHnGx64r.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-BhmQnYL9.mjs`),o=e(),s=t.host,c;try{c=ra(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ta({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;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)}};ea(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=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await ia({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new C;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ee(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const oa=x(()=>$);Q.addCommand(oa,{isDefault:!0});const sa=Pi(()=>$);Q.addCommand(sa),Q.addCommand(v());const ca=Fi(()=>$);Q.addCommand(ca);const la=aa(()=>$);Q.addCommand(la),Q.addCommand(Ji(()=>$)),Q.addCommand(ut(()=>$)),Q.addCommand(Gi(()=>$)),Q.addCommand(ot(()=>$)),Q.addCommand(yt(()=>$)),Q.addCommand(Li(()=>$)),Q.addCommand(zi(()=>$)),Q.addCommand(Ri(()=>$)),await Q.parseAsync();export{};
|
|
598
598
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,i as t,l as n,o as r,s as i,t as a}from"./init-
|
|
1
|
+
import{c as e,i as t,l as n,o as r,s as i,t as a}from"./init-DysAQtCG.mjs";import{n as o,r as s}from"./loader-DfTFnc2z.mjs";import"./src-CBVTx8JJ.mjs";export{e as ALL_EDITOR_IDS,s as ConfigSchema,n as EDITOR_TARGETS,a as detectInstalledEditors,o as loadConfig,t as readExistingMcpEntry,r as writeEditorMcpConfig,i as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-CODC0Drd.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./constants-
|
|
1
|
+
import{n as e,r as t,t as n}from"./constants-DA7Qh-Kl.mjs";import{O as r}from"./src-CQw-HNNM.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${r}/ — Open Knowledge config
|
|
2
2
|
|
|
3
3
|
This directory holds Open Knowledge's configuration for this project. It's **not** where content lives — content lives wherever \`content.dir\` + \`content.include\` in \`config.yml\` point. The default is the repo root with \`**/*.md\`, so any markdown file in the project is fair game. Inspect \`config.yml\` for the actual setting.
|
|
4
4
|
|
|
@@ -227,4 +227,4 @@ ${f}`;function v(e,t,r){let a=[n,...r??[]],u=new Set,d=[];for(let n of a){let r=
|
|
|
227
227
|
|
|
228
228
|
`)?`
|
|
229
229
|
`:``}${n}`,`utf-8`),`appended`)}const x=[{name:n,content:m},{name:`.gitignore`,content:`${e}/\nserver.lock\nui.lock\nsync-state.json\n`},{name:t,content:h}];function S(t){let n=u(t,r),i=[],o=[];a(n,{recursive:!0}),a(l(n,e),{recursive:!0});for(let e of x)y(l(n,e.name),e.content)?i.push(e.name):o.push(e.name);return{created:i,skipped:o}}export{b as a,g as i,d as n,S as o,f as r,v as s,_ as t};
|
|
230
|
-
//# sourceMappingURL=init-
|
|
230
|
+
//# sourceMappingURL=init-CODC0Drd.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-DysAQtCG.mjs";export{o as detectInstalledEditors,n as formatInitResult,i as initCommand,t as readExistingMcpEntry,e as runInit,r as writeEditorMcpConfig,a as writeUserMcpConfigs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{i as e}from"./constants-
|
|
1
|
+
import{i as e}from"./constants-DA7Qh-Kl.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{n,t as r}from"./src-rqPIkHTi.mjs";import{o as i,s as a}from"./init-CODC0Drd.mjs";import{t as o}from"./preview-jDZwLSul.mjs";import{t as s}from"./is-object-DaHwJLOe.mjs";import{Command as c}from"commander";import{existsSync as l,mkdirSync as u,readFileSync as d,writeFileSync as f}from"node:fs";import{homedir as p}from"node:os";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as x,win32 as S}from"node:path";import{parse as C,stringify as w}from"smol-toml";const T=[`claude`,`claude-desktop`,`cursor`,`vscode`,`windsurf`,`codex`],ee=[`@inkeep/open-knowledge`,`mcp`],te={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function E(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=b(e);if(m(t)===`cli.mjs`&&m(h(t))===`dist`)return t;let n=t.split(x),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 _(i.length===0?x:i.join(x),`packages`,`cli`,`dist`,`cli.mjs`)}function D(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[E(e.cliEntryPath),`mcp`],env:{...te}}:{command:`npx`,args:[...ee]}}function O(e){return e===`win32`?S:v}function k(e={}){let t=e.platformName??process.platform,n=e.home??p(),r=e.env??process.env,i=O(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function A(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.claude.json`)}function j(e={}){let t=e.platformName??process.platform,n=e.home??p(),r=e.env??process.env;if(t===`darwin`)return v.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??S.join(n,`AppData`,`Roaming`);return S.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function M(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.cursor`,`mcp.json`)}function N(e={}){return O(e.platformName??process.platform).join(k(e),`Code`,`User`,`mcp.json`)}function P(e={}){let t=e.platformName??process.platform,n=e.home??p();return O(t).join(n,`.codeium`,`windsurf`,`mcp_config.json`)}function F(e={}){let t=e.platformName??process.platform,n=e.home??p();return(e.env??process.env).CODEX_HOME??O(t).join(n,`.codex`)}function I(e={}){return O(e.platformName??process.platform).join(F(e),`config.toml`)}function L(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>L(e,t[n]));if(s(e)&&s(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=>L(e[n],t[n]))}return!1}function R(e,t){return Object.entries(t).every(([t,n])=>L(e[t],n))}function z(e,t){return{...e,...t}}function B(e){return{...e,isCompatible(t,n,r){return R(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return z(t,e.buildEntry(n,r))}}}const V={claude:B({id:`claude`,label:`Claude Code`,configPath:(e,t)=>A({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>_(t??p(),`.claude`),legacyProjectConfigPath:e=>_(e,`.mcp.json`),instructionsPath:e=>_(e,`CLAUDE.md`)}),"claude-desktop":B({id:`claude-desktop`,label:`Claude Desktop`,configPath:(e,t)=>j({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(j({home:t}))}),cursor:B({id:`cursor`,label:`Cursor`,configPath:(e,t)=>M({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(M({home:t})),legacyProjectConfigPath:e=>_(e,`.cursor`,`mcp.json`)}),vscode:B({id:`vscode`,label:`VS Code`,configPath:(e,t)=>N({home:t}),format:`json`,topLevelKey:`servers`,serverName:()=>e,buildEntry:(e,t)=>({type:`stdio`,...D(t)}),scope:`global`,detectPath:(e,t)=>h(N({home:t})),legacyProjectConfigPath:e=>_(e,`.vscode`,`mcp.json`)}),windsurf:B({id:`windsurf`,label:`Windsurf`,configPath:(e,t)=>P({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(P({home:t}))}),codex:B({id:`codex`,label:`Codex`,configPath:(e,t)=>I({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>h(I({home:t})),legacyProjectConfigPath:e=>_(e,`.codex`,`config.toml`)})};function H(e){let t=e.filter(e=>!(e in V));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${T.join(`, `)}`);return e.map(e=>V[e])}function U(e){if(!l(e))return{};let t=d(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(s(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 W(e){if(!l(e))return{};let t=d(e,`utf-8`).trim();if(t===``)return{};try{let n=C(t);if(s(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 G(e,t){u(h(e),{recursive:!0}),f(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function K(e,t){u(h(e),{recursive:!0});let n=w(t);f(e,n.endsWith(`
|
|
2
2
|
`)?n:`${n}\n`,`utf-8`)}const q=`0.0.1`,J=`open-knowledge-ui`;function ne(e,t={}){let n=_(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:J,runtimeExecutable:`node`,runtimeArgs:[E(t.cliEntryPath),`ui`],port:3e3}:{name:J,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!l(n))return u(h(n),{recursive:!0}),f(n,`${JSON.stringify({version:q,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let e=d(n,`utf-8`).trim(),t=e?JSON.parse(e):{};if(!s(t))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let i=Array.isArray(t.configurations)?t.configurations:[],a=i.findIndex(e=>s(e)&&e.name===J);a>=0?i[a]=r:i.push(r);let o={...t,version:t.version??q,configurations:i};return f(n,`${JSON.stringify(o,null,2)}\n`,`utf-8`),{action:a>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Y(e,t,n){try{return l(e.detectPath?.(t,n)??h(e.configPath(t,n)))}catch{return!1}}function X(e,t,n,r){let i=e.serverName(t),a;try{a=e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:i,error:t instanceof Error?t.message:String(t)}}if(!n.skipAvailabilityCheck&&!Y(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:a,serverName:i};let o;try{o=e.format===`toml`?W(a):U(a)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}let s=o[e.topLevelKey]??{},c=s[i],l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}let u={...o,[e.topLevelKey]:{...s,[i]:l}};try{e.format===`toml`?K(a,u):G(a,u)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:a,serverName:i,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:c===void 0?`written`:`overwritten`,configPath:a,serverName:i}}function re(e,t){let n=e.legacyProjectConfigPath?.(t);if(!(!n||!l(n)))return{editorId:e.id,label:e.label,path:n}}async function ie(e){let t=H(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>X(t,``,n,e.home))}function ae(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?W(r):U(r)}catch{return null}let a=i[e.topLevelKey];if(!s(a))return null;let o=a[e.serverName(t)];return s(o)?o:null}async function Z(e={}){let t=b(e.cwd??process.cwd()),r={mode:e.devMcp?`dev`:`published`,cliEntryPath:e.cliEntryPath},o=await n(t),s;try{s=i(t)}catch(n){let r=V.claude.configPath(t,e.home);return{contentCreated:[],contentSkipped:[],editors:[],legacyProjectConfigs:[],rootInstructions:[],didGitInit:o.didInit,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let c=H(e.editors??$(t,e.home)),l=c.filter(n=>Y(n,t,e.home)),u=[];for(let n of c){if(e.mcp===!1){let r=``;try{r=n.configPath(t,e.home)}catch{}u.push({editorId:n.id,label:n.label,action:`skipped-flag`,configPath:r,serverName:n.serverName(t)});continue}u.push(X(n,t,r,e.home))}let d=e.mcp===!1?[]:l.map(e=>re(e,t)).filter(e=>e!==void 0),f=l.some(e=>e.id===`claude`)&&e.mcp!==!1?ne(t,r):void 0,p=l.map(e=>e.instructionsPath?.(t)).filter(e=>e!==void 0).map(e=>g(e)?y(t,e):e),m=e.rootInstructions===!1?[]:a(t,!0,p),h=e.mcp===!1?`skipped-flag`:`skipped-missing`,_=u.find(e=>e.editorId===`claude`)??u[0]??{action:h,configPath:V.claude.configPath(t,e.home)};return{contentCreated:s.created,contentSkipped:s.skipped,editors:u,legacyProjectConfigs:d,rootInstructions:m,launchJson:f,didGitInit:o.didInit,mcpAction:_.action,mcpPath:_.configPath,mcpError:`error`in _?_.error:void 0}}function Q(e,n){let r=[],i=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),a=e.editors.some(e=>e.action===`failed`),s=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),c=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),l=e=>{let t=e.configPath.startsWith(n)?y(n,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${t} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${t} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${t} FAILED: ${e.error}`}};e.didGitInit&&r.push(`Initialized git repo at ${n}/.git/ (default branch: main)`);let u=_(n,t);if(e.contentCreated.length>0?(r.push(`Content scaffolded at ${u}/`),r.push(` Created: ${e.contentCreated.join(`, `)}`)):r.push(`Content already present at ${u}/`),e.contentSkipped.length>0&&r.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),r.push(``),e.mcpError&&e.editors.length===0)r.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)r.push(`MCP server configuration:`),r.push(e.mcpAction===`skipped-flag`?` MCP config not written — use without --no-mcp to configure editors`:` No supported editor config directories detected; skipped MCP registration`);else if(s)r.push(`MCP config not written — use without --no-mcp to configure editors`);else if(c)r.push(`MCP server configuration:`),r.push(` No supported editor config directories detected; skipped MCP registration`);else{r.push(`MCP server configuration:`);for(let t of e.editors){let i=t.configPath.startsWith(n)?y(n,t.configPath):t.configPath.replace(/^\/Users\/[^/]+/,`~`),a=t.serverName===`open-knowledge`?``:` (${t.serverName})`,o=` `.repeat(Math.max(1,14-t.label.length)),s=t.editorId===`claude-desktop`&&(t.action===`written`||t.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(t.action){case`written`:r.push(` ${t.label}${o}${i} registered${a}${s}`);break;case`overwritten`:r.push(` ${t.label}${o}${i} updated${a}${s}`);break;case`skipped-missing`:r.push(` ${t.label}${o}${i} config root missing; skipped`);break;case`failed`:r.push(` ${t.label}${o}${i} FAILED: ${t.error}`);break;case`skipped-flag`:break}t.editorId===`claude`&&e.launchJson&&r.push(l(e.launchJson))}}if(a&&(r.push(``),r.push(`For failed editors, add the MCP server entry manually. See:`),r.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){r.push(``),r.push(`Legacy project MCP configs detected:`);for(let t of e.legacyProjectConfigs)r.push(` ${t.label} ${y(n,t.path)}`);r.push(` These project-local files may override the new global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.rootInstructions.length>0){let t=e.rootInstructions.filter(e=>e.action!==`skipped-symlink`);if(t.length>0){r.push(``),r.push(`Root instructions:`);for(let e of t){let t=e.path.startsWith(n)?y(n,e.path):e.path,i=` `.repeat(Math.max(1,14-e.file.length));switch(e.action){case`created`:r.push(` ${e.file}${i}${t} created`);break;case`appended`:r.push(` ${e.file}${i}${t} appended Open Knowledge section`);break;case`replaced`:r.push(` ${e.file}${i}${t} replaced Open Knowledge section`);break;case`skipped-existing`:r.push(` ${e.file}${i}${t} already has Open Knowledge section`);break}}}}if(e.preview?(r.push(``),r.push(o(e.preview,n))):e.previewWarning&&(r.push(``),r.push(`Content preview unavailable: ${e.previewWarning}`)),i){let t=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.label);r.push(``),r.push(`Next steps:`),r.push(` 1. Open your editor (${t.join(` / `)})`),r.push(` 2. Approve the MCP server when prompted`),r.push(` 3. The knowledge base is ready — use the three workflow tools:`),r.push(` - mcp__open-knowledge__init-content — bootstrap articles from the codebase`),r.push(` - mcp__open-knowledge__ingest — capture an external source`),r.push(` - mcp__open-knowledge__research — gather sources and write findings`)}return r.join(`
|
|
3
3
|
`)}function $(e,t){let n=[];for(let r of T)Y(V[r],e,t)&&n.push(r);return n}function oe(){return new c(`init`).description(`Scaffold ${t}/ 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 ${t}/ 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`).action(async e=>{let t=process.cwd(),n;try{n=await Z({cwd:t,mcp:e.mcp,devMcp:e.devMcp})}catch(e){if(e instanceof r){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
4
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
5
|
-
//# sourceMappingURL=init-
|
|
4
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-CULBnUoI.mjs`),{loadConfig:r}=await import(`./loader-89zKhhvs.mjs`),{resolveContentDir:i}=await import(`./paths-BhmQnYL9.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o,include:a.content.include,exclude:a.content.exclude})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Q(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Z as a,T as c,ae as i,V as l,Q as n,X as o,oe as r,ie as s,$ as t};
|
|
5
|
+
//# sourceMappingURL=init-DysAQtCG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-DfTFnc2z.mjs";export{e as loadConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./constants-
|
|
1
|
+
import{r as e}from"./constants-DA7Qh-Kl.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{t as n}from"./is-object-DaHwJLOe.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{realpath as c}from"node:fs/promises";import{z as l}from"zod";async function u(e){let t=o(e);try{return await c(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}}const d=l.object({title:l.string().optional(),description:l.string().optional(),tags:l.array(l.string()).optional()}).strict(),f=l.object({match:l.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:d}).strict(),p=l.object({content:l.object({dir:l.string().default(`.`),include:l.array(l.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:l.array(l.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:l.object({oauthAppClientId:l.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:l.object({enabled:l.boolean().optional(),pushIntervalSeconds:l.number().int().min(1).default(60),pullIntervalSeconds:l.number().int().min(1).default(30),autoCommit:l.boolean().default(!0),autoPush:l.boolean().default(!0),autoPull:l.boolean().default(!0),commitMessage:l.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:l.object({port:l.number().int().min(0).max(65535).default(0),host:l.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:l.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:l.object({debounceMs:l.number().int().min(0).default(2e3),maxDebounceMs:l.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:l.object({baseUrl:l.url().optional()}).default({}),folders:l.array(f).default([]),mcp:l.object({autoStart:l.boolean().default(!0),tools:l.object({read_document:l.object({historyDepth:l.number().int().min(0).default(5)}).default({historyDepth:5}),search:l.object({maxResults:l.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function m(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=m(a,o):o!==void 0&&(r[i]=o)}return r}function h(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function g(n){let r=n??process.cwd(),i=[],s=o(a(),t,e),c={},l=h(s);l&&(c=m(c,l),i.push(s));let u=o(r,t,e),d=h(u);d&&(c=m(c,d),i.push(u));let f=p.safeParse(c);if(!f.success){let e=f.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
|
|
2
2
|
`)}`)}return{config:f.data,sources:i}}function _(e,t=process.env){let n=e;return t.PORT&&(n={...n,server:{...n.server,port:Number(t.PORT)}}),t.HOST&&(n={...n,server:{...n.server,host:t.HOST}}),n}function v(e){let t=e.env??process.env,n=e.cacheMs??1e3,r=e.loadConfigFn??g,i=new Map,a=new Map,o=u(e.startupCwd);return async s=>{let c=await u(s??e.startupCwd),l=Date.now(),d=i.get(c);if(d&&d.expiresAt>l)return d.config;let f=a.get(c);if(f)return await f;let p=(async()=>{if(c===await o){let r=_(e.startupConfig,t);return i.set(c,{config:r,expiresAt:Date.now()+n}),r}let a=_(r(c).config,t);return i.set(c,{config:a,expiresAt:Date.now()+n}),a})();a.set(c,p);try{return await p}finally{a.delete(c)}}}export{u as i,g as n,p as r,v as t};
|
|
3
|
-
//# sourceMappingURL=loader-
|
|
3
|
+
//# sourceMappingURL=loader-DfTFnc2z.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./constants-
|
|
2
|
-
//# sourceMappingURL=paths-
|
|
1
|
+
import"./constants-DA7Qh-Kl.mjs";import{O as e}from"./src-CQw-HNNM.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
|
|
2
|
+
//# sourceMappingURL=paths-B9hXoumv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./paths-B9hXoumv.mjs";export{t as resolveContentDir,e as resolveLockDir};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-jDZwLSul.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import"./constants-
|
|
1
|
+
import"./constants-DA7Qh-Kl.mjs";import{O as e}from"./src-CQw-HNNM.mjs";import{m as t}from"./src-rqPIkHTi.mjs";import{existsSync as n,lstatSync as r,readdirSync as i,realpathSync as a,statSync as o}from"node:fs";import{join as s,relative as c}from"node:path";function l(e){let{projectDir:n,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{r(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:n,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=i(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${c(l,e)||`.`}: ${n}`);return}for(let n of t){let t=s(e,n.name);if(n.isSymbolicLink()){let e;try{e=a(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${c(l,t)}`):p.push(`cannot resolve symlink ${c(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=o(e)}catch{continue}if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,r){let i=[],a=c(r,t.contentDir),o=a===``?`./`:`./${a}`;i.push(`Content:`),i.push(` Found ${t.totalCount} markdown files in ${o}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(i.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;i.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)i.push(` Warning: ${e}`);return i.push(``),n(s(r,`.open-knowledge`,`config.yml`))?(i.push(` To adjust, edit ${e}/config.yml:`),i.push(` content:`),i.push(` include: ${JSON.stringify(t.include)}`),i.push(` exclude: ${JSON.stringify(t.exclude)}`)):(i.push(" Run `open-knowledge init` to scaffold config, then adjust:"),i.push(` ${e}/config.yml → content.include / content.exclude`)),i.push(``),i.push(` Re-check anytime: open-knowledge preview`),i.join(`
|
|
2
2
|
`)}export{l as n,u as t};
|
|
3
|
-
//# sourceMappingURL=preview-
|
|
3
|
+
//# sourceMappingURL=preview-jDZwLSul.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{closeSync as e,existsSync as t,mkdirSync as n,openSync as r,readFileSync as i,unlinkSync as a,writeFileSync as o,writeSync as s}from"node:fs";import{hostname as c}from"node:os";import{resolve as l}from"node:path";function u(e){try{return process.kill(e,0),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`)}}var d=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`Open Knowledge ${n} already running on port ${e.port} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function f(e,t){return l(e,`${t}.lock`)}const p=new Map;function m(e){p.set(e,(p.get(e)??0)+1)}function h(e){let t=p.get(e);return t===void 0||t<=1?(p.delete(e),!0):(p.set(e,t-1),!1)}function g(e,t){try{let n=JSON.parse(i(e,`utf-8`));return n&&typeof n==`object`&&typeof n.pid==`number`?n:(console.warn(`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return console.warn(`${t} Corrupt lock file at ${e} — replacing`),null}}function _(i){let{lockName:l,lockDir:p,metadata:h}=i,_=`[${l}-lock]`;n(p,{recursive:!0});let y=f(p,l),b={pid:process.pid,hostname:c(),port:h.port,startedAt:new Date().toISOString(),worktreeRoot:h.worktreeRoot},x=JSON.stringify(b,null,2);for(let n=0;n<3;n++){if(!t(y))try{let t=r(y,`wx`,384);try{s(t,x)}finally{e(t)}return m(y),v({lockName:l,lockDir:p,lockPath:y})}catch(e){if(e.code!==`EEXIST`)throw e}let n=g(y,_);if(n){let e=n.hostname===c();if(e&&n.pid===process.pid)return o(y,x,{encoding:`utf-8`,mode:384}),m(y),v({lockName:l,lockDir:p,lockPath:y});if(e&&u(n.pid))throw new d(n,y,l);console.warn(`${_} Stale lock detected (pid=${n.pid}, host=${n.hostname}) — replacing`)}try{a(y)}catch{}}throw Error(`${_} Failed to acquire ${y} after 3 attempts (concurrent acquire contention).`)}function v(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>x({lockName:t,lockDir:n}),updatePort:e=>y({lockName:t,lockDir:n,port:e})}}function y(e){let{lockName:n,lockDir:r,port:a}=e,s=`[${n}-lock]`,l=f(r,n);if(!t(l)){console.warn(`${s} Lock file missing at ${l} during port update — skipping`);return}let u;try{let e=JSON.parse(i(l,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`){console.warn(`${s} Corrupt lock at ${l} during port update — skipping`);return}u=e}catch{console.warn(`${s} Unreadable lock at ${l} during port update — skipping`);return}if(u.pid===process.pid&&!(typeof u.hostname==`string`&&u.hostname!==c())){u.port=a;try{o(l,JSON.stringify(u,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${s} Failed to update port in ${l}: ${e instanceof Error?e.message:String(e)}`)}}}function b(e){let{lockName:n,lockDir:r}=e,o=f(r,n);if(!t(o))return null;let s;try{let e=JSON.parse(i(o,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`)return null;s=e}catch{return null}if(s.hostname!==c())return null;if(!u(s.pid)){try{a(o)}catch{}return null}return s}function x(e){let{lockName:n,lockDir:r}=e,o=`[${n}-lock]`,s=f(r,n);if(h(s)&&t(s))try{let e=JSON.parse(i(s,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||typeof e.hostname==`string`&&e.hostname!==c())return;a(s)}catch(e){console.warn(`${o} Failed to release ${s}: ${e instanceof Error?e.message:String(e)}`)}}var S=class extends d{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function C(e,t){try{return _({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof d&&e.lockName===`server`?new S(e.existing,e.lockPath):e}}function w(e,t){y({lockName:`server`,lockDir:e,port:t})}function T(e){return b({lockName:`server`,lockDir:e})}function E(e){x({lockName:`server`,lockDir:e})}export{w as a,f as c,y as d,u as f,E as i,b as l,C as n,d as o,T as r,_ as s,S as t,x as u};
|
|
2
|
+
//# sourceMappingURL=server-lock-BI-SqMWk.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e}from"./server-lock-BI-SqMWk.mjs";export{e as updateServerLockPort};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./init-DysAQtCG.mjs";import"./loader-DfTFnc2z.mjs";export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./src-CQw-HNNM.mjs";import{Tt as e,et as t,it as n,n as r,nt as i,r as a,rt as o,t as s,tt as c}from"./src-rqPIkHTi.mjs";import{f as l,r as u}from"./server-lock-BI-SqMWk.mjs";export{s as ProjectGitInitError,t as UiLockCollisionError,c as acquireUiLock,a as bootServer,r as ensureProjectGit,e as getLogger,l as isProcessAlive,u as readServerLock,i as readUiLock,o as releaseUiLock,n as updateUiLockPort};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{A as r,C as i,D as a,E as o,M as s,O as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,h as v,i as y,j as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k,v as A,w as j,x as M,y as N}from"./src-CQw-HNNM.mjs";import{d as P,f as ee,i as te,l as ne,n as re,o as F,r as ie,s as ae,u as I}from"./server-lock-
|
|
1
|
+
import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{A as r,C as i,D as a,E as o,M as s,O as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,h as v,i as y,j as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k,v as A,w as j,x as M,y as N}from"./src-CQw-HNNM.mjs";import{d as P,f as ee,i as te,l as ne,n as re,o as F,r as ie,s as ae,u as I}from"./server-lock-BI-SqMWk.mjs";import{n as oe,t as L}from"./git-handle-C_GYoScT.mjs";import{createRequire as se}from"node:module";import{closeSync as ce,existsSync as R,lstatSync as le,mkdirSync as ue,openSync as de,readFileSync as z,readdirSync as fe,realpathSync as pe,renameSync as me,rmSync as he,statSync as ge,unlinkSync as _e,writeFileSync as B,writeSync as ve}from"node:fs";import{homedir as ye,hostname as be,tmpdir as xe}from"node:os";import{dirname as Se,extname as Ce,join as V,posix as we,relative as Te,resolve as H,sep as Ee}from"node:path";import{URLSearchParams as De}from"node:url";import Oe,{createHash as ke,randomUUID as Ae,webcrypto as je}from"node:crypto";import{execFile as Me,spawn as Ne,spawnSync as Pe}from"node:child_process";import Fe from"simple-git";import{mkdir as Ie,readFile as Le,realpath as Re,rename as ze,writeFile as Be}from"node:fs/promises";import"node:http";import Ve from"picomatch";import{promisify as He}from"node:util";var Ue=n(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
|
|
2
2
|
causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
3
3
|
caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),We=n(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),Ge=n(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Ue(),{pinoErrProto:a,pinoErrorSymbols:o}=We(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),Ke=n(((e,t)=>{t.exports=s;let{isErrorLike:n}=Ue(),{pinoErrProto:r,pinoErrorSymbols:i}=We(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),qe=n(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),Je=n(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),Ye=n(((e,t)=>{let n=Ge(),r=Ke(),i=qe(),a=Je();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Xe=n(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Ze=n(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Qe=n(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),$e=n(((e,t)=>{let n=Ze(),{redactFmtSym:r,wildcardFirstSym:i}=Qe(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),et=n(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),tt=n(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),nt=n(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),rt=n(((e,n)=>{let r=t(`fs`),i=t(`events`),a=t(`util`).inherits,o=t(`path`),s=nt(),c=t(`assert`),l=Buffer.allocUnsafe(0),u=`buffer`,d=`utf8`,[f,p]=(process.versions.node||`0.0`).split(`.`).map(Number),m=f>=22&&p>=7;function h(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function n(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,a=t.mode;if(t.sync)try{t.mkdir&&r.mkdirSync(o.dirname(e),{recursive:!0}),n(null,r.openSync(e,i,a))}catch(e){throw n(e),e}else t.mkdir?r.mkdir(o.dirname(e),{recursive:!0},t=>{if(t)return n(t);r.open(e,i,a,n)}):r.open(e,i,a,n)}function g(e){if(!(this instanceof g))return new g(e);let{fd:t,dest:n,minLength:i,maxLength:a,maxWrite:o,periodicFlush:c,sync:f,append:p=!0,mkdir:m,retryEAGAIN:y,fsync:S,contentMode:A,mode:j}=e||{};t||=n,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=o||16384,this._periodicFlush=c||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=S||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=y||(()=>!0),this.mkdir=m||!1;let M,N;if(A===u)this._writingBuf=l,this.write=x,this.flush=w,this.flushSync=E,this._actualWrite=O,M=()=>r.writeSync(this.fd,this._writingBuf),N=()=>r.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===d)this._writingBuf=``,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`),N=()=>Buffer.isBuffer(this._writingBuf)?r.write(this.fd,this._writingBuf,this.release):r.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${d}" and "${u}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)h(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{s(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(N,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let n=_(this._writingBuf,this._len,t);if(this._len=n.len,this._writingBuf=n.writingBuf,this._writingBuf.length){if(!this.sync){N();return}try{do{let e=M(),t=_(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&r.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,k(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(v,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function _(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function v(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}a(g,i);function y(e,t){return e.length===0?l:e.length===1?e[0]:Buffer.concat(e,t)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{r.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,n)},n=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,n)}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function w(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}g.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&r.close(t,e=>{if(e)return this.emit(`error`,e)})}),h(this.file,this)},g.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():k(this)))};function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?r.writeSync(this.fd,e):r.writeSync(this.fd,e,`utf8`),n=_(e,this._len,t);e=n.writingBuf,this._len=n.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}try{r.fsyncSync(this.fd)}catch{}}function E(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=l);let e=l;for(;this._bufs.length||e.length;){e.length<=0&&(e=y(this._bufs[0],this._lens[0]));try{let t=r.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}}g.prototype.destroy=function(){this.destroyed||k(this)};function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else r.write(this.fd,this._writingBuf,e)}function O(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:y(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,r.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else m&&(this._writingBuf=Buffer.from(this._writingBuf)),r.write(this.fd,this._writingBuf,e)}function k(e){if(e.fd===-1){e.once(`ready`,k.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],c(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{r.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?r.close(e.fd,n):n()}function n(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}g.SonicBoom=g,g.default=g,n.exports=g})),it=n(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),at=n(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),ot=n(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),st=n(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),ct=n(((e,n)=>{let{version:r}=at(),{EventEmitter:i}=t(`events`),{Worker:a}=t(`worker_threads`),{join:o}=t(`path`),{pathToFileURL:s}=t(`url`),{wait:c}=ot(),{WRITE_INDEX:l,READ_INDEX:u}=st(),d=t(`buffer`),f=t(`assert`),p=Symbol(`kImpl`),m=d.constants.MAX_STRING_LENGTH;var h=class{constructor(e){this._value=e}deref(){return this._value}},g=class{register(){}unregister(){}};let _=process.env.NODE_V8_COVERAGE?g:global.FinalizationRegistry||g,v=process.env.NODE_V8_COVERAGE?h:global.WeakRef||h,y=new _(e=>{e.exited||e.terminate()});function b(e,t){let{filename:n,workerData:i}=t,c=new a((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||o(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:n.indexOf(`file://`)===0?n:s(n).href,dataBuf:e[p].dataBuf,stateBuf:e[p].stateBuf,workerData:{$context:{threadStreamVersion:r},...i}}});return c.stream=new h(e),c.on(`message`,C),c.on(`exit`,w),y.register(e,c),c}function x(e){f(!e[p].sync),e[p].needDrain&&(e[p].needDrain=!1,e.emit(`drain`))}function S(e){let t=Atomics.load(e[p].state,l),n=e[p].data.length-t;if(n>0){if(e[p].buf.length===0){e[p].flushing=!1,e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e);return}let t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);r>e[p].data.length;)n/=2,t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))}})}else if(n===0){if(t===0&&e[p].buf.length===0)return;e.flush(()=>{Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u),S(e)})}else D(e,Error(`overwritten`))}function C(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new v(t),t.flush(()=>{t[p].ready=!0,t.emit(`ready`)});break;case`ERROR`:D(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:D(t,Error(`this should not happen: `+e.code))}}function w(e){let t=this.stream.deref();t!==void 0&&(y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,w),D(t,e===0?null:Error(`the worker thread exited`)))}var T=class extends i{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[p]={},this[p].stateBuf=new SharedArrayBuffer(128),this[p].state=new Int32Array(this[p].stateBuf),this[p].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[p].data=Buffer.from(this[p].dataBuf),this[p].sync=e.sync||!1,this[p].ending=!1,this[p].ended=!1,this[p].needDrain=!1,this[p].destroyed=!1,this[p].flushing=!1,this[p].ready=!1,this[p].finished=!1,this[p].errored=null,this[p].closed=!1,this[p].buf=``,this.worker=b(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[p].destroyed)return E(this,Error(`the worker has exited`)),!1;if(this[p].ending)return E(this,Error(`the worker is ending`)),!1;if(this[p].flushing&&this[p].buf.length+e.length>=m)try{A(this),this[p].flushing=!0}catch(e){return D(this,e),!1}if(this[p].buf+=e,this[p].sync)try{return A(this),!0}catch(e){return D(this,e),!1}return this[p].flushing||(this[p].flushing=!0,setImmediate(S,this)),this[p].needDrain=this[p].data.length-this[p].buf.length-Atomics.load(this[p].state,l)<=0,!this[p].needDrain}end(){this[p].destroyed||(this[p].ending=!0,k(this))}flush(e){if(this[p].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[p].state,l);c(this[p].state,u,t,1/0,(t,n)=>{if(t){D(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[p].destroyed||(A(this),j(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[p].ready}get destroyed(){return this[p].destroyed}get closed(){return this[p].closed}get writable(){return!this[p].destroyed&&!this[p].ending}get writableEnded(){return this[p].ending}get writableFinished(){return this[p].finished}get writableNeedDrain(){return this[p].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[p].errored}};function E(e,t){setImmediate(()=>{e.emit(`error`,t)})}function D(e,t){e[p].destroyed||(e[p].destroyed=!0,t&&(e[p].errored=t,E(e,t)),e.worker.exited?setImmediate(()=>{e[p].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[p].closed=!0,e.emit(`close`)}))}function O(e,t,n){let r=Atomics.load(e[p].state,l),i=Buffer.byteLength(t);return e[p].data.write(t,r),Atomics.store(e[p].state,l,r+i),Atomics.notify(e[p].state,l),n(),!0}function k(e){if(!(e[p].ended||!e[p].ending||e[p].flushing)){e[p].ended=!0;try{e.flushSync();let t=Atomics.load(e[p].state,u);Atomics.store(e[p].state,l,-1),Atomics.notify(e[p].state,l);let n=0;for(;t!==-1;){if(Atomics.wait(e[p].state,u,t,1e3),t=Atomics.load(e[p].state,u),t===-2){D(e,Error(`end() failed`));return}if(++n===10){D(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[p].finished=!0,e.emit(`finish`)})}catch(t){D(e,t)}}}function A(e){let t=()=>{e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e)};for(e[p].flushing=!1;e[p].buf.length!==0;){let n=Atomics.load(e[p].state,l),r=e[p].data.length-n;if(r===0){j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);continue}else if(r<0)throw Error(`overwritten`);let i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[p].buf=e[p].buf.slice(r),O(e,i,t);else{for(j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);a>e[p].buf.length;)r/=2,i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);e[p].buf=e[p].buf.slice(r),O(e,i,t)}}}function j(e){if(e[p].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[p].state,l),n=0;for(;;){let r=Atomics.load(e[p].state,u);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[p].state,u,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}n.exports=T})),lt=n(((e,n)=>{let{createRequire:r}=t(`module`),{existsSync:i}=t(`node:fs`),a=Xe(),{join:o,isAbsolute:s,sep:c}=t(`node:path`),{fileURLToPath:l}=t(`node:url`),u=nt(),d=it(),f=ct();function p(e){d.register(e,y),d.registerBeforeExit(e,b),e.on(`close`,function(){d.unregister(e)})}function m(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function h(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&g(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&g(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function g(e){let t=_(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=l(n)}catch{return!1}return s(n)&&!i(n)}function _(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function v(e,n,r,i,a){if(!r.execArgv&&m()&&t.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let e=h(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:e}})}r={...r,name:a};let o=new f({filename:e,workerData:n,workerOpts:r,sync:i});o.on(`ready`,s),o.on(`close`,function(){process.removeListener(`exit`,c)}),process.on(`exit`,c);function s(){process.removeListener(`exit`,c),o.unref(),r.autoEnd!==!1&&p(o)}function c(){o.closed||(o.flushSync(),u(100),o.end())}return o}function y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function b(e){e.flushSync()}function x(e){let{pipeline:t,targets:n,levels:i,dedupe:l,worker:u={},caller:d=a(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&n)throw Error(`only one of target or targets can be specified`);n?(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.targets=n.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=n.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),i&&(p.levels=i),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let _=n||t?`pino.transport`:g;return v(y(g),p,u,f,_);function y(e){if(e=h[e]||e,s(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return o(__dirname,`..`,`file.js`);let t;for(let n of m)try{t=r(n===`node:repl`?process.cwd()+c:n).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}n.exports=x})),ut=n(((e,n)=>{let r=t(`node:diagnostics_channel`),i=tt(),{mapHttpRequest:a,mapHttpResponse:o}=Ye(),s=rt(),c=it(),{lsCacheSym:l,chindingsSym:u,writeSym:d,serializersSym:f,formatOptsSym:p,endSym:m,stringifiersSym:h,stringifySym:g,stringifySafeSym:_,wildcardFirstSym:v,nestedKeySym:y,formattersSym:b,messageKeySym:x,errorKeySym:S,nestedKeyStrSym:C,msgPrefixSym:w}=Qe(),{isMainThread:T}=t(`worker_threads`),E=lt(),[D]=process.versions.node.split(`.`).map(e=>Number(e)),O=r.tracingChannel(`pino_asJson`),k=D>=25?e=>JSON.stringify(e):M;function A(){}function j(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let r=t;t!==null&&(t.method&&t.headers&&t.socket?t=a(t):typeof t.setHeader==`function`&&(t=o(t)));let s;r===null&&n.length===0?s=[null]:(r=n.shift(),s=n),typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](t,i(r,s,this[p]),e)}else{let r=t===void 0?n.shift():t;typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](null,i(r,n,this[p]),e)}}}function M(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function N(e,t,n,r){if(O.hasSubscribers===!1)return P.call(this,e,t,n,r);let i={instance:this,arguments};return O.traceSync(P,i,this,e,t,n,r)}function P(e,t,n,r){let i=this[g],a=this[_],o=this[h],s=this[m],c=this[u],d=this[f],p=this[b],w=this[x],T=this[S],E=this[l][n]+r;E+=c;let D;p.log&&(e=p.log(e));let O=o[v],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){d[t]?D=d[t](D):t===T&&d.err&&(D=d.err(D));let e=o[t]||O;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||k)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=k(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=d[w]?d[w](t):t;let e=o[w]||O;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||k)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[y]&&A?E+this[C]+A.slice(1)+`}`+j+s:E+A+j+s}function ee(e,t){let n,r=e[u],i=e[g],a=e[_],o=e[h],s=o[v],c=e[f],l=e[b].bindings;t=l(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function te(e){return e.write!==e.constructor.prototype.write}function ne(e){let t=new s(e);return t.on(`error`,n),!e.sync&&T&&(c.register(t,re),t.on(`close`,function(){c.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=A,t.end=A,t.flushSync=A,t.destroy=A;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function re(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function F(e){return function(t,n,r={},i){if(typeof r==`string`)i=ne({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=ne({dest:i})}else if(r instanceof s||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof s||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=E({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:o}=r;return a===!1&&(r.level=`silent`),o||(r.onChild=A),i||=te(process.stdout)?process.stdout:ne({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function ie(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[_])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ae(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}n.exports={noop:A,buildSafeSonicBoom:ne,asChindings:ee,asJson:N,genLog:j,createArgsNormalizer:F,stringify:ie,buildFormatters:ae,normalizeDestFileDescriptor:I}})),dt=n(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),ft=n(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Qe(),{noop:l,genLog:u}=ut(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=dt(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),pt=n(((e,t)=>{t.exports={version:`10.3.1`}})),mt=n(((e,n)=>{let{EventEmitter:r}=t(`node:events`),{lsCacheSym:i,levelValSym:a,setLevelSym:o,getLevelSym:s,chindingsSym:c,mixinSym:l,asJsonSym:u,writeSym:d,mixinMergeStrategySym:f,timeSym:p,timeSliceIndexSym:m,streamSym:h,serializersSym:g,formattersSym:_,errorKeySym:v,messageKeySym:y,useOnlyCustomLevelsSym:b,needsMetadataGsym:x,redactFmtSym:S,stringifySym:C,formatOptsSym:w,stringifiersSym:T,msgPrefixSym:E,hooksSym:D}=Qe(),{getLevel:O,setLevel:k,isLevelEnabled:A,mappings:j,initialLsCache:M,genLsCache:N,assertNoLevelCollisions:P}=ft(),{asChindings:ee,asJson:te,buildFormatters:ne,stringify:re,noop:F}=ut(),{version:ie}=pt(),ae=$e(),I={constructor:class{},child:L,bindings:se,setBindings:ce,flush:ue,isLevelEnabled:A,version:ie,get level(){return this[s]()},set level(e){this[o](e)},get levelVal(){return this[a]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[E]},get[Symbol.toStringTag](){return`Pino`},[i]:M,[d]:le,[u]:te,[s]:O,[o]:k};Object.setPrototypeOf(I,r.prototype),n.exports=function(){return Object.create(I)};let oe=e=>e;function L(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[g],r=this[_],i=Object.create(this);if(t==null)return i[_].bindings!==oe&&(i[_]=ne(r.level,oe,r.log)),i[c]=ee(i,e),this.onChild!==F&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[g]=Object.create(null);for(let e in n)i[g][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var a=0;a<e.length;a++){let t=e[a];i[g][t]=n[t]}for(let e in t.serializers)i[g][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var s=0;s<r.length;s++){let e=r[s];i[g][e]=t.serializers[e]}}else i[g]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[_]=ne(e||r.level,n||oe,a||r.log)}else i[_]=ne(r.level,oe,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(P(this.levels,t.customLevels),i.levels=j(t.customLevels,i[b]),N(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ae(i.redact,re),n={stringify:e[S]};i[C]=re,i[T]=e,i[w]=n}if(typeof t.msgPrefix==`string`&&(i[E]=(this[E]||``)+t.msgPrefix),i[c]=ee(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[o](e)}return this.onChild(i),i}function se(){let e=`{${this[c].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function ce(e){this[c]=ee(this,e)}function R(e,t){return Object.assign(t,e)}function le(e,t,n){let r=this[p](),i=this[l],a=this[v],o=this[y],s=this[f]||R,c,d=this[D].streamWrite;e==null?c={}:e instanceof Error?(c={[a]:e},t===void 0&&(t=e.message)):(c=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(c=s(c,i(c,n,this)));let g=this[u](c,t,n,r),_=this[h];_[x]===!0&&(_.lastLevel=n,_.lastObj=c,_.lastMsg=t,_.lastTime=r.slice(this[m]),_.lastLogger=this),_.write(d?d(g):g)}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[h];typeof t.flush==`function`?t.flush(e||F):e&&e()}})),ht=n(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),gt=n(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=dt(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),_t=n(((e,n)=>{let r=t(`node:os`),i=Ye(),a=Xe(),o=$e(),s=et(),c=mt(),l=Qe(),{configure:u}=ht(),{assertDefaultLevelFound:d,mappings:f,genLsCache:p,genLevelComparison:m,assertLevelComparison:h}=ft(),{DEFAULT_LEVELS:g,SORTING_ORDER:_}=dt(),{createArgsNormalizer:v,asChindings:y,buildSafeSonicBoom:b,buildFormatters:x,stringify:S,normalizeDestFileDescriptor:C,noop:w}=ut(),{version:T}=pt(),{chindingsSym:E,redactFmtSym:D,serializersSym:O,timeSym:k,timeSliceIndexSym:A,streamSym:j,stringifySym:M,stringifySafeSym:N,stringifiersSym:P,setLevelSym:ee,endSym:te,formatOptsSym:ne,messageKeySym:re,errorKeySym:F,nestedKeySym:ie,mixinSym:ae,levelCompSym:I,useOnlyCustomLevelsSym:oe,formattersSym:L,hooksSym:se,nestedKeyStrSym:ce,mixinMergeStrategySym:R,msgPrefixSym:le}=l,{epochTime:ue,nullTime:de}=s,{pid:z}=process,fe=r.hostname(),pe=i.err,me=v({level:`info`,levelComparison:_.ASC,levels:g,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:z,hostname:fe},serializers:Object.assign(Object.create(null),{err:pe}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ue,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),he=Object.assign(Object.create(null),i);function ge(...e){let t={},{opts:n,stream:r}=me(t,a(),...e);n.level&&typeof n.level==`string`&&g[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:i,crlf:s,serializers:l,timestamp:_,messageKey:v,errorKey:b,nestedKey:C,base:T,name:z,level:fe,customLevels:pe,levelComparison:he,mixin:ge,mixinMergeStrategy:_e,useOnlyCustomLevels:B,formatters:ve,hooks:ye,depthLimit:be,edgeLimit:xe,onChild:Se,msgPrefix:Ce}=n,V=u({maximumDepth:be,maximumBreadth:xe}),we=x(ve.level,ve.bindings,ve.log),Te=S.bind({[N]:V}),H=i?o(i,Te):{},Ee=i?{stringify:H[D]}:{stringify:Te},De=`}`+(s?`\r
|
|
4
4
|
`:`
|
|
@@ -88,5 +88,5 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
88
88
|
`)){let n=t.trim();if(!n)continue;let r=e.get(n)??Te(this.contentDir,V(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await kh(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!Sb.test(g)){$.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=L(this.projectDir,{credentialArgs:this.credentialArgs});for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=bb(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=L(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=bb(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}$.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{_e(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=V(xe(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=L(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let r=(await i.git.raw([`write-tree`])).trim();if(r===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let a=await kh(this.projectDir),o=a?.name??`Open Knowledge`,s=a?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:o,GIT_AUTHOR_EMAIL:s,GIT_COMMITTER_NAME:o,GIT_COMMITTER_EMAIL:s});let c=(await i.git.raw([`commit-tree`,r,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!c||!Sb.test(c))return $.warn({raw:c},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,c,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return c}finally{try{_e(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
|
|
89
89
|
`).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=fe(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=V(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=Te(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Te(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return R(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=L(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
|
|
90
90
|
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){$.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=V(this.projectDir,e),i=Te(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){$.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=L(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),$.info({},`[sync] merge aborted`)}catch(e){$.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};B(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(R(this.statePath))try{let e=z(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};const Db=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function Ob(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=ln(`server`),_=H(t,`.open-knowledge`);re(_,{port:e.port??0,worktreeRoot:n});let v,y,x,S,C,w,T=null,E=null,D=null,O=null;function k(e){T?.signal(e)}try{v=Py({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),y=new vm({projectDir:n,contentDir:t,contentFilter:v}),x={current:u},S=nh({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:x,contentRoot:d,backlinkIndex:y,getCurrentBranch:()=>oe?.getLastKnownBranch()??null,getPrincipal:()=>O}),C=new gy({quiet:r,debounce:i,maxDebounce:a,extensions:[S.extension]}),T=new El(C),E=new un(C),D=new Hn(C),w=new Pl(C);let m=qy({backlinkIndex:y,signalChannel:k});C.configuration.extensions.push(m),C.configuration.extensions.push({async onAuthenticate(e){try{let t=e.token;if(!t)return;let n=JSON.parse(t),r=e.context;typeof n.principalId==`string`&&(O&&n.principalId===O.id?r.principalId=O.id:O?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:O.id})):r.principalId=n.principalId),typeof n.tabSessionId==`string`&&(r.tabSessionId=n.tabSessionId),r.kind=`human`}catch{}}});let g=h_({hocuspocus:C,sessionManager:w,contentDir:t,getFileIndex:()=>I?I.getFileIndex():new Map,getAliasMap:()=>I?I.getAliasMap():new Map,enableTestRoutes:l,shadowRef:x,flushGitCommit:()=>S.flushPendingGitCommit(),getCurrentBranch:()=>oe?.getLastKnownBranch()??null,contentRoot:d,backlinkIndex:y,signalChannel:k,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>L,localOpCliArgs:h,projectDir:n,getPrincipal:()=>O});C.configuration.extensions.push(g),C.configuration.extensions.push(eb({mdManager:Dl,schema:Ol,shadowRef:x,contentRoot:d,getCurrentBranch:()=>oe?.getLastKnownBranch()??null}))}catch(e){throw te(_),e}let A=null;function j(e,t){let n=H(e,`rescue`),r=H(n,`${t}${Up(t)}`);return r.startsWith(`${n}/`)?r:null}function N(e){let t=C.documents.get(e);if(!t)return null;let n=Tl(t.getXmlFragment(`default`),Ol).toJSON(),r=Dl.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return M(typeof i==`string`?i:``,r)}let P=(e,t)=>zy(C,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function ne(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),y.updateDocumentFromMarkdown(e.docName,e.content),y.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),k(`files`),k(`backlinks`),k(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=C.documents.get(t);if(!r){y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),k(`backlinks`),k(`graph`);return}let i=Xm(t)??``,a=N(t)??i,o=oh({docName:t,base:i,ours:a,theirs:n}),s=mh(i).slice(0,6),c=mh(a).slice(0,6),l=mh(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),k(`backlinks`),k(`graph`);break;case`clean`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),Zm(t,n)}break;case`merged`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),Zm(t,n)}break;case`conflicts`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),gn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),Zm(t,n)}break;case`refused`:{gn();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=C.documents.get(t);if(!n){y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),k(`files`),k(`backlinks`),k(`graph`);return}let r=Xm(t)??``,i=N(t)??``,a=i!==r;if(a&&x.current){let e=x.current,n=oe?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Lm(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Qm(t),y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),C.closeConnections(t),await C.unloadDocument(n),k(`files`),k(`backlinks`),k(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=C.documents.get(t);if(Qm(t),Zm(n,r),y.renameDocument(t,n,r),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),k(`files`),k(`backlinks`),k(`graph`);break}case`conflict`:{let{docName:t}=e,n=C.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let F=[];async function ie(e){if(th()){F.push(e);return}await ne(e)}async function ae(){let e=F.splice(0,F.length);for(let t of e)await ne(t)}let I=null,oe=null,L=null,se=null;async function ce(e){if(C.documents.size===0)return;let t=!1,n=new Promise(e=>{C.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(C.documents.keys());C.closeConnections(),C.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(C.documents.keys()),i=[],o=[];if(x.current){for(let e of n)if(!J(e))try{let t=N(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=j(x.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:x.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ue(Se(n),{recursive:!0}),B(n,t,`utf-8`),yn(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function le(){return se||(se=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([pe.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=C.documents.size;try{try{try{oe&&=(await oe.unsubscribe(),null),I&&=(await I.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{T?.destroy(),D?.destroy(),A&&=(await A.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await w.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ce(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await S.flushPendingGitCommit(),await S.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{L&&=(await L.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(x.current){try{let e=(await Fe({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&B(H(x.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{wm(x.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{te(_)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),se)}let de=[];async function fe(){try{O=await Yy(t),g.info({principalId:O.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!x.current)try{x.current=await Cm(n),g.info({gitDir:x.current.gitDir},`[server] history repo initialized at ${x.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),de.push(`shadow-repo`)}if(x.current)try{await Sm(x.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`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{x.current=await Cm(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),x.current=void 0,de.includes(`shadow-repo`)||de.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(x.current)try{let e=H(x.current.gitDir,`last-known-head`),t=null;try{t=z(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Fe({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Fe({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Pm(x.current,d??``,t,r,e),vn()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{B(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Qh(t);e.recovered&&e.journal&&g.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){g.error({err:e},`[server] managed rename recovery failed`),de.push(`managed-rename-recovery`)}try{A=await C.openDirectConnection(b)}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),de.push(`cc1-push`)}try{I=await Dh(t,ie,v),y.rebuildFromDisk(Ym()),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${Ym()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),de.push(`file-watcher`)}try{oe=await Wy(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),_n(),C.flushPendingStores(),await S.flushPendingGitCommit(),eh(!0),x.current){let e=Ym(),t=Vy(n),r=t?Uy(t)??e:e,i=[];for(let[e,t]of C.documents){if(J(e))continue;let n=null;if(t.transact(()=>{n=N(e)},Db),n===null)continue;let r=Xm(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await zm(x.current,e,Mm.id,i,r);t&&(xn(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=F.length,r=e.newBranch??`main`;if(eh(!1),g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await ae();else{bn(),F.splice(0,F.length),Jm(r),y.switchBranch(r);for(let[e,n]of C.documents)if(!J(e))try{let i=Wm(e,t);if(!R(i)){let t=Xm(e)??``,i=N(e)??``;if(i!==t&&x.current){let t=x.current;queueMicrotask(()=>{Lm(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=z(i,`utf-8`);P(e,a),Zm(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:C.documents.size},`[branch-switch] loaded branch ${r} (${C.documents.size} docs)`),y.rebuildFromDisk(r),y.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),x.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of C.documents)if(!J(t))try{let n=await Bm(x.current,r,Mm.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Xm(t);if(!i)continue;let a=oh({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:P(t,a.newContent),Zm(t,a.newContent),e++;break;case`conflicts`:P(t,a.newContent),Zm(t,a.newContent),gn(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&x.current)try{let t=Sm(x.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
|
|
91
|
-
`))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`content`;try{let n=await Pm(x.current,t,e.oldHead,e.newHead,r);vn(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),de.push(`head-watcher`)}let e=h?.[0]??`open-knowledge`,r=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):e} auth git-credential`];try{L=new Eb({projectDir:n,contentDir:t,contentFilter:v,contentRoot:d,credentialArgs:r,cc1Broadcaster:T,setBatchInProgress:eh,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await L.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),L=null}}let pe=fe();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:v,destroy:le,ready:pe,degraded:de,lockDir:_,get syncEngine(){return L}}}async function kb(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??ln(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-_sZfvZ-v.mjs`),{updateServerLockPort:s}=await import(`./server-lock-
|
|
92
|
-
//# sourceMappingURL=src-
|
|
91
|
+
`))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`content`;try{let n=await Pm(x.current,t,e.oldHead,e.newHead,r);vn(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),de.push(`head-watcher`)}let e=h?.[0]??`open-knowledge`,r=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):e} auth git-credential`];try{L=new Eb({projectDir:n,contentDir:t,contentFilter:v,contentRoot:d,credentialArgs:r,cc1Broadcaster:T,setBatchInProgress:eh,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await L.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),L=null}}let pe=fe();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:v,destroy:le,ready:pe,degraded:de,lockDir:_,get syncEngine(){return L}}}async function kb(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??ln(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-_sZfvZ-v.mjs`),{updateServerLockPort:s}=await import(`./server-lock-zOHsiWX-.mjs`),c=!1;!t&&e.ensureProjectGitFn&&(c=!!(await e.ensureProjectGitFn()).didInit);let l=!1;if(!t&&e.autoInitFn)try{l=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let u=Ob({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,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:d,destroy:f,ready:p,degraded:m,lockDir:h,agentPresenceBroadcaster:g}=u,_=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){d.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),v=new o({noServer:!0});v.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let y=e.keepaliveGraceMs??1e4,b=new Map,x=new Set,S=!1;_.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{zn(e)||i.error({err:e},`MCP keepalive socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=Ab(e.url);if(n){let e=b.get(n);e!==void 0&&(clearTimeout(e),b.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{g?.bumpPresenceTs(mn(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(b.delete(n),S)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await u.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{u.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{g?.clearPresence(mn(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();x.add(e),e.finally(()=>x.delete(e))},y);e.unref?.(),b.set(n,e),i.info({connectionId:n,graceMs:y},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{zn(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{zn(e)||i.error({err:e},`Upgrade socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=d.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{zn(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let C=null;r!==null&&(C=g_({httpServer:_,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await f()})})),await new Promise((t,n)=>{let r=e=>n(e);_.once(`error`,r),_.listen(e.port,e.host,()=>{_.removeListener(`error`,r),t()})});let w=_.address(),T=typeof w==`object`&&w?w.port:e.port??0;if(s(h,T),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let E=!1;return{httpServer:_,destroy:async()=>{if(!E){E=!0,S=!0,C?.detach();for(let e of b.values())clearTimeout(e);b.clear(),x.size>0&&await Promise.allSettled([...x]),await new Promise(e=>{_.close(()=>e())}),await f()}},lockDir:h,contentDir:e.contentDir,port:T,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}function Ab(e){if(!e)return null;try{return pn(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const jb=He(Me);var Mb=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function Nb(e){let t=H(e),n=H(t,`.git`);if(R(n))return{didInit:!1};let r=``;try{r=(await jb(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new Mb(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!R(H(n,`HEAD`)))throw new Mb(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}export{fm as $,Dh as A,jm as B,mh as C,un as Ct,hh as D,_h as E,cn as Et,oh as F,km as G,Om as H,ah as I,Im as J,Cm as K,nh as L,uh as M,rh as N,fh as O,ih as P,vm as Q,Wm as R,bh as S,pn as St,xh as T,ln as Tt,Pm as U,Mm as V,Em as W,Vm as X,Lm as Y,Sm as Z,qg as _,zn as _t,Ob as a,rp as at,ug as b,fn as bt,Zy as c,Rl as ct,Uy as d,Pl as dt,Mp as et,Ry as f,Al as ft,Jg as g,Vn as gt,g_ as h,Hn as ht,Ab as i,Pp as it,vh as j,yh as k,Yy as l,ru as lt,Py as m,J as mt,Nb as n,Fp as nt,eb as o,$f as ot,zy as p,El as pt,Rm as q,kb as r,Ip as rt,Xy as s,Ll as st,Mb as t,Np as tt,qy as u,Jl as ut,h_ as v,Fn as vt,ph as w,sn as wt,lg as x,mn as xt,n_ as y,Dn as yt,Am as z};
|
|
92
|
+
//# sourceMappingURL=src-rqPIkHTi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./start-DAAnFlO5.mjs";export{e as startCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e}from"./constants-
|
|
2
|
-
//# sourceMappingURL=start-
|
|
1
|
+
import{a as e}from"./constants-DA7Qh-Kl.mjs";import{O as t}from"./src-CQw-HNNM.mjs";import{Command as n}from"commander";import{closeSync as r,existsSync as i,mkdirSync as a,openSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){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 @inkeep/open-knowledge\`. This re-introduces the version-drift surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`@inkeep/open-knowledge`]})}function u(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 d(e){i(e.lockDir)||a(e.lockDir,{recursive:!0});let t=o(s(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??c,{PORT:u,...d}=process.env,f=l();try{let r=n(f.command,[...f.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:d});return r.unref(),r}finally{try{r(t)}catch{}}}async function f(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 p(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>new Promise(t=>setTimeout(t,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 m(e){let{config:n,cwd:r}=e,i=e.skipAutoInit??!1,a=e.skipUiAutoSpawn??!1,o=e.idleThresholdMs??18e5,{existsSync:s,mkdirSync:c}=await import(`node:fs`),{resolve:l}=await import(`node:path`),{bootServer:m,ensureProjectGit:h,getLogger:g,isProcessAlive:_,readUiLock:v}=await import(`./src-DHnGx64r.mjs`),{resolveContentDir:y}=await import(`./paths-BhmQnYL9.mjs`),b=e.log??g(`start`),x=y(n,r);s(x)||(c(x,{recursive:!0}),b.info({contentDir:x},`Created content directory`));let S=!s(l(r,t)),C=i?void 0:async()=>{try{let{initContent:e}=await import(`./init-CFVYH-16.mjs`),t=e(r);return S||t.created.length>0}catch(e){return console.warn(`Auto-init failed:`,e instanceof Error?e.message:e),!1}},w=!1,T=l(x,t),E=n.server.openOnAgentEdit?()=>{if(w)return;let e=v(T);if(!e||e.port<=0||!_(e.pid))return;w=!0;let t=`http://localhost:${e.port}`;import(`./open-browser-CfwaLBtR.mjs`).then(({openBrowser:e})=>e(t)).catch(()=>{})}:void 0,D=null,O=await m({contentDir:x,projectDir:r,contentRoot:n.content.dir,port:n.server.port,host:n.server.host,quiet:!1,debounce:n.persistence.debounceMs,maxDebounce:n.persistence.maxDebounceMs,includePatterns:n.content.include,excludePatterns:n.content.exclude,onAgentWrite:E,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:o,skipAutoInit:i,autoInitFn:C,ensureProjectGitFn:i?void 0:()=>h(r),spawnUiSiblingFn:async({lockDir:t})=>{if(D=u({uiLock:v(t),isAlive:_}),D.action===`spawn`&&!a)try{d({lockDir:t,cwd:r,spawn:e.spawn}),b.info({reason:D.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 D.action===`skip`&&b.info({port:D.port,pid:D.pid},`UI already running at port ${D.port}`)},idleShutdownHandler:e=>p({readUiLock:()=>v(O.lockDir),isAlive:_,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:b}),log:b});D||={action:`skip`,reason:`alive`,pid:0,port:0};let k=D,A=null;if(k.action===`skip`)A=k.port>0?k.port:null;else if(!a){let t=e.uiBindTimeoutMs??3e3;A=await f({readUiLock:()=>v(O.lockDir),now:Date.now,sleep:e=>new Promise(t=>setTimeout(t,e)),timeoutMs:t,pollIntervalMs:50}),A===null&&b.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:O.httpServer,destroy:O.destroy,lockDir:O.lockDir,contentDir:x,port:O.port,ready:O.ready,degraded:O.degraded,uiSpawnDecision:D,resolvedUiPort:A,didAutoInit:O.didAutoInit,didGitInit:O.didGitInit}}function h(r){return new n(`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(`--no-init`,`Skip auto-scaffolding of ${t}/`).action(async n=>{let{renderBanner:i}=await import(`./banner-C51OKbnz.mjs`),{dim:a,error:o,info:s,warning:c}=await import(`./colors-xJqYhQcY.mjs`),l=r(),u=process.cwd();n.port!==void 0&&(l.server.port=Number(n.port)),n.host!==void 0&&(l.server.host=n.host);let d;try{d=await m({config:l,cwd:u,skipAutoInit:n.init===!1})}catch(e){let{ProjectGitInitError:t}=await import(`./src-DHnGx64r.mjs`);e instanceof t&&(console.error(o(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.`)),e.stderr&&console.error(a(e.stderr.trim())),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let f=!1,p=async e=>{if(!f){f=!0,console.log(a(`\nShutting down (${e})...`));try{await d.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{p(`SIGINT`)}),process.once(`SIGTERM`,()=>{p(`SIGTERM`)});let h=`http://${l.server.host}:${d.port}`,g=l.server.host===`0.0.0.0`||l.server.host===`::`?`http://0.0.0.0:${d.port}`:void 0,_=d.resolvedUiPort,v=_!==null&&_>0?`http://${l.server.host}:${_}`:h;console.log(i({name:`open-knowledge`,version:e,localUrl:v,apiUrl:v===h?void 0:h,networkUrl:g})),d.didAutoInit&&(console.log(` ${s(`✓`)} Scaffolded ${t}/ (first run)`),console.log(` ${a("Tip: Run `open-knowledge init` to register MCP tools for Claude Code")}\n`));let y={"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`};d.ready.then(async()=>{if(d.degraded.length>0){console.log();for(let e of d.degraded){let t=y[e]??`${e} (check server logs for details)`;console.warn(` ${c(`⚠`)} ${c(e)}: ${a(t)}`)}console.log()}if(d.didAutoInit||d.didGitInit)if(d.didGitInit&&console.log(`\n ${s(`✓`)} Initialized git repo at ${u}/.git/ (default branch: main)`),d.didAutoInit)try{let{previewContent:e,formatPreviewBlock:t}=await import(`./preview-CULBnUoI.mjs`),n=e({projectDir:u,contentDir:d.contentDir,include:l.content.include,exclude:l.content.exclude});console.log(`\n${t(n,u)}\n`)}catch(e){console.warn(`Content preview unavailable: ${e instanceof Error?e.message:String(e)}`)}else console.log();if(n.open){let{openBrowser:e}=await import(`./open-browser-CfwaLBtR.mjs`);e(v)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})})}export{d as a,u as i,m as n,h as o,p as r,l as s,f as t};
|
|
2
|
+
//# sourceMappingURL=start-DAAnFlO5.mjs.map
|
package/package.json
CHANGED
package/dist/init-Z_14KXK6.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-Ca3oXZ2r.mjs";export{o as detectInstalledEditors,n as formatInitResult,i as initCommand,t as readExistingMcpEntry,e as runInit,r as writeEditorMcpConfig,a as writeUserMcpConfigs};
|
package/dist/init-t1KAo7Xn.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-BEYJxssT.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
|
package/dist/loader-C_Bm1Mam.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./loader-AGQcuG-5.mjs";export{e as loadConfig};
|
package/dist/paths-OkgDVC2Q.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./paths-BHyG1wt5.mjs";export{t as resolveContentDir,e as resolveLockDir};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./preview-BNr7OMR-.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{closeSync as e,existsSync as t,mkdirSync as n,openSync as r,readFileSync as i,unlinkSync as a,writeFileSync as o,writeSync as s}from"node:fs";import{hostname as c}from"node:os";import{resolve as l}from"node:path";function u(e){try{return process.kill(e,0),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`)}}var d=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`Open Knowledge ${n} already running on port ${e.port} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function f(e,t){return l(e,`${t}.lock`)}function p(e,t){try{let n=JSON.parse(i(e,`utf-8`));return n&&typeof n==`object`&&typeof n.pid==`number`?n:(console.warn(`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return console.warn(`${t} Corrupt lock file at ${e} — replacing`),null}}function m(i){let{lockName:l,lockDir:m,metadata:g}=i,_=`[${l}-lock]`;n(m,{recursive:!0});let v=f(m,l),y={pid:process.pid,hostname:c(),port:g.port,startedAt:new Date().toISOString(),worktreeRoot:g.worktreeRoot},b=JSON.stringify(y,null,2);for(let n=0;n<3;n++){if(!t(v))try{let t=r(v,`wx`,384);try{s(t,b)}finally{e(t)}return h({lockName:l,lockDir:m,lockPath:v})}catch(e){if(e.code!==`EEXIST`)throw e}let n=p(v,_);if(n){let e=n.hostname===c();if(e&&n.pid===process.pid)return o(v,b,{encoding:`utf-8`,mode:384}),h({lockName:l,lockDir:m,lockPath:v});if(e&&u(n.pid))throw new d(n,v,l);console.warn(`${_} Stale lock detected (pid=${n.pid}, host=${n.hostname}) — replacing`)}try{a(v)}catch{}}throw Error(`${_} Failed to acquire ${v} after 3 attempts (concurrent acquire contention).`)}function h(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>v({lockName:t,lockDir:n}),updatePort:e=>g({lockName:t,lockDir:n,port:e})}}function g(e){let{lockName:n,lockDir:r,port:a}=e,s=`[${n}-lock]`,l=f(r,n);if(!t(l)){console.warn(`${s} Lock file missing at ${l} during port update — skipping`);return}let u;try{let e=JSON.parse(i(l,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`){console.warn(`${s} Corrupt lock at ${l} during port update — skipping`);return}u=e}catch{console.warn(`${s} Unreadable lock at ${l} during port update — skipping`);return}if(u.pid===process.pid&&!(typeof u.hostname==`string`&&u.hostname!==c())){u.port=a;try{o(l,JSON.stringify(u,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${s} Failed to update port in ${l}: ${e instanceof Error?e.message:String(e)}`)}}}function _(e){let{lockName:n,lockDir:r}=e,o=f(r,n);if(!t(o))return null;let s;try{let e=JSON.parse(i(o,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`)return null;s=e}catch{return null}if(s.hostname!==c())return null;if(!u(s.pid)){try{a(o)}catch{}return null}return s}function v(e){let{lockName:n,lockDir:r}=e,o=`[${n}-lock]`,s=f(r,n);if(t(s))try{let e=JSON.parse(i(s,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||typeof e.hostname==`string`&&e.hostname!==c())return;a(s)}catch(e){console.warn(`${o} Failed to release ${s}: ${e instanceof Error?e.message:String(e)}`)}}var y=class extends d{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function b(e,t){try{return m({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof d&&e.lockName===`server`?new y(e.existing,e.lockPath):e}}function x(e,t){g({lockName:`server`,lockDir:e,port:t})}function S(e){return _({lockName:`server`,lockDir:e})}function C(e){v({lockName:`server`,lockDir:e})}export{x as a,f as c,g as d,u as f,C as i,_ as l,b as n,d as o,S as r,m as s,y as t,v as u};
|
|
2
|
-
//# sourceMappingURL=server-lock-B4frNnOB.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e}from"./server-lock-B4frNnOB.mjs";export{e as updateServerLockPort};
|
package/dist/src-Cgf9w34f.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./init-Ca3oXZ2r.mjs";import"./loader-AGQcuG-5.mjs";export{};
|
package/dist/src-DB3pnkMU.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./src-CQw-HNNM.mjs";import{$ as e,et as t,n,nt as r,r as i,rt as a,t as o,tt as s,wt as c}from"./src-skP-DoiW.mjs";import{f as l,r as u}from"./server-lock-B4frNnOB.mjs";export{o as ProjectGitInitError,e as UiLockCollisionError,t as acquireUiLock,i as bootServer,n as ensureProjectGit,c as getLogger,l as isProcessAlive,u as readServerLock,s as readUiLock,r as releaseUiLock,a as updateUiLockPort};
|
package/dist/start-iuBWR-Az.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./start-BJ0_AeSA.mjs";export{e as startCommand};
|