@inkeep/open-knowledge 0.4.0-beta.32 → 0.4.0-beta.34

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.
Files changed (31) hide show
  1. package/dist/assets/skills/open-knowledge/SKILL.md +1 -1
  2. package/dist/cli.mjs +5 -5
  3. package/dist/constants-BgI7SDCI.mjs +2 -0
  4. package/dist/{dist-BjlSvO5w.mjs → dist-BXmbRKLs.mjs} +1 -1
  5. package/dist/{dist-Bfw3oOGm.mjs → dist-BaVVyZsg.mjs} +218 -2
  6. package/dist/index.mjs +1 -1
  7. package/dist/init-CfT911gp.mjs +1 -0
  8. package/dist/{init-DsLc7vc7.mjs → init-Mu6hjAn2.mjs} +3 -3
  9. package/dist/loader-tcpZSp2X.mjs +1 -0
  10. package/dist/{loader-DmKx1Dxe.mjs → loader-th8fUQ0l.mjs} +2 -2
  11. package/dist/preview-B14jfjgL.mjs +1 -0
  12. package/dist/{preview-CuLb6srO.mjs → preview-Brj3agTC.mjs} +2 -2
  13. package/dist/public/assets/{ActivityModeContent-PLMlj69Z.js → ActivityModeContent-CukRGM5b.js} +1 -1
  14. package/dist/public/assets/{DocumentContext-DyDoN3zw.js → DocumentContext-Dnlc0y78.js} +1 -1
  15. package/dist/public/assets/{SettingsDialog-BZIR95bl.js → SettingsDialog-D01daWLi.js} +1 -1
  16. package/dist/public/assets/{SourceEditor-BSNx4vgo.js → SourceEditor-oc5DmPOz.js} +2 -2
  17. package/dist/public/assets/{config-validation-events-CQdOhgu4.js → config-validation-events-BhBbdwp7.js} +1 -1
  18. package/dist/public/assets/index-DhEY5RAu.css +1 -0
  19. package/dist/public/assets/{index-DplFbAir.js → index-n61bMVO9.js} +67 -67
  20. package/dist/public/assets/{typing-burst-detector-2N-LtlIn.js → typing-burst-detector-niWkdPcc.js} +1 -1
  21. package/dist/public/index.html +5 -5
  22. package/dist/{src-CPSJr8lr.mjs → src-_bKfCVLS.mjs} +2 -2
  23. package/dist/start-BiFE3OLx.mjs +1 -0
  24. package/dist/{start-DUBJCx0O.mjs → start-JWghIgzZ.mjs} +2 -2
  25. package/package.json +1 -1
  26. package/dist/constants-BVG2ymMz.mjs +0 -2
  27. package/dist/init-CcjfJ0-a.mjs +0 -1
  28. package/dist/loader-BLwabAxT.mjs +0 -1
  29. package/dist/preview-GtCa8ObI.mjs +0 -1
  30. package/dist/public/assets/index-CjbILLtI.css +0 -1
  31. package/dist/start-BoXsjqPU.mjs +0 -1
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "MUST invoke when the project contains a .ok/ directory — before any read or edit of .md / .mdx files, any mcp__open-knowledge__ tool call, and any write_document / edit_document. Skip if no .ok/ — not an Open Knowledge project. Carries preview-attach (open preview browser at session start; one-shot on `action: attach-preview-once`), STOP rules for native Read/Grep/Edit on in-scope markdown, grounding rules (every factual claim needs a source), standard markdown linking with get_dead_links verification, image sourcing + alt-text + source-citation rules, folder-first organization with opt-in nested .ok/ frontmatter + templates, and the anti-pattern table. Authoritative — MCP server instructions and AGENTS.md overlap but do not substitute for the full attach rule, grounding rule, media rules, dead-link verification, and failure-mode guidance carried only here."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.4.0-beta.32"
6
+ version: "0.4.0-beta.34"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Dr as n,Er as r,Ln as i,Lr as a,On as o,Ot as s,Pr as c,Tr as l,Xr as u,Y as d,Zr as f,br as p,it as m,jr as h,mr as g,r as ee,vr as _,wr as v,yr as y}from"./dist-k62w-4-v.mjs";import{n as b,r as x,t as S}from"./dist-bundle-BSdjl7Rj.mjs";import{C as te,S as C,T as ne,_ as re,b as ie,g as ae,h as oe,r as se,v as w,w as ce,x as le,y as ue}from"./init-DsLc7vc7.mjs";import{c as de,f as fe,l as pe,n as me,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as he}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{$ as ge,Br as _e,D as ve,Dn as ye,E as be,G as xe,Gn as Se,Gr as Ce,H as we,Hr as Te,Ir as Ee,Jn as De,Jr as Oe,Kt as ke,Ur as Ae,V as je,Vr as Me,Wr as Ne,an as Pe,it as Fe,m as Ie,on as Le,ot as Re,qr as ze,sr as Be,un as Ve,zn as He}from"./dist-Bfw3oOGm.mjs";import{n as Ue}from"./constants-BVG2ymMz.mjs";import{n as We,t as Ge}from"./loader-DmKx1Dxe.mjs";import{d as Ke,f as qe,l as Je,m as Ye,p as Xe,s as Ze}from"./start-DUBJCx0O.mjs";import{c as Qe,i as $e,n as E,o as D,r as O,s as k,t as A}from"./colors-BtKMHmBX.mjs";import"./src-CPSJr8lr.mjs";import{execFileSync as et,spawn as tt,spawnSync as j}from"node:child_process";import nt,{basename as rt,dirname as it,join as M,relative as at,resolve as N}from"node:path";import{closeSync as ot,existsSync as P,mkdirSync as st,mkdtempSync as ct,openSync as lt,readFileSync as F,readdirSync as ut,rmSync as dt,statSync as ft,unlinkSync as pt,writeFileSync as mt}from"node:fs";import ht from"node:process";import{homedir as gt,hostname as _t,tmpdir as vt}from"node:os";import{fileURLToPath as yt}from"node:url";import{AsyncLocalStorage as bt,AsyncResource as xt}from"node:async_hooks";import{stripVTControlCharacters as St,styleText as I}from"node:util";import*as Ct from"node:readline";import{randomUUID as wt}from"node:crypto";import{realpath as Tt}from"node:fs/promises";import{setTimeout as Et}from"node:timers/promises";import{createServer as Dt,request as Ot}from"node:http";import{createInterface as kt}from"node:readline/promises";var At=f();const jt=`open-knowledge`;var Mt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(jt,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(jt,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(jt,e).deletePassword()}catch{}}},Nt=class{backend=`file`;authFile;constructor(e){this.authFile=e??M(gt(),`.ok`,`auth.yml`)}read(){if(!P(this.authFile))return{};try{return(0,At.parse)(F(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=it(this.authFile);P(t)||st(t,{recursive:!0,mode:448}),mt(this.authFile,(0,At.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Pt(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(jt,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Dr as n,Er as r,Ln as i,Lr as a,On as o,Ot as s,Pr as c,Tr as l,Xr as u,Y as d,Zr as f,br as p,it as m,jr as h,mr as g,r as ee,vr as _,wr as v,yr as y}from"./dist-k62w-4-v.mjs";import{n as b,r as x,t as S}from"./dist-bundle-BSdjl7Rj.mjs";import{C as te,S as C,T as ne,_ as re,b as ie,g as ae,h as oe,r as se,v as w,w as ce,x as le,y as ue}from"./init-Mu6hjAn2.mjs";import{c as de,f as fe,l as pe,n as me,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as he}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{$ as ge,Br as _e,D as ve,Dn as ye,E as be,G as xe,Gn as Se,Gr as Ce,H as we,Hr as Te,Ir as Ee,Jn as De,Jr as Oe,Kt as ke,Ur as Ae,V as je,Vr as Me,Wr as Ne,an as Pe,it as Fe,m as Ie,on as Le,ot as Re,qr as ze,sr as Be,un as Ve,zn as He}from"./dist-BaVVyZsg.mjs";import{n as Ue}from"./constants-BgI7SDCI.mjs";import{n as We,t as Ge}from"./loader-th8fUQ0l.mjs";import{d as Ke,f as qe,l as Je,m as Ye,p as Xe,s as Ze}from"./start-JWghIgzZ.mjs";import{c as Qe,i as $e,n as E,o as D,r as O,s as k,t as A}from"./colors-BtKMHmBX.mjs";import"./src-_bKfCVLS.mjs";import{execFileSync as et,spawn as tt,spawnSync as j}from"node:child_process";import nt,{basename as rt,dirname as it,join as M,relative as at,resolve as N}from"node:path";import{closeSync as ot,existsSync as P,mkdirSync as st,mkdtempSync as ct,openSync as lt,readFileSync as F,readdirSync as ut,rmSync as dt,statSync as ft,unlinkSync as pt,writeFileSync as mt}from"node:fs";import ht from"node:process";import{homedir as gt,hostname as _t,tmpdir as vt}from"node:os";import{fileURLToPath as yt}from"node:url";import{AsyncLocalStorage as bt,AsyncResource as xt}from"node:async_hooks";import{stripVTControlCharacters as St,styleText as I}from"node:util";import*as Ct from"node:readline";import{randomUUID as wt}from"node:crypto";import{realpath as Tt}from"node:fs/promises";import{setTimeout as Et}from"node:timers/promises";import{createServer as Dt,request as Ot}from"node:http";import{createInterface as kt}from"node:readline/promises";var At=f();const jt=`open-knowledge`;var Mt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(jt,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(jt,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(jt,e).deletePassword()}catch{}}},Nt=class{backend=`file`;authFile;constructor(e){this.authFile=e??M(gt(),`.ok`,`auth.yml`)}read(){if(!P(this.authFile))return{};try{return(0,At.parse)(F(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=it(this.authFile);P(t)||st(t,{recursive:!0,mode:448}),mt(this.authFile,(0,At.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Pt(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(jt,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new Mt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
4
4
  `),new Nt(e)}}async function Ft(e,t,n){let r=It(await Lt(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function It(e){let t={};for(let n of e.split(`
5
5
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function Lt(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Rt(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Ft(process.stdin,process.stdout,t);process.exit(n)}),n}function zt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Bt(e,t,n){let r={baseUrl:zt(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new b(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Vt(e){let t=e.request||S,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Bt(t,`POST /login/device/code`,n)}async function Ht(e){let t=await Bt(e.request||S,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ut(e,t.data.expires_in),n.refreshTokenExpiresAt=Ut(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ut(e,t){return new Date(e+t*1e3).toISOString()}async function Wt(e,t){let n=Gt(e,t.auth);if(n)return n;let{data:r}=await Vt({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await qt(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Gt(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Kt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function qt(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Ht({...i,clientType:`oauth-app`}):await Ht({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Kt(r.interval),qt(e,t,n,r);if(a===`slow_down`)return await Kt(r.interval+7),qt(e,t,n,r);throw i}}async function Jt(e,t){return Wt(e,{auth:t})}async function Yt(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await Wt(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Xt=`0.0.0-development`;function Zt(e){let t=e.request||S.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Xt} ${x()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Jt.bind(null,i),{hook:Yt.bind(null,i)})}async function Qt(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Zt({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}const $t={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var en;(function(e){})(en||={});function tn(e){return a(g,e)}function nn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const rn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function an(e){let t=e.toLowerCase().replace(/:\d+$/,``);rn.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function on(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function sn(e,t,n=Qt){let r=nn(),{host:i,json:a}=e;an(i),a||process.stderr.write(`Logging in to ${i}…\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?on(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?on(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function cn(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await sn(t,await e())})}const ln=e=>e.name===`enter`||e.name===`return`;var un=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},dn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},fn=class extends Error{name=`ExitPromptError`},pn=class extends Error{name=`HookError`},mn=class extends Error{name=`ValidationError`};const hn=new bt;function gn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function _n(e,t){let n=gn(e);return hn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function L(){let e=hn.getStore();if(!e)throw new pn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function vn(){return L().rl}function yn(e){return xt.bind((...t)=>{let n=L(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function bn(e){let t=L(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function xn(){L().handleChange()}const Sn={queue(e){let t=L(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(vn());if(r!=null&&typeof r!=`function`)throw new mn(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=L();yn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=L();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Cn(e){return typeof e==`function`}function R(e){return bn(t=>{let n=xt.bind(function(e){t.get()!==e&&(t.set(e),xn())});if(t.initialized)return[t.get(),n];let r=Cn(e)?e():e;return t.set(r),[r,n]})}function wn(e,t){bn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Sn.queue(e),n.set(t)})}const Tn={prefix:{idle:I(`blue`,`?`),done:I(`green`,ne.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>I(`yellow`,e))},style:{answer:e=>I(`cyan`,e),message:e=>I(`bold`,e),error:e=>I(`red`,`> ${e}`),defaultAnswer:e=>I(`dim`,`(${e})`),help:e=>I(`dim`,e),highlight:e=>I(`cyan`,e),key:e=>I(`cyan`,I(`bold`,`<${e}>`))}};function En(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Dn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=En(n)&&En(r)?Dn(n,r):r}return t}function On(...e){return Dn(Tn,...e.filter(e=>e!=null))}function kn({status:e=`idle`,theme:t}){let[n,r]=R(!1),[i,a]=R(0),{prefix:o,spinner:s}=On(t);return wn(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function An(e){return R({current:e})[0]}function jn(e){let t=An(e);t.current=e,wn(e=>{let n=!1,r=yn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var Mn=e(ce(),1);function Nn(e,t){return e.split(`
@@ -17,10 +17,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
17
17
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function Br(e){return new t(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await zr(t,await e())})}async function Vr(e,t){let{host:n,json:r}=e;an(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 Rr({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 Hr(e){return new t(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Vr(t,await e())})}async function Ur(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function Wr(e){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Ur(t,await e())})}async function Gr(e,t){let{host:n,json:r}=e;an(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 Rr({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`})+`
18
18
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Kr(e){return new t(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Gr(t,await e())})}function qr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>Pt();return e.addCommand(cn(n)),e.addCommand(Kr(n)),e.addCommand(Hr(n)),e.addCommand(Wr(n)),e.addCommand(Br(n)),e.addCommand(Rt(n)),e}function B(e,t,n={}){let r=pe(e,t);if(!P(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(F(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!de(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??T)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??_t();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Jr(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 Yr(e){let t=e.inspect??(t=>B(e.lockDir,t)),n=e.unlink??(e=>pt(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Jr(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 Xr(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Yr({lockDir:De(process.cwd())}).failed.length>0&&(process.exitCode=1)})}function Zr(){try{let e=et(`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 Qr(e,t,n={},r=Zr){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 $r(e){return e.replace(/:\d+$/,``)}function ei(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:$r(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:$r(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:$r(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 ti=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function ni(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of ti)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function V(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function ri(e,t,n,r=process.cwd()){let i=ei(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?N(r,t.dir):N(r,i.name);if(P(a)&&ut(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Pt(),s=await Qr(i.hostname,o,{}),c=he({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
19
19
  `)){let n=ni(e);n&&n.pct!==l&&(l=n.pct,V(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning… ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
20
- `);try{let{runInit:e}=await import(`./init-CcjfJ0-a.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?V(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?V(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ii(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?V(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ii(e){let t=M(e,`.git`,`info`,`exclude`);if(!P(t))return`no-exclude`;let n=F(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
20
+ `);try{let{runInit:e}=await import(`./init-CfT911gp.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?V(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?V(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ii(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?V(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ii(e){let t=M(e,`.git`,`info`,`exclude`);if(!P(t))return`no-exclude`;let n=F(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
21
21
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(mt(t,`${n}${n.length===0||n.endsWith(`
22
22
  `)?``:`
23
- `}.ok/\n`,`utf-8`),`appended`)}function ai(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await ri(t,{json:r.json,dir:n},i);if(r.json)V(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BoXsjqPU.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?V(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const oi=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function si(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ci(e){let t=(0,At.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of oi)t.hasIn(e)&&n.push(e.join(`.`));return n}function li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ui(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=li(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function di(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,a=e.dryRun??!1,o=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Oe,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:ze(`project`,o,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:ze(`user`,o,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ci(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||a){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:o,scope:t,patch:ui(oi.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:i(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(a?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function fi(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{si({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await di({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var H=e(Qe(),1);const U=2e3,pi=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/];function mi(e){return pi.some(t=>t.test(e))}async function hi(){let e=j(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:U});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=gi(t);if(n.length>0||t.trim()===``)return n}let t=j(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:U});return t.error!=null||!t.stdout?[]:_i(t.stdout)}function gi(e){let t=[];for(let n of e.split(`
23
+ `}.ok/\n`,`utf-8`),`appended`)}function ai(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await ri(t,{json:r.json,dir:n},i);if(r.json)V(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BiFE3OLx.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?V(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const oi=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function si(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ci(e){let t=(0,At.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of oi)t.hasIn(e)&&n.push(e.join(`.`));return n}function li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ui(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=li(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function di(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,a=e.dryRun??!1,o=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Oe,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:ze(`project`,o,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:ze(`user`,o,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ci(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||a){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:o,scope:t,patch:ui(oi.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:i(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(a?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function fi(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{si({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await di({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var H=e(Qe(),1);const U=2e3,pi=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/];function mi(e){return pi.some(t=>t.test(e))}async function hi(){let e=j(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:U});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=gi(t);if(n.length>0||t.trim()===``)return n}let t=j(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:U});return t.error!=null||!t.stdout?[]:_i(t.stdout)}function gi(e){let t=[];for(let n of e.split(`
24
24
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&mi(a)&&t.push(o)}return t}function _i(e){let t=[],n=e.split(`
25
25
  `);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.indexOf(` `);if(i===-1)continue;let a=r.slice(0,i),o=r.slice(i+1).trim(),s=Number.parseInt(a,10);!Number.isNaN(s)&&mi(o)&&t.push(s)}return t}function vi(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=rt(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function yi(e){let t=j(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:U});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function bi(e){let t=j(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:U});if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}async function xi(e){let t=j(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:U});if(t.error!=null)return null;let n=t.stdout??``;for(let e of n.split(`
26
26
  `))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function Si(e){let t=[],n=e.split(`
@@ -56,12 +56,12 @@ setTimeout(() => process.exit(2), ${t+1e4});
56
56
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function so(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
57
57
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
58
58
  `&&r++}}return[t,n]}var co=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=oo({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const lo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var J=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},uo=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=qi(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??lo}async _authThenStart(){if(!this._authProvider)throw new q(`No auth provider`);let e;try{e=await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new q;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=Ki(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new J(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new co({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Me.parse(JSON.parse(e.data));Ce(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new q(`No auth provider`);if(await La(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new q(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ne(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new J(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Va(o);if(this._resourceMetadataUrl=t,this._scope=n,await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new q;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Va(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new J(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new q;return this.send(e)}}throw new J(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Ae(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Me.parse(e)):[Me.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new J(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new J(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function fo(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function po(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function mo(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function ho(e,t){return`http://${mo(e)}:${t}/mcp`}function go(e,t){return`ws://${mo(e)}:${t}`}function _o(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function vo(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function yo(e){return P(e)?F(e,`utf-8`).trim():``}function bo(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function xo(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function So(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function Co(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function wo(e){let t=e.readLock??(()=>fe(e.lockDir)),n=e.isAlive??T,r=e.sleep??(e=>Et(e)),i=e.spawn??tt,a=e.readErrorLog??yo,o=e.openErrorLog??(e=>lt(e,`w`)),s=e.closeFd??ot,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return ho(`localhost`,t)}let u=vo(t(),n);if(u!==void 0)return ho(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);P(e.lockDir)||st(e.lockDir,{recursive:!0});let d=M(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=Ke();try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`}}),p.on(`error`,e=>{m=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){m=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let g=Date.now()+c;for(;Date.now()<g;){if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}await r(l);let e=vo(t(),n);if(e!==void 0)return ho(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(bo(c,a(d)))}function To(e,t){if(e.portOverride!==void 0)return _o(t);let n=e.readLock??(()=>fe(e.lockDir)),r=e.isAlive??T,i=vo(n(),r);if(i!==void 0)return go(`localhost`,i)}async function Eo(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Wi(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new uo(new URL(e),{fetch:fo(r),...t.connectionId===void 0?{}:{requestInit:{headers:{[be]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let c=Promise.resolve();i.onmessage=e=>{c=c.then(async()=>{try{await a.send(e)}catch(t){let r=xo(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(Co(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=So(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function Do(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Eo,r=await wo(e),i=e.createConnectionId?.()??wt(),a=!1,o=(e.startKeepalive??Gi)({connectionId:i,resolveWsUrl:async()=>To(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}function Oo(e){let t=N(e);for(;;){if(ko(M(t,`.ok`)))return t;let n=it(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`.ok/\`).`);t=n}}function ko(e){try{return ft(e).isDirectory()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function Ao(e){try{let t=new URL(e);return t.protocol===`file:`?yt(t):void 0}catch{return}}async function jo(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Ao(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Mo(e,t){if(e!==void 0)return Oo(e);let n=await t();if(n!==void 0)return Oo(n);throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.")}async function No(e){let t=process.stderr,n=e.spawnTimeoutMs??po(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Ge({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new _e({name:ve,version:me},{instructions:Re({dir:`.`})}),o=wt(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=ke(e),r=Gi({connectionId:o,resolveWsUrl:async()=>To({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,r)},u=()=>jo({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d=e=>Mo(e,u),f=async e=>{let t;if(e===void 0){let e=await u();if(e===void 0)return;t=Oo(e)}else t=Oo(e);let a=await i(t),o=await wo({lockDir:ke(t),contentDir:Se(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(t),o.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Be(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},He(a,{serverUrl:f,resolveCwd:d,config:i,identityRef:s});let p=new Wi,m=!1,h=async()=>{if(m)return;m=!0;for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),p.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await a.connect(p),t.write(`[mcp] global stdio server ready (per-call project routing)
59
- `);let g=()=>{h().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,g),process.once(`SIGTERM`,g),{close:h}}function Po(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=po(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Do({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await No({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fo(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-GtCa8ObI.mjs`),r=e(),i=process.cwd(),a=Se(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Io(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Lo(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ro(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:vi(r),command:r,isDesktop:Io(r)}}function zo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Bo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&zo(e)?`ui-orphan`:`stale`}const Vo=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Ho(e){switch(e){case`running`:return H.default.green(e);case`desktop`:return H.default.blue(e);case`foreign`:return H.default.cyan(e);case`ui-orphan`:return H.default.magenta(e);case`stale`:return H.default.yellow(e)}}function Uo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Wo(e){return`${Uo(e.server.usage)} | ${Uo(e.ui?.usage??null)}`}function Go(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ko(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Bo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Go(e),Wo(e),t,String(n),Lo(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Ho(Bo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=H.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
59
+ `);let g=()=>{h().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,g),process.once(`SIGTERM`,g),{close:h}}function Po(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=po(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Do({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await No({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Fo(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-B14jfjgL.mjs`),r=e(),i=process.cwd(),a=Se(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Io(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Lo(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ro(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:vi(r),command:r,isDesktop:Io(r)}}function zo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Bo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&zo(e)?`ui-orphan`:`stale`}const Vo=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Ho(e){switch(e){case`running`:return H.default.green(e);case`desktop`:return H.default.blue(e);case`foreign`:return H.default.cyan(e);case`ui-orphan`:return H.default.magenta(e);case`stale`:return H.default.yellow(e)}}function Uo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Wo(e){return`${Uo(e.server.usage)} | ${Uo(e.ui?.usage??null)}`}function Go(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ko(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Bo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Go(e),Wo(e),t,String(n),Lo(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Ho(Bo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=H.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
60
60
  `)}async function qo(e={}){let t=e.discover??Ci,n=e.inspect??B,r=e.log??(e=>console.log(e)),i=e.resolveCommand??yi,a=e.resolveUsage??bi,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=Ro(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:Bo(e)}));r(JSON.stringify(e,null,2));return}r(Ko(e.all?s:s.filter(e=>Vo.has(Bo(e)))))}function Jo(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await qo({all:t.all===!0||e===`all`,json:t.json===!0})})}function Y(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Yo(e,t,n=process.cwd()){let r=e.op??`sync`,i=fe(De(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Y(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=he({baseDir:n});if(r===`sync`||r===`pull`){Y(e.json,{type:`step`,step:`pull`});let t=await a.pull();Y(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Y(e.json,{type:`step`,step:`push`}),await a.push(),Y(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
61
61
  `)),Y(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Xo(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yo({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Zo(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yo({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Qo(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yo({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function $o(e){return typeof e==`string`&&we.includes(e)}async function es(e={}){let t=N(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!je[n])return{status:`failed`,message:`${O(`Error:`)} Unknown pack "${n}". Available: ${we.join(`, `)}`,exitCode:1};let r;try{r=await ye({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof xe?{status:`prerequisite-missing`,message:`${O(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${O(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let t=je[n].name;if(e.personalTemplates&&!e.dryRun){let e=Ee();if(e.errors.length>0){let n=e.errors.map(e=>` ${k(`!`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${D(`Your ${t} pack is already seeded.`)}`,`${k(`Personal templates: some writes failed:`)}`,...n].join(`
62
62
  `),plan:r,exitCode:1}}let n=e.written.length;if(n>0)return{status:`applied`,message:`${D(`Your ${t} pack is already seeded.`)}\n${D(`✓ Wrote ${n} personal template${n===1?``:`s`}`)} ${E(`to ~/.ok/templates/`)}`,plan:r,exitCode:0}}return{status:`no-op`,message:`${D(`Your ${t} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${A(`Plan (dry-run — no changes made):`)}\n\n${ns(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await rs(`${A(`Plan:`)}\n\n${ns(r,t)}\n\n${A(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:r,exitCode:0};let i=await ge(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${O(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${k(`Applied`)} ${i.applied} entries, ${k(String(i.errors.length))} error(s):`,...e].join(`
63
63
  `),plan:r,exitCode:1}}let a=``;if(e.personalTemplates){let e=Ee();if(e.written.length>0)a=`\n${D(`✓ Wrote ${e.written.length} personal template(s)`)} ${E(`to ~/.ok/templates/`)}`;else if(e.errors.length===0)a=`\n${E(`Personal templates already present — skipped.`)}`;else{let t=e.errors.map(e=>` ${k(`!`)} ${e.path}: ${e.error}`);a=`\n${k(`Personal templates: errors:`)}\n${t.join(`
64
64
  `)}`}}let o=je[n].name;return{status:`applied`,message:`${D(`✓ Seeded ${o}`)} ${E(`(${i.applied} entries, ${i.durationMs}ms)`)}${a}`,plan:r,exitCode:0}}function ts(){let e=[A(`Available packs:`)];for(let t of we){let n=je[t];e.push(` ${D(t)} ${E(`—`)} ${n.name}: ${n.description}`)}return e.join(`
65
65
  `)}function ns(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(A(`Folders to create:`));for(let e of r)n.push(` ${D(`+`)} ${$e(at(t,N(t,e.path))||e.path)}${E(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(A(`Files to create:`));for(let e of i)n.push(` ${D(`+`)} ${$e(at(t,N(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(E(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${E(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(k(`Warnings:`));for(let t of e.warnings)n.push(` ${k(`!`)} ${t}`)}return n.join(`
66
- `)}async function rs(e,t){let n=kt({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function is(){return new t(`seed`).description(`Scaffold a starter pack into the project. Defaults to "${Ie}" — the Karpathy three-layer knowledge base. Use --pack to pick a different pack (run with --list-packs to see all). Use --root to place pack folders inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-p, --pack <id>`,`Starter pack to scaffold. One of: ${we.join(`, `)}. Defaults to "${Ie}".`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`--personal-templates`,`Also write the personal-templates pack (daily journal, reading log, etc.) to ~/.ok/templates/ — idempotent.`).option(`--list-packs`,`List available starter packs and exit.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{if(t.listPacks){process.stdout.write(`${ts()}\n`);return}if(t.pack!==void 0&&!$o(t.pack)){process.stderr.write(`${O(`Error:`)} Unknown pack "${t.pack}". Available: ${we.join(`, `)}\n`),process.exitCode=1;return}let n=await es({cwd:e??process.cwd(),pack:t.pack,root:t.root,personalTemplates:t.personalTemplates,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function as(e,t){return{server:os(`server`,e),ui:os(`ui`,t)}}function os(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 ss(e){return`${cs(e.server)}\n${cs(e.ui)}`}function cs(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 ls(e){let t=e.inspect??(t=>B(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=as(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(ss(r)),r}function us(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),ls({lockDir:De(process.cwd()),json:t.json===!0})})}function ds(e,t,n={}){let r=n.isAlive??T,i=[];for(let[n,a]of[[`server`,e],[`ui`,t]])(a.status===`alive`||a.status===`foreign-host`&&r(a.lock.pid))&&i.push({name:n,pid:a.lock.pid,port:a.lock.port});return{targets:i}}function fs(e){let t=e.inspect??(t=>B(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=ds(t(`server`),t(`ui`),{isAlive:e.isAlive});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 X(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function ps(e,t=T){let n=await Ci(),r=null;for(let i of n){let n=B(i,`server`),a=B(i,`ui`);if(X(n,t)&&n.lock.port===e||X(a,t)&&a.lock.port===e)return i;r===null&&(X(n,t)&&n.lock.pid===e||X(a,t)&&a.lock.pid===e)&&(r=i)}return r}function ms(e){let t=fs({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function hs(e){return new t(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=fs({lockDir:De(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await qo({});return}if(n===`all`){let e=await Ci();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=B(n,`server`),r=B(n,`ui`);!X(e,T)&&!X(r,T)||(ms(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await ps(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}ms(t);return}ms(De(n))})}function Z(e,t,n,r,i){let a=`urn:uuid:${wt()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},c=s.safeParse(o);if(!c.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:c.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const gs=1e4;function _s(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!Ve(n))return Z(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!Le(e.headers.host))return Z(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!Pe(r)?(Z(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const vs=3e4,ys=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function bs(e){let t=e.upstreamTimeoutMs??gs,n=Dt((n,r)=>{_s(n,r)||Ss(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 xs(e,t,n){Ss(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??gs)}function Ss(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of ys)delete a[e];e.setTimeout(vs,()=>{if(t.headersSent)try{t.end()}catch{}else try{Z(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${vs/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=Ot({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of ys)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)Z(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)Z(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Cs(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ws(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:a,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BjlSvO5w.mjs`),{default:f}=await import(`./build-GAD37AZK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-BjlSvO5w.mjs`),g=p(e.config,e.cwd),_=h(e.cwd);i(_,{port:0,worktreeRoot:e.cwd});let v=import.meta.dirname??new URL(`.`,import.meta.url).pathname,y=[r(v,`public`),r(v,`../../app/dist`),r(v,`../../../app/dist`)].find(e=>t(e)),b=y?f(y,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,x=t(g)?a({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:f(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:m,assetExtensions:ee,blocklistExtensions:d}):null,S=e.port,te=null,C=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&_s(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){te?.();let n=c(_),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:S});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/`)){te?.();let r=c(_);if(!r||r.port<=0){Z(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}xs(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(x){x(e,t,()=>{b?b(e,t):Ts(t,n)});return}if(b){b(e,t);return}Ts(t,n)}},ne=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],re=[],ie=e.port;try{for(let e of ne){let t=n(C);re.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ie,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ie=e.port),n()})})}}catch(e){await Promise.all(re.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(_)}catch{}throw e}let ae=ie;S=ae,u(_,ae);let oe=e.scheduler??o,se=e.safetyNetMs??432e5,w=null,ce=!1,le=!1,ue=()=>{ce||(ce=!0,w!==null&&(oe.clearTimeout(w),w=null))},de=()=>{if(ue(),!le){le=!0;try{l(_)}catch{}}},fe=()=>{ce||se<=0||(w!==null&&(oe.clearTimeout(w),w=null),w=oe.setTimeout(()=>{w=null,console.warn(`[ui] safety-net (${se}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of re)try{e.close()}catch{}de()},se))},pe=()=>{ce||se<=0||fe()};return te=pe,fe(),{httpServers:re,port:ae,release:de,detachSafetyNet:ue,nudgeSafetyNet:pe}}function Ts(e,t){Z(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Es(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 Ds(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BjlSvO5w.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 bs({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Os(e){return new t(`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-BCE2jNgl.mjs`),{UiLockCollisionError:r}=await import(`./dist-BjlSvO5w.mjs`),{resolveLockDir:i}=await import(`./dist-BjlSvO5w.mjs`),a=e(),o=t.host,s;try{s=Es(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ws({config:a,cwd:process.cwd(),port:s,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Cs(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,c;try{c=await Ds({requestedPort:s,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}c.mode===`already-running`&&(console.log(`UI already running at http://${a}:${c.port}`),process.exit(0)),console.log(`UI running at http://${a}:${c.upstreamPort}; acting as HTTP proxy on port ${c.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),c.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(Ue).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;t!==void 0&&process.chdir(t);let{config:n}=We(t);$=n}),Q.action(async()=>{if(Xe(qe()).available){Ye({spawn:tt});return}await Ze($,{})});const ks=Je(()=>$);Q.addCommand(ks);const As=Po(()=>$);Q.addCommand(As),Q.addCommand(se()),Q.addCommand(is()),Q.addCommand(Bi());const js=Fo(()=>$);Q.addCommand(js);const Ms=Os(()=>$);Q.addCommand(Ms),Q.addCommand(hs(()=>$)),Q.addCommand(Xr(()=>$)),Q.addCommand(us(()=>$)),Q.addCommand(Jo()),Q.addCommand(Mi()),Q.addCommand(fi()),Q.addCommand(qr()),Q.addCommand(ai(()=>$)),Q.addCommand(Xo(()=>$)),Q.addCommand(Qo(()=>$)),Q.addCommand(Zo(()=>$)),await Q.parseAsync(process.argv,{from:`node`});export{};
66
+ `)}async function rs(e,t){let n=kt({input:t??process.stdin,output:process.stdout});try{let t=(await n.question(e)).trim().toLowerCase();return t===``||t===`y`||t===`yes`}finally{n.close()}}function is(){return new t(`seed`).description(`Scaffold a starter pack into the project. Defaults to "${Ie}" — the Karpathy three-layer knowledge base. Use --pack to pick a different pack (run with --list-packs to see all). Use --root to place pack folders inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).option(`-p, --pack <id>`,`Starter pack to scaffold. One of: ${we.join(`, `)}. Defaults to "${Ie}".`).option(`-r, --root <path>`,`Subfolder (relative to the project dir) to scaffold into — created if missing. Defaults to the project root when omitted in non-interactive runs; prompts on a TTY.`).option(`--personal-templates`,`Also write the personal-templates pack (daily journal, reading log, etc.) to ~/.ok/templates/ — idempotent.`).option(`--list-packs`,`List available starter packs and exit.`).option(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{if(t.listPacks){process.stdout.write(`${ts()}\n`);return}if(t.pack!==void 0&&!$o(t.pack)){process.stderr.write(`${O(`Error:`)} Unknown pack "${t.pack}". Available: ${we.join(`, `)}\n`),process.exitCode=1;return}let n=await es({cwd:e??process.cwd(),pack:t.pack,root:t.root,personalTemplates:t.personalTemplates,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function as(e,t){return{server:os(`server`,e),ui:os(`ui`,t)}}function os(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 ss(e){return`${cs(e.server)}\n${cs(e.ui)}`}function cs(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 ls(e){let t=e.inspect??(t=>B(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=as(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(ss(r)),r}function us(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),ls({lockDir:De(process.cwd()),json:t.json===!0})})}function ds(e,t,n={}){let r=n.isAlive??T,i=[];for(let[n,a]of[[`server`,e],[`ui`,t]])(a.status===`alive`||a.status===`foreign-host`&&r(a.lock.pid))&&i.push({name:n,pid:a.lock.pid,port:a.lock.port});return{targets:i}}function fs(e){let t=e.inspect??(t=>B(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=ds(t(`server`),t(`ui`),{isAlive:e.isAlive});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 X(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function ps(e,t=T){let n=await Ci(),r=null;for(let i of n){let n=B(i,`server`),a=B(i,`ui`);if(X(n,t)&&n.lock.port===e||X(a,t)&&a.lock.port===e)return i;r===null&&(X(n,t)&&n.lock.pid===e||X(a,t)&&a.lock.pid===e)&&(r=i)}return r}function ms(e){let t=fs({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function hs(e){return new t(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=fs({lockDir:De(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await qo({});return}if(n===`all`){let e=await Ci();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=B(n,`server`),r=B(n,`ui`);!X(e,T)&&!X(r,T)||(ms(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await ps(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}ms(t);return}ms(De(n))})}function Z(e,t,n,r,i){let a=`urn:uuid:${wt()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},c=s.safeParse(o);if(!c.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:c.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const gs=1e4;function _s(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!Ve(n))return Z(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!Le(e.headers.host))return Z(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!Pe(r)?(Z(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const vs=3e4,ys=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function bs(e){let t=e.upstreamTimeoutMs??gs,n=Dt((n,r)=>{_s(n,r)||Ss(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 xs(e,t,n){Ss(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??gs)}function Ss(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of ys)delete a[e];e.setTimeout(vs,()=>{if(t.headersSent)try{t.end()}catch{}else try{Z(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${vs/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=Ot({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of ys)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)Z(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)Z(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Cs(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ws(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:a,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BXmbRKLs.mjs`),{default:f}=await import(`./build-GAD37AZK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-BXmbRKLs.mjs`),g=p(e.config,e.cwd),_=h(e.cwd);i(_,{port:0,worktreeRoot:e.cwd});let v=import.meta.dirname??new URL(`.`,import.meta.url).pathname,y=[r(v,`public`),r(v,`../../app/dist`),r(v,`../../../app/dist`)].find(e=>t(e)),b=y?f(y,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,x=t(g)?a({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:f(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:m,assetExtensions:ee,blocklistExtensions:d}):null,S=e.port,te=null,C=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&_s(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){te?.();let n=c(_),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:S});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/`)){te?.();let r=c(_);if(!r||r.port<=0){Z(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}xs(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(x){x(e,t,()=>{b?b(e,t):Ts(t,n)});return}if(b){b(e,t);return}Ts(t,n)}},ne=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],re=[],ie=e.port;try{for(let e of ne){let t=n(C);re.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ie,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ie=e.port),n()})})}}catch(e){await Promise.all(re.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(_)}catch{}throw e}let ae=ie;S=ae,u(_,ae);let oe=e.scheduler??o,se=e.safetyNetMs??432e5,w=null,ce=!1,le=!1,ue=()=>{ce||(ce=!0,w!==null&&(oe.clearTimeout(w),w=null))},de=()=>{if(ue(),!le){le=!0;try{l(_)}catch{}}},fe=()=>{ce||se<=0||(w!==null&&(oe.clearTimeout(w),w=null),w=oe.setTimeout(()=>{w=null,console.warn(`[ui] safety-net (${se}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of re)try{e.close()}catch{}de()},se))},pe=()=>{ce||se<=0||fe()};return te=pe,fe(),{httpServers:re,port:ae,release:de,detachSafetyNet:ue,nudgeSafetyNet:pe}}function Ts(e,t){Z(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Es(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 Ds(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BXmbRKLs.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 bs({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Os(e){return new t(`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-BCE2jNgl.mjs`),{UiLockCollisionError:r}=await import(`./dist-BXmbRKLs.mjs`),{resolveLockDir:i}=await import(`./dist-BXmbRKLs.mjs`),a=e(),o=t.host,s;try{s=Es(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await ws({config:a,cwd:process.cwd(),port:s,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Cs(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,c;try{c=await Ds({requestedPort:s,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}c.mode===`already-running`&&(console.log(`UI already running at http://${a}:${c.port}`),process.exit(0)),console.log(`UI running at http://${a}:${c.upstreamPort}; acting as HTTP proxy on port ${c.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),c.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(Ue).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;t!==void 0&&process.chdir(t);let{config:n}=We(t);$=n}),Q.action(async()=>{if(Xe(qe()).available){Ye({spawn:tt});return}await Ze($,{})});const ks=Je(()=>$);Q.addCommand(ks);const As=Po(()=>$);Q.addCommand(As),Q.addCommand(se()),Q.addCommand(is()),Q.addCommand(Bi());const js=Fo(()=>$);Q.addCommand(js);const Ms=Os(()=>$);Q.addCommand(Ms),Q.addCommand(hs(()=>$)),Q.addCommand(Xr(()=>$)),Q.addCommand(us(()=>$)),Q.addCommand(Jo()),Q.addCommand(Mi()),Q.addCommand(fi()),Q.addCommand(qr()),Q.addCommand(ai(()=>$)),Q.addCommand(Xo(()=>$)),Q.addCommand(Qo(()=>$)),Q.addCommand(Zo(()=>$)),await Q.parseAsync(process.argv,{from:`node`});export{};
67
67
  //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./dist-k62w-4-v.mjs";var e=`0.4.0-beta.34`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-BgI7SDCI.mjs.map
@@ -1 +1 @@
1
- import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-k62w-4-v.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-Bfw3oOGm.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};
1
+ import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-k62w-4-v.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-BaVVyZsg.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};