@inkeep/open-knowledge 0.0.0-dev-20260428021930 → 0.0.0-dev-20260428024726

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 (39) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/dist/constants-Bypdthtt.mjs +2 -0
  3. package/dist/{dist-BWvkug8h.mjs → dist-BW0CmwMf.mjs} +2 -2
  4. package/dist/{dist-Bx5GgBdJ.mjs → dist-CUNdZ2_C.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-C9NcluI6.mjs +1 -0
  7. package/dist/{init-C6cjLUFz.mjs → init-DT5HolXi.mjs} +3 -3
  8. package/dist/init-GJP2EVzJ.mjs +1 -0
  9. package/dist/{init-CzZhMVnY.mjs → init-rEg7vsQo.mjs} +2 -2
  10. package/dist/{loader-CPc-aW4O.mjs → loader-G-_WDqR0.mjs} +2 -2
  11. package/dist/loader-LG3X7RJ0.mjs +1 -0
  12. package/dist/paths-DfUzFdTC.mjs +1 -0
  13. package/dist/{paths-BpTFy0jY.mjs → paths-YqCzdIxh.mjs} +2 -2
  14. package/dist/preview-1YeKX_ki.mjs +1 -0
  15. package/dist/{preview-D0LnqCdK.mjs → preview-ByA3Zxgf.mjs} +2 -2
  16. package/dist/public/assets/{ActivityModeContent-8j8yoFNR.js → ActivityModeContent-QSE28ToP.js} +1 -1
  17. package/dist/public/assets/{DocumentContext-CRsKuypY.js → DocumentContext-C7zXwLGg.js} +1 -1
  18. package/dist/public/assets/{GraphPanel-nC0tek4D.js → GraphPanel-B9s5n-VJ.js} +1 -1
  19. package/dist/public/assets/McpConsentDialogBody-FBruOF3J.js +1 -0
  20. package/dist/public/assets/{PageListContext-BeAv6YTY.js → PageListContext-DNRRECTw.js} +21 -21
  21. package/dist/public/assets/{SourceEditor-Cr2CUBTn.js → SourceEditor-B5_U1uud.js} +1 -1
  22. package/dist/public/assets/{clipboard-CokCqXWa.js → clipboard-BcHcwwH2.js} +1 -1
  23. package/dist/public/assets/{index-CfjCKbN6.js → index-CfLPPlu0.js} +8 -8
  24. package/dist/public/assets/{toggle-group-ClhkYZ6-.js → toggle-group-akWK7-wE.js} +1 -1
  25. package/dist/public/assets/{tooltip-BAEC-KjA.js → tooltip-nCu_fYrg.js} +1 -1
  26. package/dist/public/index.html +6 -6
  27. package/dist/src-5CKdfahI.mjs +1 -0
  28. package/dist/{start-BiBFA2tc.mjs → start-BXOGxEm7.mjs} +2 -2
  29. package/dist/start-DJ47R0B2.mjs +1 -0
  30. package/package.json +1 -1
  31. package/dist/constants-DWQfpDRU.mjs +0 -2
  32. package/dist/init-BrdLKYwH.mjs +0 -1
  33. package/dist/init-CLz5m9aU.mjs +0 -1
  34. package/dist/loader-Dv6yC7sh.mjs +0 -1
  35. package/dist/paths-BH3t9_kz.mjs +0 -1
  36. package/dist/preview-S0e7r-4X.mjs +0 -1
  37. package/dist/public/assets/McpConsentDialogBody-CDgbvt5r.js +0 -1
  38. package/dist/src-BeVEUOH4.mjs +0 -1
  39. package/dist/start-CArB0f_G.mjs +0 -1
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-29fM6BBO.mjs";import{t as i}from"./dist-BCyi1oM7.mjs";import{n as a,r as o,t as s}from"./dist-bundle-BSdjl7Rj.mjs";import{i as c,r as l}from"./constants-DWQfpDRU.mjs";import{$ as u,B as d,G as f,H as p,I as m,J as h,K as g,L as _,Q as v,R as y,S as b,U as x,V as S,W as C,X as w,Y as ee,Z as T,at as E,ct as te,dt as ne,ft as re,lt as ie,m as ae,mt as oe,nt as se,ot as ce,p as le,pt as ue,q as D,st as de,tt as fe,ut as pe,z as O}from"./dist-DRC09WNZ.mjs";import{n as me,t as he}from"./paths-BpTFy0jY.mjs";import{a as ge,c as _e,o as ve}from"./server-lock-CH0GCP_4-DXqutMlt.mjs";import{i as ye}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{Jt as be,Kt as xe,O as Se,S as Ce,Xt as we,Yt as Te,gt as Ee,j as De,qt as Oe,vt as ke}from"./dist-BWvkug8h.mjs";import{r as Ae}from"./init-C6cjLUFz.mjs";import{i as je,n as Me,o as Ne,r as Pe,s as Fe,t as Ie}from"./colors-DoPZvo1q.mjs";import{t as Le}from"./is-object-BNVklKxg.mjs";import{i as Re,n as ze,t as Be}from"./loader-CPc-aW4O.mjs";import{t as Ve}from"./chunk-YNYSPYQ5-BpP11HXS.mjs";import{a as He,c as Ue,d as We,f as Ge,h as Ke,i as qe,l as Je,m as Ye,n as Xe,o as Ze,p as Qe,r as $e,s as et,t as tt,u as nt}from"./chunk-GFQRA5P5-1fzItQ8F.mjs";import{A as rt,B as it,C as at,D as ot,E as st,F as ct,H as lt,I as ut,L as dt,M as ft,N as pt,O as mt,P as ht,S as gt,T as _t,V as vt,_ as yt,a as bt,b as xt,c as St,d as Ct,f as k,g as wt,h as Tt,i as Et,j as Dt,k as Ot,l as kt,m as At,n as jt,o as Mt,p as Nt,r as Pt,s as Ft,t as It,u as Lt,v as Rt,w as zt,x as Bt,y as Vt,z as Ht}from"./chunk-FEIOJCZD-C4x0A4rb.mjs";import{a as Ut,c as Wt,d as Gt,i as Kt,l as qt,n as Jt,o as Yt,r as Xt,s as A,t as Zt,u as Qt}from"./chunk-XHM67O4N-Cg35xc6b.mjs";import{n as $t,r as en,t as tn}from"./chunk-R6VWJ2ZL-B0CcMPyK.mjs";import{r as nn}from"./chunk-CWQS3NFK-DFdwmFxJ.mjs";import"./chunk-DXB73IDG-C774okS0.mjs";import{n as rn,t as an}from"./chunk-5QMZ5MUS-DWTkM0vM.mjs";import{n as on,t as sn}from"./chunk-A5O5YHGN-C7BVq0eF.mjs";import{n as cn,r as ln,t as un}from"./chunk-OJDRYQWQ-BV5MVRVg.mjs";import{r as dn,t as fn}from"./chunk-24IMIIXA-Bz7rlZT3.mjs";import{n as pn}from"./chunk-3THT3N7L-klp8GP84.mjs";import{t as mn}from"./chunk-44UOCSGV-BUBpWxXm.mjs";import{o as hn,s as gn}from"./start-BiBFA2tc.mjs";import"./src-BeVEUOH4.mjs";import{execFileSync as _n,spawn as vn}from"node:child_process";import*as yn from"node:path";import bn,{basename as xn,dirname as Sn,isAbsolute as Cn,join as wn,relative as Tn,resolve as En}from"node:path";import*as j from"node:fs";import{appendFileSync as Dn,closeSync as On,existsSync as kn,mkdirSync as An,openSync as jn,readFileSync as Mn,readdirSync as Nn,realpathSync as Pn,statSync as Fn,unlinkSync as In,writeFileSync as Ln}from"node:fs";import Rn from"node:process";import{homedir as zn,hostname as Bn,platform as Vn}from"node:os";import{AsyncLocalStorage as Hn,AsyncResource as Un}from"node:async_hooks";import{stripVTControlCharacters as Wn,styleText as Gn}from"node:util";import*as Kn from"node:readline";import{fileURLToPath as qn}from"node:url";import{randomUUID as Jn}from"node:crypto";import{mkdir as Yn,readFile as Xn,readdir as Zn,stat as Qn}from"node:fs/promises";import{createServer as $n,request as er}from"node:http";import{lookup as tr}from"node:dns";import{createInterface as nr}from"node:readline/promises";var rr=i();const ir=`open-knowledge`;var ar=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(ir,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(ir,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(ir,e).deletePassword()}catch{}}},or=class{backend=`file`;authFile;constructor(e){this.authFile=e??wn(zn(),`.open-knowledge`,`auth.yml`)}read(){if(!kn(this.authFile))return{};try{return(0,rr.parse)(Mn(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=Sn(this.authFile);kn(t)||An(t,{recursive:!0,mode:448}),Ln(this.authFile,(0,rr.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 sr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(ir,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-29fM6BBO.mjs";import{t as i}from"./dist-BCyi1oM7.mjs";import{n as a,r as o,t as s}from"./dist-bundle-BSdjl7Rj.mjs";import{i as c,r as l}from"./constants-Bypdthtt.mjs";import{$ as u,B as d,G as f,H as p,I as m,J as h,K as g,L as _,Q as v,R as y,S as b,U as x,V as S,W as C,X as w,Y as ee,Z as T,at as E,ct as te,dt as ne,ft as re,lt as ie,m as ae,mt as oe,nt as se,ot as ce,p as le,pt as ue,q as D,st as de,tt as fe,ut as pe,z as O}from"./dist-DRC09WNZ.mjs";import{n as me,t as he}from"./paths-YqCzdIxh.mjs";import{a as ge,c as _e,o as ve}from"./server-lock-CH0GCP_4-DXqutMlt.mjs";import{i as ye}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{Jt as be,Kt as xe,O as Se,S as Ce,Xt as we,Yt as Te,gt as Ee,j as De,qt as Oe,vt as ke}from"./dist-BW0CmwMf.mjs";import{r as Ae}from"./init-DT5HolXi.mjs";import{i as je,n as Me,o as Ne,r as Pe,s as Fe,t as Ie}from"./colors-DoPZvo1q.mjs";import{t as Le}from"./is-object-BNVklKxg.mjs";import{i as Re,n as ze,t as Be}from"./loader-G-_WDqR0.mjs";import{t as Ve}from"./chunk-YNYSPYQ5-BpP11HXS.mjs";import{a as He,c as Ue,d as We,f as Ge,h as Ke,i as qe,l as Je,m as Ye,n as Xe,o as Ze,p as Qe,r as $e,s as et,t as tt,u as nt}from"./chunk-GFQRA5P5-1fzItQ8F.mjs";import{A as rt,B as it,C as at,D as ot,E as st,F as ct,H as lt,I as ut,L as dt,M as ft,N as pt,O as mt,P as ht,S as gt,T as _t,V as vt,_ as yt,a as bt,b as xt,c as St,d as Ct,f as k,g as wt,h as Tt,i as Et,j as Dt,k as Ot,l as kt,m as At,n as jt,o as Mt,p as Nt,r as Pt,s as Ft,t as It,u as Lt,v as Rt,w as zt,x as Bt,y as Vt,z as Ht}from"./chunk-FEIOJCZD-C4x0A4rb.mjs";import{a as Ut,c as Wt,d as Gt,i as Kt,l as qt,n as Jt,o as Yt,r as Xt,s as A,t as Zt,u as Qt}from"./chunk-XHM67O4N-Cg35xc6b.mjs";import{n as $t,r as en,t as tn}from"./chunk-R6VWJ2ZL-B0CcMPyK.mjs";import{r as nn}from"./chunk-CWQS3NFK-DFdwmFxJ.mjs";import"./chunk-DXB73IDG-C774okS0.mjs";import{n as rn,t as an}from"./chunk-5QMZ5MUS-DWTkM0vM.mjs";import{n as on,t as sn}from"./chunk-A5O5YHGN-C7BVq0eF.mjs";import{n as cn,r as ln,t as un}from"./chunk-OJDRYQWQ-BV5MVRVg.mjs";import{r as dn,t as fn}from"./chunk-24IMIIXA-Bz7rlZT3.mjs";import{n as pn}from"./chunk-3THT3N7L-klp8GP84.mjs";import{t as mn}from"./chunk-44UOCSGV-BUBpWxXm.mjs";import{o as hn,s as gn}from"./start-BXOGxEm7.mjs";import"./src-5CKdfahI.mjs";import{execFileSync as _n,spawn as vn}from"node:child_process";import*as yn from"node:path";import bn,{basename as xn,dirname as Sn,isAbsolute as Cn,join as wn,relative as Tn,resolve as En}from"node:path";import*as j from"node:fs";import{appendFileSync as Dn,closeSync as On,existsSync as kn,mkdirSync as An,openSync as jn,readFileSync as Mn,readdirSync as Nn,realpathSync as Pn,statSync as Fn,unlinkSync as In,writeFileSync as Ln}from"node:fs";import Rn from"node:process";import{homedir as zn,hostname as Bn,platform as Vn}from"node:os";import{AsyncLocalStorage as Hn,AsyncResource as Un}from"node:async_hooks";import{stripVTControlCharacters as Wn,styleText as Gn}from"node:util";import*as Kn from"node:readline";import{fileURLToPath as qn}from"node:url";import{randomUUID as Jn}from"node:crypto";import{mkdir as Yn,readFile as Xn,readdir as Zn,stat as Qn}from"node:fs/promises";import{createServer as $n,request as er}from"node:http";import{lookup as tr}from"node:dns";import{createInterface as nr}from"node:readline/promises";var rr=i();const ir=`open-knowledge`;var ar=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(ir,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(ir,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(ir,e).deletePassword()}catch{}}},or=class{backend=`file`;authFile;constructor(e){this.authFile=e??wn(zn(),`.open-knowledge`,`auth.yml`)}read(){if(!kn(this.authFile))return{};try{return(0,rr.parse)(Mn(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=Sn(this.authFile);kn(t)||An(t,{recursive:!0,mode:448}),Ln(this.authFile,(0,rr.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 sr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(ir,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new ar}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new or(e)}}async function cr(e,t,n){let r=lr(await ur(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 lr(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 ur(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 dr(e){let t=new r(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await cr(process.stdin,process.stdout,t);process.exit(n)}),t}function fr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function pr(e,t,n){let r={baseUrl:fr(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new a(`${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 mr(e){let t=e.request||s,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),pr(t,`POST /login/device/code`,n)}async function hr(e){let t=await pr(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=gr(e,t.data.expires_in),n.refreshTokenExpiresAt=gr(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function gr(e,t){return new Date(e+t*1e3).toISOString()}async function _r(e,t){let n=vr(e,t.auth);if(n)return n;let{data:r}=await mr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await br(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function vr(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 yr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function br(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await hr({...i,clientType:`oauth-app`}):await hr({...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 yr(r.interval),br(e,t,n,r);if(a===`slow_down`)return await yr(r.interval+7),br(e,t,n,r);throw i}}async function xr(e,t){return _r(e,{auth:t})}async function Sr(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 _r(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Cr=`0.0.0-development`;function wr(e){let t=e.request||s.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Cr} ${o()}`}}),{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(xr.bind(null,i),{hook:Sr.bind(null,i)})}async function Tr(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=wr({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??[]}}function Er(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const Dr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Or(e){let t=e.toLowerCase().replace(/:\d+$/,``);Dr.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 kr(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ar(e,t,n,r=Tr){let i=Er(n),{host:a,json:o}=e;Or(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?kr(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?kr(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function jr(e,t){return new r(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await Ar(n,await t(),e())})}const Mr=e=>e.name===`enter`||e.name===`return`;var Nr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Pr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Fr=class extends Error{name=`ExitPromptError`},Ir=class extends Error{name=`HookError`},Lr=class extends Error{name=`ValidationError`};const Rr=new Hn;function zr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Br(e,t){let n=zr(e);return Rr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function Vr(){let e=Rr.getStore();if(!e)throw new Ir(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Hr(){return Vr().rl}function Ur(e){return Un.bind((...t)=>{let n=Vr(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Wr(e){let t=Vr(),{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 Gr(){Vr().handleChange()}const Kr={queue(e){let t=Vr(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Hr());if(r!=null&&typeof r!=`function`)throw new Lr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=Vr();Ur(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=Vr();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function qr(e){return typeof e==`function`}function Jr(e){return Wr(t=>{let n=Un.bind(function(e){t.get()!==e&&(t.set(e),Gr())});if(t.initialized)return[t.get(),n];let r=qr(e)?e():e;return t.set(r),[r,n]})}function Yr(e,t){Wr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Kr.queue(e),n.set(t)})}function Xr(){return Rn.platform.startsWith(`win`)?!!Rn.env.CI||!!Rn.env.WT_SESSION||!!Rn.env.TERMINUS_SUBLIME||Rn.env.ConEmuTask===`{cmd::Cmder}`||Rn.env.TERM_PROGRAM===`Terminus-Sublime`||Rn.env.TERM_PROGRAM===`vscode`||Rn.env.TERM===`xterm-256color`||Rn.env.TERM===`alacritty`||Rn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:Rn.env.TERM!==`linux`}const Zr={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},Qr={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},$r={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ei={...Zr,...Qr},ti={...Zr,...$r},ni=Xr()?ei:ti;Object.entries(Qr);const ri={prefix:{idle:Gn(`blue`,`?`),done:Gn(`green`,ni.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>Gn(`yellow`,e))},style:{answer:e=>Gn(`cyan`,e),message:e=>Gn(`bold`,e),error:e=>Gn(`red`,`> ${e}`),defaultAnswer:e=>Gn(`dim`,`(${e})`),help:e=>Gn(`dim`,e),highlight:e=>Gn(`cyan`,e),key:e=>Gn(`cyan`,Gn(`bold`,`<${e}>`))}};function ii(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 ai(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ii(n)&&ii(r)?ai(n,r):r}return t}function oi(...e){return ai(ri,...e.filter(e=>e!=null))}function si({status:e=`idle`,theme:t}){let[n,r]=Jr(!1),[i,a]=Jr(0),{prefix:o,spinner:s}=oi(t);return Yr(()=>{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 ci(e){return Jr({current:e})[0]}function li(e){let t=ci(e);t.current=e,Yr(e=>{let n=!1,r=Ur((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var ui=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const di=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),fi=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,pi=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,mi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,hi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,gi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,_i=/\t{1,1000}/y,vi=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,yi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,bi=/\p{M}+/gu,xi={limit:1/0,ellipsis:``},Si=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Si(i,xi,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[yi,l],[mi,0],[hi,o],[_i,s],[vi,c],[gi,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(bi,``)){let t=e.codePointAt(0)||0;if(S=fi(t)?2:pi(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===gi?di(e.slice(p,n.lastIndex)):n===vi?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Ci={limit:1/0,ellipsis:``,ellipsisWidth:0},wi=(e,t={})=>Si(e,Ci,t).width,Ti=`]8;;`,Ei=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ti}(?<uri>.*))`,`y`),Di=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Oi=e=>`[${e}m`,ki=e=>`${Ti}${e}`,Ai=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:wi(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=wi(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ti,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},ji=e=>{let t=e.split(` `),n=t.length;for(;n&&!wi(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Mi=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=wi(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=wi(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ai(s,r,t),c=wi(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ai(s,r,t),c=wi(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ai(s,r,t),c=wi(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>ji(e)));let l=s.join(`
@@ -21,7 +21,7 @@ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-
21
21
  `),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 uo(e){return new r(`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 lo(t,await e())})}async function fo(e,t){let{host:n,json:r}=e;Or(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 co({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 po(e){return new r(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await fo(t,await e())})}async function mo(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function ho(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await mo(t,await e())})}async function go(e,t){let{host:n,json:r}=e;Or(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 co({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`})+`
22
22
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function _o(e){return new r(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await go(t,await e())})}function vo(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>sr(),i=e??(()=>({}));return t.addCommand(jr(i,n)),t.addCommand(_o(n)),t.addCommand(po(n)),t.addCommand(ho(n)),t.addCommand(uo(n)),t.addCommand(dr(n)),t}function yo(e,t,n={}){let r=ve(e,t);if(!kn(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Mn(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??Bn();return a.hostname===o?(n.isAlive??ge)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function bo(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 xo(e){let t=e.inspect??(t=>yo(e.lockDir,t)),n=e.unlink??(e=>In(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=bo(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 So(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{xo({lockDir:me(he(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function Co(){try{let e=_n(`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 wo(e,t,n={},r=Co){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 To(e){return e.replace(/:\d+$/,``)}function Eo(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:To(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:To(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:To(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 Do=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Oo(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 Do)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function ko(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Ao(e,t,n,r=process.cwd()){let i=Eo(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?En(r,t.dir):En(r,i.name);if(kn(a)&&Nn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await sr(),s=await wo(i.hostname,o,{}),c=ye({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;if(c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
23
23
  `)){let n=Oo(e);n&&n.pct!==l&&(l=n.pct,ko(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(`
24
- `),!kn(En(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-CLz5m9aU.mjs`),import(`./init-BrdLKYwH.mjs`)]);await e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function jo(e){return new r(`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 Ao(t,{json:r.json,dir:n},i);if(r.json)ko(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CArB0f_G.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?ko(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}function Mo(e=zn()){return wn(e,`Downloads`,`openknowledge.skill`)}function No(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function Po(e={}){let t=En(e.out??Mo()),n=e.platformName??Vn(),r=e.spawnFn??vn;try{await Yn(Sn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Pe(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await De({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Pe(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ne(`Built ${i.outputPath}`),Me(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),je(` Open the Claude Desktop App, then: ${Ie(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
24
+ `),!kn(En(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-C9NcluI6.mjs`),import(`./init-GJP2EVzJ.mjs`)]);await e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function jo(e){return new r(`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 Ao(t,{json:r.json,dir:n},i);if(r.json)ko(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DJ47R0B2.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?ko(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}function Mo(e=zn()){return wn(e,`Downloads`,`openknowledge.skill`)}function No(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function Po(e={}){let t=En(e.out??Mo()),n=e.platformName??Vn(),r=e.spawnFn??vn;try{await Yn(Sn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Pe(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await De({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Pe(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ne(`Built ${i.outputPath}`),Me(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),je(` Open the Claude Desktop App, then: ${Ie(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
25
25
  `),exitCode:0};let a=No(i.outputPath,n,r);return a.ok?{status:`installed`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ne(`Built ${i.outputPath}`),Me(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}… • CLI v${i.cliVersion}`),je(` Claude Desktop App opened. Now upload the file manually:`),` 1. ${Ie(`Customize`)} (sidebar) → ${Ie(`Skills`)}`,` 2. Click the ${Ie(`+`)} button`,` 3. Click ${Ie(`Create skill`)}`,` 4. Click ${Ie(`Upload skill`)}`,` 5. Pick ${Ie(`openknowledge.skill`)} from Downloads`,Me(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${i.outputPath}`)].join(`
26
26
  `),exitCode:0}:{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ne(`Built ${i.outputPath}`),Fe(` Handoff failed: ${a.message}`),je(` Open the Claude Desktop App, then: ${Ie(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
27
27
  `),exitCode:0}}function Fo(){return new r(`install-skill`).description("Build openknowledge.skill and open the Claude Desktop App so you can upload it for Claude Chat & Cowork. Not needed for Claude Code — `ok init` covers that separately.").option(`--out <path>`,`Custom output path (default: ~/Downloads/openknowledge.skill)`).option(`--no-open`,`Build the file but skip the OS file-association handoff`).action(async e=>{let t=await Po({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var M;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(M||={});var Io;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Io||={});const N=M.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Lo=e=>{switch(typeof e){case`undefined`:return N.undefined;case`string`:return N.string;case`number`:return Number.isNaN(e)?N.nan:N.number;case`boolean`:return N.boolean;case`function`:return N.function;case`bigint`:return N.bigint;case`symbol`:return N.symbol;case`object`:return Array.isArray(e)?N.array:e===null?N.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?N.promise:typeof Map<`u`&&e instanceof Map?N.map:typeof Set<`u`&&e instanceof Set?N.set:typeof Date<`u`&&e instanceof Date?N.date:N.object;default:return N.unknown}},P=M.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var Ro=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ro.create=e=>new Ro(e);const zo=(e,t)=>{let n;switch(e.code){case P.invalid_type:n=e.received===N.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,`, `)}`;break;case P.invalid_union:n=`Invalid input`;break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n=`Invalid function arguments`;break;case P.invalid_return_type:n=`Invalid function return type`;break;case P.invalid_date:n=`Invalid date`;break;case P.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case P.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case P.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case P.custom:n=`Invalid input`;break;case P.invalid_intersection_types:n=`Intersection results could not be merged`;break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,M.assertNever(e)}return{message:n}};let Bo=zo;function Vo(){return Bo}const Ho=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function F(e,t){let n=Vo(),r=Ho({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===zo?void 0:zo].filter(e=>!!e)});e.common.issues.push(r)}var Uo=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return I;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return I;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const I=Object.freeze({status:`aborted`}),Wo=e=>({status:`dirty`,value:e}),Go=e=>({status:`valid`,value:e}),Ko=e=>e.status===`aborted`,qo=e=>e.status===`dirty`,Jo=e=>e.status===`valid`,Yo=e=>typeof Promise<`u`&&e instanceof Promise;var L;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(L||={});var Xo=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const Zo=(e,t)=>{if(Jo(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new Ro(e.common.issues),this._error}}};function R(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var z=class{get description(){return this._def.description}_getType(e){return Lo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Lo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Uo,ctx:{common:e.parent.common,data:e.data,parsedType:Lo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Yo(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lo(e)};return Zo(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lo(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Jo(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Jo(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lo(e)},r=this._parse({data:e,path:n.path,parent:n});return Zo(n,await(Yo(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:P.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new $s({schema:this,typeName:B.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ec.create(this,this._def)}nullable(){return tc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ps.create(this)}promise(){return Qs.create(this,this._def)}or(e){return Ls.create([this,e],this._def)}and(e){return Vs.create(this,e,this._def)}transform(e){return new $s({...R(this._def),schema:this,typeName:B.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new nc({...R(this._def),innerType:this,defaultValue:t,typeName:B.ZodDefault})}brand(){return new ac({typeName:B.ZodBranded,type:this,...R(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new rc({...R(this._def),innerType:this,catchValue:t,typeName:B.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return oc.create(this,e)}readonly(){return sc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Qo=/^c[^\s-]{8,}$/i,$o=/^[0-9a-z]+$/,es=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ts=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ns=/^[a-z0-9_-]{21}$/i,rs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,is=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,as=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let os;const ss=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,cs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ls=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,us=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ds=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ps=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,ms=RegExp(`^${ps}$`);function hs(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function gs(e){return RegExp(`^${hs(e)}$`)}function _s(e){let t=`${ps}T${hs(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function vs(e,t){return!!((t===`v4`||!t)&&ss.test(e)||(t===`v6`||!t)&&ls.test(e))}function ys(e,t){if(!rs.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function bs(e,t){return!!((t===`v4`||!t)&&cs.test(e)||(t===`v6`||!t)&&us.test(e))}var xs=class e extends z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.string,received:t.parsedType}),I}let t=new Uo,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?F(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&F(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)as.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`email`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)os||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),os.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`emoji`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ts.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`uuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ns.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`nanoid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Qo.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)$o.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cuid2`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)es.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ulid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),F(n,{validation:`url`,code:P.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`regex`,code:P.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?_s(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ms.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?gs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:P.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?is.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`duration`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?vs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`ip`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?ys(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`jwt`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?bs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`cidr`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ds.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?fs.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:`base64url`,code:P.invalid_string,message:r.message}),t.dirty()):M.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:P.invalid_string,...L.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...L.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...L.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...L.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...L.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...L.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...L.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...L.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...L.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...L.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...L.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...L.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...L.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...L.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...L.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...L.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...L.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...L.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...L.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...L.errToObj(t)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};xs.create=e=>new xs({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...R(e)});function Ss(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Cs=class e extends z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==N.number){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.number,received:t.parsedType}),I}let t,n=new Uo;for(let r of this._def.checks)r.kind===`int`?M.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ss(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_finite,message:r.message}),n.dirty()):M.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:L.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:L.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:L.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:L.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&M.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Cs.create=e=>new Cs({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...R(e)});var ws=class e extends z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==N.bigint)return this._getInvalidInput(e);let t,n=new Uo;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),F(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):M.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit(`min`,e,!0,L.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,L.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,L.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,L.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:L.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ws.create=e=>new ws({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...R(e)});var Ts=class extends z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.boolean,received:t.parsedType}),I}return Go(e.data)}};Ts.create=e=>new Ts({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...R(e)});var Es=class e extends z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime()))return F(this._getOrReturnCtx(e),{code:P.invalid_date}),I;let t=new Uo,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:P.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):M.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:L.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:L.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Es.create=e=>new Es({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...R(e)});var Ds=class extends z{_parse(e){if(this._getType(e)!==N.symbol){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.symbol,received:t.parsedType}),I}return Go(e.data)}};Ds.create=e=>new Ds({typeName:B.ZodSymbol,...R(e)});var Os=class extends z{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.undefined,received:t.parsedType}),I}return Go(e.data)}};Os.create=e=>new Os({typeName:B.ZodUndefined,...R(e)});var ks=class extends z{_parse(e){if(this._getType(e)!==N.null){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.null,received:t.parsedType}),I}return Go(e.data)}};ks.create=e=>new ks({typeName:B.ZodNull,...R(e)});var As=class extends z{constructor(){super(...arguments),this._any=!0}_parse(e){return Go(e.data)}};As.create=e=>new As({typeName:B.ZodAny,...R(e)});var js=class extends z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Go(e.data)}};js.create=e=>new js({typeName:B.ZodUnknown,...R(e)});var Ms=class extends z{_parse(e){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.never,received:t.parsedType}),I}};Ms.create=e=>new Ms({typeName:B.ZodNever,...R(e)});var Ns=class extends z{_parse(e){if(this._getType(e)!==N.undefined){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.void,received:t.parsedType}),I}return Go(e.data)}};Ns.create=e=>new Ns({typeName:B.ZodVoid,...R(e)});var Ps=class e extends z{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==N.array)return F(t,{code:P.invalid_type,expected:N.array,received:t.parsedType}),I;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(F(t,{code:e?P.too_big:P.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(F(t,{code:P.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(F(t,{code:P.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Xo(t,e,t.path,n)))).then(e=>Uo.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Xo(t,e,t.path,n)));return Uo.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:L.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};Ps.create=(e,t)=>new Ps({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...R(t)});function Fs(e){if(e instanceof Is){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ec.create(Fs(r))}return new Is({...e._def,shape:()=>t})}else if(e instanceof Ps)return new Ps({...e._def,type:Fs(e.element)});else if(e instanceof ec)return ec.create(Fs(e.unwrap()));else if(e instanceof tc)return tc.create(Fs(e.unwrap()));else if(e instanceof Hs)return Hs.create(e.items.map(e=>Fs(e)));else return e}var Is=class e extends z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:M.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==N.object){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Xo(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ms){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(F(n,{code:P.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Xo(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Uo.mergeObjectSync(t,e)):Uo.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:L.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:B.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of M.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of M.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Fs(this)}partial(t){let n={};for(let e of M.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of M.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ec;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ys(M.objectKeys(this.shape))}};Is.create=(e,t)=>new Is({shape:()=>e,unknownKeys:`strip`,catchall:Ms.create(),typeName:B.ZodObject,...R(t)}),Is.strictCreate=(e,t)=>new Is({shape:()=>e,unknownKeys:`strict`,catchall:Ms.create(),typeName:B.ZodObject,...R(t)}),Is.lazycreate=(e,t)=>new Is({shape:e,unknownKeys:`strip`,catchall:Ms.create(),typeName:B.ZodObject,...R(t)});var Ls=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Ro(e.ctx.common.issues));return F(t,{code:P.invalid_union,unionErrors:n}),I}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Ro(e));return F(t,{code:P.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}};Ls.create=(e,t)=>new Ls({options:e,typeName:B.ZodUnion,...R(t)});const Rs=e=>e instanceof qs?Rs(e.schema):e instanceof $s?Rs(e.innerType()):e instanceof Js?[e.value]:e instanceof Xs?e.options:e instanceof Zs?M.objectValues(e.enum):e instanceof nc?Rs(e._def.innerType):e instanceof Os?[void 0]:e instanceof ks?[null]:e instanceof ec?[void 0,...Rs(e.unwrap())]:e instanceof tc?[null,...Rs(e.unwrap())]:e instanceof ac||e instanceof sc?Rs(e.unwrap()):e instanceof rc?Rs(e._def.innerType):[];var zs=class e extends z{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.object)return F(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),I;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(F(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),I)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Rs(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...R(r)})}};function Bs(e,t){let n=Lo(e),r=Lo(t);if(e===t)return{valid:!0,data:e};if(n===N.object&&r===N.object){let n=M.objectKeys(t),r=M.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Bs(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===N.array&&r===N.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Bs(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===N.date&&r===N.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Vs=class extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Ko(e)||Ko(r))return I;let i=Bs(e.value,r.value);return i.valid?((qo(e)||qo(r))&&t.dirty(),{status:t.value,value:i.data}):(F(n,{code:P.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Vs.create=(e,t,n)=>new Vs({left:e,right:t,typeName:B.ZodIntersection,...R(n)});var Hs=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.array)return F(n,{code:P.invalid_type,expected:N.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return F(n,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),I;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Xo(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Uo.mergeArray(t,e)):Uo.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Hs.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Hs({items:e,typeName:B.ZodTuple,rest:null,...R(t)})};var Us=class e extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return F(n,{code:P.invalid_type,expected:N.object,received:n.parsedType}),I;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Xo(n,e,n.path,e)),value:a._parse(new Xo(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Uo.mergeObjectAsync(t,r):Uo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof z?new e({keyType:t,valueType:n,typeName:B.ZodRecord,...R(r)}):new e({keyType:xs.create(),valueType:t,typeName:B.ZodRecord,...R(n)})}},Ws=class extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.map)return F(n,{code:P.invalid_type,expected:N.map,received:n.parsedType}),I;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Xo(n,e,n.path,[a,`key`])),value:i._parse(new Xo(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return I;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Ws.create=(e,t,n)=>new Ws({valueType:t,keyType:e,typeName:B.ZodMap,...R(n)});var Gs=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.set)return F(n,{code:P.invalid_type,expected:N.set,received:n.parsedType}),I;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(F(n,{code:P.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(F(n,{code:P.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return I;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Xo(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:L.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Gs.create=(e,t)=>new Gs({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...R(t)});var Ks=class e extends z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.function)return F(t,{code:P.invalid_type,expected:N.function,received:t.parsedType}),I;function n(e,n){return Ho({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Vo(),zo].filter(e=>!!e),issueData:{code:P.invalid_arguments,argumentsError:n}})}function r(e,n){return Ho({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Vo(),zo].filter(e=>!!e),issueData:{code:P.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Qs){let e=this;return Go(async function(...t){let o=new Ro([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Go(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Ro([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Ro([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Hs.create(t).rest(js.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Hs.create([]).rest(js.create()),returns:n||js.create(),typeName:B.ZodFunction,...R(r)})}},qs=class extends z{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};qs.create=(e,t)=>new qs({getter:e,typeName:B.ZodLazy,...R(t)});var Js=class extends z{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return F(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),I}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Js.create=(e,t)=>new Js({value:e,typeName:B.ZodLiteral,...R(t)});function Ys(e,t){return new Xs({values:e,typeName:B.ZodEnum,...R(t)})}var Xs=class e extends z{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{expected:M.joinValues(n),received:t.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return F(t,{received:t.data,code:P.invalid_enum_value,options:n}),I}return Go(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Xs.create=Ys;var Zs=class extends z{_parse(e){let t=M.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==N.string&&n.parsedType!==N.number){let e=M.objectValues(t);return F(n,{expected:M.joinValues(e),received:n.parsedType,code:P.invalid_type}),I}if(this._cache||=new Set(M.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=M.objectValues(t);return F(n,{received:n.data,code:P.invalid_enum_value,options:e}),I}return Go(e.data)}get enum(){return this._def.values}};Zs.create=(e,t)=>new Zs({values:e,typeName:B.ZodNativeEnum,...R(t)});var Qs=class extends z{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==N.promise&&t.common.async===!1?(F(t,{code:P.invalid_type,expected:N.promise,received:t.parsedType}),I):Go((t.parsedType===N.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Qs.create=(e,t)=>new Qs({type:e,typeName:B.ZodPromise,...R(t)});var $s=class extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{F(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return I;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?Wo(r.value):r});{if(t.value===`aborted`)return I;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?I:r.status===`dirty`||t.value===`dirty`?Wo(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?I:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?I:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Jo(e))return I;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Jo(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I);M.assertNever(r)}};$s.create=(e,t,n)=>new $s({schema:e,typeName:B.ZodEffects,effect:t,...R(n)}),$s.createWithPreprocess=(e,t,n)=>new $s({schema:t,effect:{type:`preprocess`,transform:e},typeName:B.ZodEffects,...R(n)});var ec=class extends z{_parse(e){return this._getType(e)===N.undefined?Go(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ec.create=(e,t)=>new ec({innerType:e,typeName:B.ZodOptional,...R(t)});var tc=class extends z{_parse(e){return this._getType(e)===N.null?Go(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tc.create=(e,t)=>new tc({innerType:e,typeName:B.ZodNullable,...R(t)});var nc=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===N.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};nc.create=(e,t)=>new nc({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...R(t)});var rc=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Yo(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Ro(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Ro(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};rc.create=(e,t)=>new rc({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...R(t)});var ic=class extends z{_parse(e){if(this._getType(e)!==N.nan){let t=this._getOrReturnCtx(e);return F(t,{code:P.invalid_type,expected:N.nan,received:t.parsedType}),I}return{status:`valid`,value:e.data}}};ic.create=e=>new ic({typeName:B.ZodNaN,...R(e)});var ac=class extends z{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},oc=class e extends z{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),Wo(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?I:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:B.ZodPipeline})}},sc=class extends z{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Jo(e)&&(e.value=Object.freeze(e.value)),e);return Yo(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};sc.create=(e,t)=>new sc({innerType:e,typeName:B.ZodReadonly,...R(t)}),Is.lazycreate;var B;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(B||={}),xs.create,Cs.create,ic.create,ws.create,Ts.create,Es.create,Ds.create,Os.create,ks.create,As.create,js.create,Ms.create,Ns.create,Ps.create;const cc=Is.create;Is.strictCreate,Ls.create,zs.create,Vs.create,Hs.create,Us.create,Ws.create,Gs.create,Ks.create,qs.create,Js.create,Xs.create,Zs.create,Qs.create,$s.create,ec.create,tc.create,$s.createWithPreprocess,oc.create;const lc=oe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ce.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>de(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ie(e,t,n),e.parseAsync=async(t,n)=>te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pe(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ne(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),uc=oe(`ZodMiniObject`,(e,t)=>{E.init(e,t),lc.init(e,t),re(e,`shape`,()=>t.shape)});function dc(e,t){return new uc({type:`object`,shape:e??{},...ue(t)})}function fc(e){return!!e._zod}function pc(e){let t=Object.values(e);if(t.length===0)return dc({});let n=t.every(fc),r=t.every(e=>!fc(e));if(n)return dc(e);if(r)return cc(e);throw Error(`Mixed Zod versions detected in object shape.`)}function mc(e,t){return fc(e)?ie(e,t):e.safeParse(t)}async function hc(e,t){return fc(e)?await pe(e,t):await e.safeParseAsync(t)}function gc(e){if(!e)return;let t;if(t=fc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function _c(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return pc(e)}}if(fc(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function vc(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function yc(e){return e.description}function bc(e){if(fc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function xc(e){if(fc(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const Sc=`2025-11-25`,Cc=[Sc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],wc=`io.modelcontextprotocol/related-task`,Tc=S(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Ec=v([T(),g().int()]),Dc=T();f({ttl:g().optional(),pollInterval:g().optional()});const Oc=D({ttl:g().optional()}),kc=D({taskId:T()}),Ac=f({progressToken:Ec.optional(),[wc]:kc.optional()}),jc=D({_meta:Ac.optional()}),Mc=jc.extend({task:Oc.optional()}),Nc=e=>Mc.safeParse(e).success,Pc=D({method:T(),params:jc.loose().optional()}),Fc=D({_meta:Ac.optional()}),Ic=D({method:T(),params:Fc.loose().optional()}),Lc=f({_meta:Ac.optional()}),Rc=v([T(),g().int()]),zc=D({jsonrpc:C(`2.0`),id:Rc,...Pc.shape}).strict(),Bc=e=>zc.safeParse(e).success,Vc=D({jsonrpc:C(`2.0`),...Ic.shape}).strict(),Hc=e=>Vc.safeParse(e).success,Uc=D({jsonrpc:C(`2.0`),id:Rc,result:Lc}).strict(),Wc=e=>Uc.safeParse(e).success;var V;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(V||={});const Gc=D({jsonrpc:C(`2.0`),id:Rc.optional(),error:D({code:g().int(),message:T(),data:u().optional()})}).strict(),Kc=e=>Gc.safeParse(e).success,qc=v([zc,Vc,Uc,Gc]);v([Uc,Gc]);const Jc=Lc.strict(),Yc=Fc.extend({requestId:Rc.optional(),reason:T().optional()}),Xc=Ic.extend({method:C(`notifications/cancelled`),params:Yc}),Zc=D({icons:O(D({src:T(),mimeType:T().optional(),sizes:O(T()).optional(),theme:_([`light`,`dark`]).optional()})).optional()}),Qc=D({name:T(),title:T().optional()}),$c=Qc.extend({...Qc.shape,...Zc.shape,version:T(),websiteUrl:T().optional(),description:T().optional()}),el=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,x(D({form:x(D({applyDefaults:d().optional()}),w(T(),u())).optional(),url:Tc.optional()}),w(T(),u()).optional())),tl=f({list:Tc.optional(),cancel:Tc.optional(),requests:f({sampling:f({createMessage:Tc.optional()}).optional(),elicitation:f({create:Tc.optional()}).optional()}).optional()}),nl=f({list:Tc.optional(),cancel:Tc.optional(),requests:f({tools:f({call:Tc.optional()}).optional()}).optional()}),rl=D({experimental:w(T(),Tc).optional(),sampling:D({context:Tc.optional(),tools:Tc.optional()}).optional(),elicitation:el.optional(),roots:D({listChanged:d().optional()}).optional(),tasks:tl.optional(),extensions:w(T(),Tc).optional()}),il=jc.extend({protocolVersion:T(),capabilities:rl,clientInfo:$c}),al=Pc.extend({method:C(`initialize`),params:il}),ol=D({experimental:w(T(),Tc).optional(),logging:Tc.optional(),completions:Tc.optional(),prompts:D({listChanged:d().optional()}).optional(),resources:D({subscribe:d().optional(),listChanged:d().optional()}).optional(),tools:D({listChanged:d().optional()}).optional(),tasks:nl.optional(),extensions:w(T(),Tc).optional()}),sl=Lc.extend({protocolVersion:T(),capabilities:ol,serverInfo:$c,instructions:T().optional()}),cl=Ic.extend({method:C(`notifications/initialized`),params:Fc.optional()}),ll=Pc.extend({method:C(`ping`),params:jc.optional()}),ul=D({progress:g(),total:h(g()),message:h(T())}),dl=D({...Fc.shape,...ul.shape,progressToken:Ec}),fl=Ic.extend({method:C(`notifications/progress`),params:dl}),pl=jc.extend({cursor:Dc.optional()}),ml=Pc.extend({params:pl.optional()}),hl=Lc.extend({nextCursor:Dc.optional()}),gl=_([`working`,`input_required`,`completed`,`failed`,`cancelled`]),_l=D({taskId:T(),status:gl,ttl:v([g(),y()]),createdAt:T(),lastUpdatedAt:T(),pollInterval:h(g()),statusMessage:h(T())}),vl=Lc.extend({task:_l}),yl=Fc.merge(_l),bl=Ic.extend({method:C(`notifications/tasks/status`),params:yl}),xl=Pc.extend({method:C(`tasks/get`),params:jc.extend({taskId:T()})}),Sl=Lc.merge(_l),Cl=Pc.extend({method:C(`tasks/result`),params:jc.extend({taskId:T()})});Lc.loose();const wl=ml.extend({method:C(`tasks/list`)}),Tl=hl.extend({tasks:O(_l)}),El=Pc.extend({method:C(`tasks/cancel`),params:jc.extend({taskId:T()})}),Dl=Lc.merge(_l),Ol=D({uri:T(),mimeType:h(T()),_meta:w(T(),u()).optional()}),kl=Ol.extend({text:T()}),Al=T().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),jl=Ol.extend({blob:Al}),Ml=_([`user`,`assistant`]),Nl=D({audience:O(Ml).optional(),priority:g().min(0).max(1).optional(),lastModified:fe({offset:!0}).optional()}),Pl=D({...Qc.shape,...Zc.shape,uri:T(),description:h(T()),mimeType:h(T()),size:h(g()),annotations:Nl.optional(),_meta:h(f({}))}),Fl=D({...Qc.shape,...Zc.shape,uriTemplate:T(),description:h(T()),mimeType:h(T()),annotations:Nl.optional(),_meta:h(f({}))}),Il=ml.extend({method:C(`resources/list`)}),Ll=hl.extend({resources:O(Pl)}),Rl=ml.extend({method:C(`resources/templates/list`)}),zl=hl.extend({resourceTemplates:O(Fl)}),Bl=jc.extend({uri:T()}),Vl=Bl,Hl=Pc.extend({method:C(`resources/read`),params:Vl}),Ul=Lc.extend({contents:O(v([kl,jl]))}),Wl=Ic.extend({method:C(`notifications/resources/list_changed`),params:Fc.optional()}),Gl=Bl,Kl=Pc.extend({method:C(`resources/subscribe`),params:Gl}),ql=Bl,Jl=Pc.extend({method:C(`resources/unsubscribe`),params:ql}),Yl=Fc.extend({uri:T()}),Xl=Ic.extend({method:C(`notifications/resources/updated`),params:Yl}),Zl=D({name:T(),description:h(T()),required:h(d())}),Ql=D({...Qc.shape,...Zc.shape,description:h(T()),arguments:h(O(Zl)),_meta:h(f({}))}),$l=ml.extend({method:C(`prompts/list`)}),eu=hl.extend({prompts:O(Ql)}),tu=jc.extend({name:T(),arguments:w(T(),T()).optional()}),nu=Pc.extend({method:C(`prompts/get`),params:tu}),ru=D({type:C(`text`),text:T(),annotations:Nl.optional(),_meta:w(T(),u()).optional()}),iu=D({type:C(`image`),data:Al,mimeType:T(),annotations:Nl.optional(),_meta:w(T(),u()).optional()}),au=D({type:C(`audio`),data:Al,mimeType:T(),annotations:Nl.optional(),_meta:w(T(),u()).optional()}),ou=D({type:C(`tool_use`),name:T(),id:T(),input:w(T(),u()),_meta:w(T(),u()).optional()}),su=D({type:C(`resource`),resource:v([kl,jl]),annotations:Nl.optional(),_meta:w(T(),u()).optional()}),cu=v([ru,iu,au,Pl.extend({type:C(`resource_link`)}),su]),lu=D({role:Ml,content:cu}),uu=Lc.extend({description:T().optional(),messages:O(lu)}),du=Ic.extend({method:C(`notifications/prompts/list_changed`),params:Fc.optional()}),fu=D({title:T().optional(),readOnlyHint:d().optional(),destructiveHint:d().optional(),idempotentHint:d().optional(),openWorldHint:d().optional()}),pu=D({taskSupport:_([`required`,`optional`,`forbidden`]).optional()}),mu=D({...Qc.shape,...Zc.shape,description:T().optional(),inputSchema:D({type:C(`object`),properties:w(T(),Tc).optional(),required:O(T()).optional()}).catchall(u()),outputSchema:D({type:C(`object`),properties:w(T(),Tc).optional(),required:O(T()).optional()}).catchall(u()).optional(),annotations:fu.optional(),execution:pu.optional(),_meta:w(T(),u()).optional()}),hu=ml.extend({method:C(`tools/list`)}),gu=hl.extend({tools:O(mu)}),_u=Lc.extend({content:O(cu).default([]),structuredContent:w(T(),u()).optional(),isError:d().optional()});_u.or(Lc.extend({toolResult:u()}));const vu=Mc.extend({name:T(),arguments:w(T(),u()).optional()}),yu=Pc.extend({method:C(`tools/call`),params:vu}),bu=Ic.extend({method:C(`notifications/tools/list_changed`),params:Fc.optional()});D({autoRefresh:d().default(!0),debounceMs:g().int().nonnegative().default(300)});const xu=_([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Su=jc.extend({level:xu}),Cu=Pc.extend({method:C(`logging/setLevel`),params:Su}),wu=Fc.extend({level:xu,logger:T().optional(),data:u()}),Tu=Ic.extend({method:C(`notifications/message`),params:wu}),Eu=D({hints:O(D({name:T().optional()})).optional(),costPriority:g().min(0).max(1).optional(),speedPriority:g().min(0).max(1).optional(),intelligencePriority:g().min(0).max(1).optional()}),Du=D({mode:_([`auto`,`required`,`none`]).optional()}),Ou=D({type:C(`tool_result`),toolUseId:T().describe(`The unique identifier for the corresponding tool call.`),content:O(cu).default([]),structuredContent:D({}).loose().optional(),isError:d().optional(),_meta:w(T(),u()).optional()}),ku=p(`type`,[ru,iu,au]),Au=p(`type`,[ru,iu,au,ou,Ou]),ju=D({role:Ml,content:v([Au,O(Au)]),_meta:w(T(),u()).optional()}),Mu=Mc.extend({messages:O(ju),modelPreferences:Eu.optional(),systemPrompt:T().optional(),includeContext:_([`none`,`thisServer`,`allServers`]).optional(),temperature:g().optional(),maxTokens:g().int(),stopSequences:O(T()).optional(),metadata:Tc.optional(),tools:O(mu).optional(),toolChoice:Du.optional()}),Nu=Pc.extend({method:C(`sampling/createMessage`),params:Mu}),Pu=Lc.extend({model:T(),stopReason:h(_([`endTurn`,`stopSequence`,`maxTokens`]).or(T())),role:Ml,content:ku}),Fu=Lc.extend({model:T(),stopReason:h(_([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(T())),role:Ml,content:v([Au,O(Au)])}),Iu=D({type:C(`boolean`),title:T().optional(),description:T().optional(),default:d().optional()}),Lu=D({type:C(`string`),title:T().optional(),description:T().optional(),minLength:g().optional(),maxLength:g().optional(),format:_([`email`,`uri`,`date`,`date-time`]).optional(),default:T().optional()}),Ru=D({type:_([`number`,`integer`]),title:T().optional(),description:T().optional(),minimum:g().optional(),maximum:g().optional(),default:g().optional()}),zu=D({type:C(`string`),title:T().optional(),description:T().optional(),enum:O(T()),default:T().optional()}),Bu=D({type:C(`string`),title:T().optional(),description:T().optional(),oneOf:O(D({const:T(),title:T()})),default:T().optional()}),Vu=v([v([D({type:C(`string`),title:T().optional(),description:T().optional(),enum:O(T()),enumNames:O(T()).optional(),default:T().optional()}),v([zu,Bu]),v([D({type:C(`array`),title:T().optional(),description:T().optional(),minItems:g().optional(),maxItems:g().optional(),items:D({type:C(`string`),enum:O(T())}),default:O(T()).optional()}),D({type:C(`array`),title:T().optional(),description:T().optional(),minItems:g().optional(),maxItems:g().optional(),items:D({anyOf:O(D({const:T(),title:T()}))}),default:O(T()).optional()})])]),Iu,Lu,Ru]),Hu=v([Mc.extend({mode:C(`form`).optional(),message:T(),requestedSchema:D({type:C(`object`),properties:w(T(),Vu),required:O(T()).optional()})}),Mc.extend({mode:C(`url`),message:T(),elicitationId:T(),url:T().url()})]),Uu=Pc.extend({method:C(`elicitation/create`),params:Hu}),Wu=Fc.extend({elicitationId:T()}),Gu=Ic.extend({method:C(`notifications/elicitation/complete`),params:Wu}),Ku=Lc.extend({action:_([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,w(T(),v([T(),g(),d(),O(T())])).optional())}),qu=D({type:C(`ref/resource`),uri:T()}),Ju=D({type:C(`ref/prompt`),name:T()}),Yu=jc.extend({ref:v([Ju,qu]),argument:D({name:T(),value:T()}),context:D({arguments:w(T(),T()).optional()}).optional()}),Xu=Pc.extend({method:C(`completion/complete`),params:Yu});function Zu(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Qu(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const $u=Lc.extend({completion:f({values:O(T()).max(100),total:h(g().int()),hasMore:h(d())})}),ed=D({uri:T().startsWith(`file://`),name:T().optional(),_meta:w(T(),u()).optional()}),td=Pc.extend({method:C(`roots/list`),params:jc.optional()}),nd=Lc.extend({roots:O(ed)}),rd=Ic.extend({method:C(`notifications/roots/list_changed`),params:Fc.optional()});v([ll,al,Xu,Cu,nu,$l,Il,Rl,Hl,Kl,Jl,yu,hu,xl,Cl,wl,El]),v([Xc,fl,cl,rd,bl]),v([Jc,Pu,Fu,Ku,nd,Sl,Tl,vl]),v([ll,Nu,Uu,td,xl,Cl,wl,El]),v([Xc,fl,Tu,Xl,Wl,bu,du,bl,Gu]),v([Jc,sl,$u,uu,eu,Ll,zl,Ul,_u,gu,Sl,Tl,vl]);var H=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===V.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new id(e.elicitations,n)}return new e(t,n,r)}},id=class extends H{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(V.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ad(e){return e===`completed`||e===`failed`||e===`cancelled`}const od=Symbol(`Let zodToJsonSchema decide on which parser to use`),sd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},cd=e=>typeof e==`string`?{...sd,name:e}:{...sd,...e},ld=e=>{let t=cd(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function ud(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function U(e,t,n,r,i){e[t]=n,ud(e,t,r,i)}const dd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function fd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?dd(t,e.currentPath):t.join(`/`)}}function pd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(n.items=W(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&U(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&U(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(U(n,`minItems`,e.exactLength.value,e.exactLength.message,t),U(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function md(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function hd(){return{type:`boolean`}}function gd(e,t){return W(e.type._def,t)}const _d=(e,t)=>W(e.innerType._def,t);function vd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>vd(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return yd(e,t)}}const yd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:U(n,`minimum`,r.value,r.message,t);break;case`max`:U(n,`maximum`,r.value,r.message,t);break}return n};function bd(e,t){return{...W(e.innerType._def,t),default:e.defaultValue()}}function xd(e,t){return t.effectStrategy===`input`?W(e.schema._def,t):fd(t)}function Sd(e){return{type:`string`,enum:Array.from(e.values)}}const Cd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function wd(e,t){let n=[W(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),W(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Cd(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Td(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Ed;const Dd={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ed===void 0&&(Ed=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Ed),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Od(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Md(n,`email`,r.message,t);break;case`format:idn-email`:Md(n,`idn-email`,r.message,t);break;case`pattern:zod`:Nd(n,Dd.email,r.message,t);break}break;case`url`:Md(n,`uri`,r.message,t);break;case`uuid`:Md(n,`uuid`,r.message,t);break;case`regex`:Nd(n,r.regex,r.message,t);break;case`cuid`:Nd(n,Dd.cuid,r.message,t);break;case`cuid2`:Nd(n,Dd.cuid2,r.message,t);break;case`startsWith`:Nd(n,RegExp(`^${kd(r.value,t)}`),r.message,t);break;case`endsWith`:Nd(n,RegExp(`${kd(r.value,t)}$`),r.message,t);break;case`datetime`:Md(n,`date-time`,r.message,t);break;case`date`:Md(n,`date`,r.message,t);break;case`time`:Md(n,`time`,r.message,t);break;case`duration`:Md(n,`duration`,r.message,t);break;case`length`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Nd(n,RegExp(kd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Md(n,`ipv4`,r.message,t),r.version!==`v4`&&Md(n,`ipv6`,r.message,t);break;case`base64url`:Nd(n,Dd.base64url,r.message,t);break;case`jwt`:Nd(n,Dd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Nd(n,Dd.ipv4Cidr,r.message,t),r.version!==`v4`&&Nd(n,Dd.ipv6Cidr,r.message,t);break;case`emoji`:Nd(n,Dd.emoji(),r.message,t);break;case`ulid`:Nd(n,Dd.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Md(n,`binary`,r.message,t);break;case`contentEncoding:base64`:U(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Nd(n,Dd.base64,r.message,t);break}break;case`nanoid`:Nd(n,Dd.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function kd(e,t){return t.patternStrategy===`escape`?jd(e):e}const Ad=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function jd(e){let t=``;for(let n=0;n<e.length;n++)Ad.has(e[n])||(t+=`\\`),t+=e[n];return t}function Md(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):U(e,`format`,t,n,r)}function Nd(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Pd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):U(e,`pattern`,Pd(t,r),n,r)}function Pd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
@@ -1398,8 +1398,8 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
1398
1398
  Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
1399
1399
 
1400
1400
  **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed ONLY when no OK MCP is registered, or immediately after an OK MCP call failed — then begin your sentence with \`Open Knowledge MCP unavailable:\`. Non-markdown: native tools always.
1401
- `}async function VC(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function HC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(zC=cm(),zC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await VC(n,zC);zC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else zC.info(`server discovery is lazy per effective cwd`);let o=new Kp({name:l,version:c},{instructions:BC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=LC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:zC}),u=RC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(rd,async()=>{s.invalidateRoots()});let f=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=Jn(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},zC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},PC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:zC});let g=new am;await o.connect(g),zC.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-CZzB5k1h.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:zC.child(`keepalive`)}),y=e=>{zC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function UC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function WC(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function GC(e){let t=e.readLock??(()=>_e(e.lockDir)),n=e.isAlive??ge,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??vn,a=e.readErrorLog??(e=>kn(e)?Mn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>jn(e,`w`)),s=e.closeFd??(e=>On(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=WC({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};kn(e.lockDir)||An(e.lockDir,{recursive:!0});let d=wn(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=gn();e.logger?.info(`spawning server`,{command:h.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),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 t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:m,stderr:t}),Error(`Error: spawn failed: ${m}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(m){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:m,stderr:t}),Error(`Error: spawn failed: ${m}${t?` stderr:\n${t}`:``}`)}let _=a(d),v=(c/1e3).toFixed(c%1e3==0?0:2),y=p?.pid,b=``;throw typeof y==`number`&&(b=n(y)?` child pid=${y} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${y} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:y,childAlive:typeof y==`number`?n(y):void 0,stderr:_||void 0}),Error(`Error: server did not start within ${v}s.${b}${_?` stderr:\n${_}`:``}`)}function KC(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??GC,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Re(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=he(i,o),s=me(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function qC(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Be({startupCwd:r,startupConfig:n}),a=UC(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=KC({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await HC({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function JC(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-S0e7r-4X.mjs`),r=e(),i=process.cwd(),a=he(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function YC(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function XC(e,t,n=process.cwd()){let r=e.op??`sync`,i=_e(me(he(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}YC(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=ye({baseDir:n});if(r===`sync`||r===`pull`){YC(e.json,{type:`step`,step:`pull`});let t=await a.pull();YC(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(YC(e.json,{type:`step`,step:`push`}),await a.push(),YC(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1401
+ `}async function VC(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/document`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function HC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(zC=cm(),zC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await VC(n,zC);zC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else zC.info(`server discovery is lazy per effective cwd`);let o=new Kp({name:l,version:c},{instructions:BC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=LC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:zC}),u=RC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(rd,async()=>{s.invalidateRoots()});let f=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=Jn(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},zC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},PC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:zC});let g=new am;await o.connect(g),zC.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-CZzB5k1h.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${p}`,logger:zC.child(`keepalive`)}),y=e=>{zC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function UC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function WC(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function GC(e){let t=e.readLock??(()=>_e(e.lockDir)),n=e.isAlive??ge,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??vn,a=e.readErrorLog??(e=>kn(e)?Mn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>jn(e,`w`)),s=e.closeFd??(e=>On(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=WC({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};kn(e.lockDir)||An(e.lockDir,{recursive:!0});let d=wn(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=gn();e.logger?.info(`spawning server`,{command:h.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),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 t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:m,stderr:t}),Error(`Error: spawn failed: ${m}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(m){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:m,stderr:t}),Error(`Error: spawn failed: ${m}${t?` stderr:\n${t}`:``}`)}let _=a(d),v=(c/1e3).toFixed(c%1e3==0?0:2),y=p?.pid,b=``;throw typeof y==`number`&&(b=n(y)?` child pid=${y} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${y} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:y,childAlive:typeof y==`number`?n(y):void 0,stderr:_||void 0}),Error(`Error: server did not start within ${v}s.${b}${_?` stderr:\n${_}`:``}`)}function KC(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??GC,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Re(a??e.startupCwd),s=Date.now(),c=r.get(o);if(c&&c.expiresAt>s)return e.logger?.debug(`server url cache hit`,{cwd:o,url:c.url}),c.url;let l=i.get(o);if(l)return e.logger?.debug(`server url resolution pending`,{cwd:o}),await l;e.logger?.debug(`server url cache miss`,{cwd:o});let u=(async()=>{let i=await e.resolveConfig(o),a=he(i,o),s=me(a),c=e.readLock,l=c?()=>c(s):void 0,u=await t({lockDir:s,contentDir:a,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:l,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(o,{url:u.serverUrl,expiresAt:Date.now()+n}),u.serverUrl})();i.set(o,u);try{return await u}finally{i.delete(o)}}}function qC(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Be({startupCwd:r,startupConfig:n}),a=UC(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=KC({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await HC({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function JC(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-1YeKX_ki.mjs`),r=e(),i=process.cwd(),a=he(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function YC(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function XC(e,t,n=process.cwd()){let r=e.op??`sync`,i=_e(me(he(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}YC(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=ye({baseDir:n});if(r===`sync`||r===`pull`){YC(e.json,{type:`step`,step:`pull`});let t=await a.pull();YC(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(YC(e.json,{type:`step`,step:`push`}),await a.push(),YC(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1402
1402
  `)),YC(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function ZC(e){return new r(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await XC({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 QC(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await XC({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 $C(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await XC({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)}})}async function ew(e={}){let t=En(e.cwd??process.cwd()),n;try{n=await Ee({projectDir:t,rootDir:e.root})}catch(e){return e instanceof Ce?{status:`prerequisite-missing`,message:`${Pe(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Pe(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Ne(`Your knowledge base is already seeded.`)}\n${Me(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${Ie(`Plan (dry-run — no changes made):`)}\n\n${tw(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await nw(`${Ie(`Plan:`)}\n\n${tw(n,t)}\n\n${Ie(`Apply?`)} ${Me(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Me(`Cancelled.`),plan:n,exitCode:0};let r=await Se(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Pe(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Fe(`Applied`)} ${r.applied} entries, ${Fe(String(r.errors.length))} error(s):`,...e].join(`
1403
1403
  `),plan:n,exitCode:1}}return{status:`applied`,message:`${Ne(`✓ Seeded knowledge base`)} ${Me(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function tw(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(Ie(`Folders to create:`));for(let e of r)n.push(` ${Ne(`+`)} ${je(Tn(t,En(t,e.path))||e.path)}${Me(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(Ie(`Files to create:`));for(let e of i)n.push(` ${Ne(`+`)} ${je(Tn(t,En(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push(Ie(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Ne(`+`)} ${je(t.folderMatch)} ${Me(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Me(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Me(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Fe(`Warnings:`));for(let t of e.warnings)n.push(` ${Fe(`!`)} ${t}`)}return n.join(`
1404
- `)}async function nw(e,t){let n=nr({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 rw(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).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(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await ew({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function iw(e,t){return{server:aw(`server`,e),ui:aw(`ui`,t)}}function aw(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 ow(e){return`${sw(e.server)}\n${sw(e.ui)}`}function sw(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 cw(e){let t=e.inspect??(t=>yo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=iw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(ow(r)),r}function lw(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{cw({lockDir:me(he(e(),process.cwd())),json:t.json===!0})})}function uw(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function dw(e){let t=e.inspect??(t=>yo(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=uw(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function fw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{dw({lockDir:me(he(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const pw=1e4,mw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function hw(e){let t=e.upstreamTimeoutMs??pw,n=$n((n,r)=>{_w(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 gw(e,t,n){_w(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??pw)}function _w(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of mw)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=er({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of mw)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function vw(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function yw(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,readServerLock:a,releaseUiLock:o,updateUiLockPort:s}=await import(`./dist-Bx5GgBdJ.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-BH3t9_kz.mjs`),d=l(e.config,e.cwd),f=u(d);i(f,{port:0,worktreeRoot:e.cwd});let p=import.meta.dirname??new URL(`.`,import.meta.url).pathname,m=[r(p,`public`),r(p,`../../app/dist`),r(p,`../../../app/dist`)].find(e=>t(e)),h=m?c(m,{single:!0,gzip:!0,immutable:!0}):null,g=t(d)?c(d,{dotfiles:!1,dev:!0}):null,_=e.port,v=null,y=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){v?.();let n=a(f),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:_});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/`)){v?.();let r=a(f);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}gw(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&g){t.setHeader(`X-Content-Type-Options`,`nosniff`),g(e,t,()=>{h?h(e,t):bw(t)});return}if(h){h(e,t);return}bw(t)},x=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],S=[],C=e.port;try{for(let e of x){let t=n(y);S.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(C,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(C=e.port),n()})})}}catch(e){await Promise.all(S.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let w=C;_=w,s(f,w);let ee=e.scheduler??b,T=e.safetyNetMs??432e5,E=null,te=!1,ne=!1,re=()=>{te||(te=!0,E!==null&&(ee.clearTimeout(E),E=null))},ie=()=>{if(re(),!ne){ne=!0;try{o(f)}catch{}}},ae=()=>{te||T<=0||(E!==null&&(ee.clearTimeout(E),E=null),E=ee.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of S)try{e.close()}catch{}ie()},T))},oe=()=>{te||T<=0||ae()};return v=oe,ae(),{httpServers:S,port:w,release:ie,detachSafetyNet:re,nudgeSafetyNet:oe}}function bw(e){e.writeHead(404),e.end(`Not found`)}function xw(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 Sw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-Bx5GgBdJ.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 hw({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Cw(e){return new r(`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-BnZ-i-vb.mjs`),{UiLockCollisionError:r}=await import(`./dist-Bx5GgBdJ.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-BH3t9_kz.mjs`),o=e(),s=t.host,c;try{c=xw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await yw({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};vw(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await Sw({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const ww=new r;let Tw;ww.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(c).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ze(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),Tw=r});const Ew=hn(()=>Tw);ww.addCommand(Ew,{isDefault:!0});const Dw=qC(()=>Tw);ww.addCommand(Dw),ww.addCommand(Ae()),ww.addCommand(rw()),ww.addCommand(Fo());const Ow=JC(()=>Tw);ww.addCommand(Ow);const kw=Cw(()=>Tw);ww.addCommand(kw),ww.addCommand(fw(()=>Tw)),ww.addCommand(So(()=>Tw)),ww.addCommand(lw(()=>Tw)),ww.addCommand(vo(()=>Tw)),ww.addCommand(jo(()=>Tw)),ww.addCommand(ZC(()=>Tw)),ww.addCommand($C(()=>Tw)),ww.addCommand(QC(()=>Tw)),await ww.parseAsync();export{};
1404
+ `)}async function nw(e,t){let n=nr({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 rw(){return new r(`seed`).description(`Scaffold the Karpathy three-layer knowledge-base structure (external-sources/, research/, articles/) + log.md + config.yml folders: entries. Use --root to place them inside a subfolder instead of the project root.`).argument(`[path]`,`Project directory (defaults to cwd)`).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(`-y, --yes`,`Skip confirmation prompt`).option(`--dry-run`,`Print the plan and exit without writing`).action(async(e,t)=>{let n=await ew({cwd:e??process.cwd(),root:t.root,yes:t.yes,dryRun:t.dryRun});process.stdout.write(`${n.message}\n`),n.exitCode!==0&&(process.exitCode=n.exitCode)})}function iw(e,t){return{server:aw(`server`,e),ui:aw(`ui`,t)}}function aw(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 ow(e){return`${sw(e.server)}\n${sw(e.ui)}`}function sw(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 cw(e){let t=e.inspect??(t=>yo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=iw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(ow(r)),r}function lw(e){return new r(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{cw({lockDir:me(he(e(),process.cwd())),json:t.json===!0})})}function uw(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function dw(e){let t=e.inspect??(t=>yo(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=uw(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function fw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{dw({lockDir:me(he(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const pw=1e4,mw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function hw(e){let t=e.upstreamTimeoutMs??pw,n=$n((n,r)=>{_w(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 gw(e,t,n){_w(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??pw)}function _w(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of mw)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=er({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of mw)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function vw(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function yw(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,readServerLock:a,releaseUiLock:o,updateUiLockPort:s}=await import(`./dist-CUNdZ2_C.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-DfUzFdTC.mjs`),d=l(e.config,e.cwd),f=u(d);i(f,{port:0,worktreeRoot:e.cwd});let p=import.meta.dirname??new URL(`.`,import.meta.url).pathname,m=[r(p,`public`),r(p,`../../app/dist`),r(p,`../../../app/dist`)].find(e=>t(e)),h=m?c(m,{single:!0,gzip:!0,immutable:!0}):null,g=t(d)?c(d,{dotfiles:!1,dev:!0}):null,_=e.port,v=null,y=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){v?.();let n=a(f),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:_});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/`)){v?.();let r=a(f);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}gw(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&g){t.setHeader(`X-Content-Type-Options`,`nosniff`),g(e,t,()=>{h?h(e,t):bw(t)});return}if(h){h(e,t);return}bw(t)},x=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],S=[],C=e.port;try{for(let e of x){let t=n(y);S.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(C,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(C=e.port),n()})})}}catch(e){await Promise.all(S.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let w=C;_=w,s(f,w);let ee=e.scheduler??b,T=e.safetyNetMs??432e5,E=null,te=!1,ne=!1,re=()=>{te||(te=!0,E!==null&&(ee.clearTimeout(E),E=null))},ie=()=>{if(re(),!ne){ne=!0;try{o(f)}catch{}}},ae=()=>{te||T<=0||(E!==null&&(ee.clearTimeout(E),E=null),E=ee.setTimeout(()=>{E=null,console.warn(`[ui] safety-net (${T}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of S)try{e.close()}catch{}ie()},T))},oe=()=>{te||T<=0||ae()};return v=oe,ae(),{httpServers:S,port:w,release:ie,detachSafetyNet:re,nudgeSafetyNet:oe}}function bw(e){e.writeHead(404),e.end(`Not found`)}function xw(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 Sw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-CUNdZ2_C.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 hw({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Cw(e){return new r(`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-BnZ-i-vb.mjs`),{UiLockCollisionError:r}=await import(`./dist-CUNdZ2_C.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-DfUzFdTC.mjs`),o=e(),s=t.host,c;try{c=xw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await yw({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};vw(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await Sw({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const ww=new r;let Tw;ww.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(c).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=ze(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),Tw=r});const Ew=hn(()=>Tw);ww.addCommand(Ew,{isDefault:!0});const Dw=qC(()=>Tw);ww.addCommand(Dw),ww.addCommand(Ae()),ww.addCommand(rw()),ww.addCommand(Fo());const Ow=JC(()=>Tw);ww.addCommand(Ow);const kw=Cw(()=>Tw);ww.addCommand(kw),ww.addCommand(fw(()=>Tw)),ww.addCommand(So(()=>Tw)),ww.addCommand(lw(()=>Tw)),ww.addCommand(vo(()=>Tw)),ww.addCommand(jo(()=>Tw)),ww.addCommand(ZC(()=>Tw)),ww.addCommand($C(()=>Tw)),ww.addCommand(QC(()=>Tw)),await ww.parseAsync();export{};
1405
1405
  //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./dist-DRC09WNZ.mjs";var e=`0.0.0-dev-20260428024726`;const t=`config.yml`,n=`cache`,r=e,i=`open-knowledge`;export{r as i,t as n,i as r,n as t};
2
+ //# sourceMappingURL=constants-Bypdthtt.mjs.map
@@ -74,7 +74,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
74
74
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
75
75
  `).trim();e&&r.push(e)}return r}function reconcile(e){if(isSystemDoc(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return containsConflictMarkers(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:mergeBlocks(splitMarkdownBlocks(t),splitMarkdownBlocks(n),splitMarkdownBlocks(r))}function mergeBlocks(e,t,n){let r=computeEditOps(e,t),i=computeEditOps(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
76
76
 
77
- `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(!r)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(!t)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(!t)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!isSystemDoc(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&&registerDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&&registerDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path));if(o.length===0)return;let s=await classifyEvents(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CblsKfnx.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_VERSION=1,MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.open-knowledge`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:MANAGED_RENAME_JOURNAL_VERSION,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==MANAGED_RENAME_JOURNAL_VERSION)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return parseManagedRenameRecoveryJournal(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);mkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;writeFileSync(r,JSON.stringify(t,null,2),`utf-8`),renameSync(r,n)}function clearManagedRenameJournal(e){rmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);mkdirSync(dirname(t),{recursive:!0}),writeFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=safeContentPath(t.destinationDocName,e);try{rmSync(n,{force:!0})}catch(e){throw existsSync(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$1(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$1(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$1(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$1(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$1(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function buildRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$1(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=readMarkdownLink$1(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=buildRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$1(e,r)&&(r=null),`${e}${a}`;let o=matchFence$1(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$1(e,i)&&(i=null),`${e}${o}`;let s=matchFence$1(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
77
+ `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!isSystemDoc(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&&registerDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&&registerDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path));if(o.length===0)return;let s=await classifyEvents(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CblsKfnx.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_VERSION=1,MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.open-knowledge`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:MANAGED_RENAME_JOURNAL_VERSION,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==MANAGED_RENAME_JOURNAL_VERSION)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return parseManagedRenameRecoveryJournal(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);mkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;writeFileSync(r,JSON.stringify(t,null,2),`utf-8`),renameSync(r,n)}function clearManagedRenameJournal(e){rmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);mkdirSync(dirname(t),{recursive:!0}),writeFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=safeContentPath(t.destinationDocName,e);try{rmSync(n,{force:!0})}catch(e){throw existsSync(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$1(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$1(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$1(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$1(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$1(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function buildRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$1(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$1(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=readMarkdownLink$1(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=buildRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$1(e,r)&&(r=null),`${e}${a}`;let o=matchFence$1(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$1(e,i)&&(i=null),`${e}${o}`;let s=matchFence$1(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
78
78
  title: Work Log
79
79
  description: Append-only audit trail. After each turn that creates, edits, or restructures content in the knowledge base, append one dated entry here (one per turn, not per file). Silent edits break the audit trail.
80
80
  ---
@@ -139,4 +139,4 @@ What to log:
139
139
  ---`,4);if(!e.startsWith(`---
140
140
  `)||t<0)return;let n=e.slice(4,t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
141
141
  `).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,n={}){let r=statSync(e).size;if(r>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${r} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let i=await sha256OfFile(e),a=await readFile(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(a.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let o=extractMetadataVersion(a);if(!n.skipVersionCheck){if(!o)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(o!==t)throw Error(`SKILL.md metadata.version (${o}) does not match CLI version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:r,sha256:i,skillVersion:o}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),n=e.outputPath??join(process.cwd(),`openknowledge.skill`),r=await readCliVersion();await zipDirectory(t,n);let{size:i,sha256:a,skillVersion:o}=await validateSkillZip(n,r,{skipVersionCheck:e.skipVersionCheck});return{outputPath:n,size:i,sha256:a,cliVersion:r,skillVersion:o}}function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):n===`win32`?existsSync(join(r.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}const SIDECAR_FILENAME=`skill-installed-version`,SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.open-knowledge`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a)return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}export{getTracer as $,bootServer as A,saveInMemoryCheckpoint as At,createApiExtension as B,updateUiLockPort as Bt,SeedRootDirError as C,removeLastKnownHash as Ct,applyExternalChange as D,safeContentPath as Dt,applyAgentMarkdownWrite as E,rewriteWikiLinksForDocumentRename as Et,commitWip as F,splitMarkdownBlocks as Ft,createServerObserverExtension as G,writeTracker as Gt,createLiveDerivedIndexExtension as H,validateSkillZip as Ht,commitWipFromTree as I,startWatcher as It,evictStaleTrackerEntries as J,getWipRefPattern as Jt,detectClaudeDesktopPresence as K,require_picomatch as Kt,containsConflictMarkers as L,starterFolderRule as Lt,buildWipTree as M,setActiveSpanAttributes as Mt,classifyEvents as N,shadowGit as Nt,applySeed as O,safeSubdir as Ot,commitUpstreamImport as P,shutdownTelemetry as Pt,getMetrics as Q,contentHash as R,toBroadcasterKey as Rt,SeedPrerequisiteError as S,releaseUiLock as St,acquireUiLock as T,rewriteMarkdownLinksForDocumentRename as Tt,createPersistenceExtension as U,withSpan as Ut,createContentFilter as V,validateAgentId as Vt,createServer$1 as W,withSpanSync as Wt,getLogger as X,readContributors as Xt,extractWikiLinksFromMarkdown as Y,parseWriterId as Yt,getMeter as Z,ProjectGitInitError as _,readBranchFromHead as _t,BacklinkIndex as a,installUserSkill as at,SERVICE_WRITER as b,recordContributor as bt,FILE_SYSTEM_WRITER as c,isSystemDoc as ct,HocuspocusAuthRejection as d,loadPrincipal as dt,handleCollabSocketError as et,HocuspocusAuthTokenSchema as f,loggerFactory as ft,PinoLogger as g,planSeed as gt,OBSERVER_SYNC_ORIGIN as h,pathToDocName as ht,AgentSessionManager as i,initTelemetry as it,buildSkillZip as j,saveVersion as jt,attachIdleShutdown as k,safetyCheckpoint as kt,FILE_WATCHER_ORIGIN as l,lastKnownHash as lt,MANAGED_RENAME_ORIGIN as m,parseKeepaliveConnectionId as mt,AgentFocusBroadcaster as n,incrementServerObserverFire as nt,CC1Broadcaster as o,isPairedWriteOrigin as ot,LOG_MD_TEMPLATE as p,parseHocuspocusAuthToken as pt,ensureProjectGit as q,getShadowRepoPath as qt,AgentPresenceBroadcaster as r,initShadowRepo as rt,CONFLICT_MARKER_RE as s,isSelfWrite as st,AGENT_ID_RE as t,incrementCollabSocketFilteredError as tt,GIT_UPSTREAM_WRITER as u,listRescueCheckpoints as ut,ROLLBACK_ORIGIN as v,readUiLock as vt,UiLockCollisionError as w,resolveBundledSkillDir as wt,STARTER_FOLDERS as x,registerWrite as xt,SEED_CONFIG_FILENAME as y,reconcile as yt,contributorCount as z,updateLastKnownHash as zt};
142
- //# sourceMappingURL=dist-BWvkug8h.mjs.map
142
+ //# sourceMappingURL=dist-BW0CmwMf.mjs.map
@@ -1 +1 @@
1
- import"./dist-DRC09WNZ.mjs";import{a as e,c as t}from"./server-lock-CH0GCP_4-DXqutMlt.mjs";import{A as n,Bt as r,St as i,T as a,X as o,_ as s,q as c,vt as l,w as u}from"./dist-BWvkug8h.mjs";export{s as ProjectGitInitError,u as UiLockCollisionError,a as acquireUiLock,n as bootServer,c as ensureProjectGit,o as getLogger,e as isProcessAlive,t as readServerLock,l as readUiLock,i as releaseUiLock,r as updateUiLockPort};
1
+ import"./dist-DRC09WNZ.mjs";import{a as e,c as t}from"./server-lock-CH0GCP_4-DXqutMlt.mjs";import{A as n,Bt as r,St as i,T as a,X as o,_ as s,q as c,vt as l,w as u}from"./dist-BW0CmwMf.mjs";export{s as ProjectGitInitError,u as UiLockCollisionError,a as acquireUiLock,n as bootServer,c as ensureProjectGit,o as getLogger,e as isProcessAlive,t as readServerLock,l as readUiLock,i as releaseUiLock,r as updateUiLockPort};