@inkeep/open-knowledge 0.0.0-dev-20260429202929 → 0.0.0-dev-20260429215316

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs 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-wByiX8MO.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-D9c9yAAt.mjs";import{$ as u,B as d,G as f,H as p,J as m,K as h,Q as g,R as _,U as v,V as y,W as b,X as x,Y as S,Z as ee,ct as te,dt as ne,et as C,ft as w,g as re,gt as ie,h as T,ht as ae,it as oe,lt as se,mt as ce,pt as le,q as ue,rt as de,st as fe,tt as pe,ut as me,w as he,z as ge}from"./dist-CIeZOXfv.mjs";import{n as _e,t as ve}from"./paths-B6FFLWys.mjs";import{l as ye,o as be,s as xe}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as Se}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{$t as Ce,A as we,C as Te,Ct as Ee,P as De,Qt as Oe,bt as ke,en as Ae,nn as je,tn as Me}from"./dist-DD_wEI4a.mjs";import{r as Ne}from"./init-Cy9EOwXR.mjs";import{i as Pe,n as Fe,o as Ie,r as Le,s as Re,t as ze}from"./colors-DoPZvo1q.mjs";import{t as Be}from"./is-object-BNVklKxg.mjs";import{i as Ve,n as He,t as Ue}from"./loader-CEH4lcXo.mjs";import{t as We}from"./chunk-YNYSPYQ5-BpP11HXS.mjs";import{a as Ge,c as Ke,d as qe,f as Je,h as Ye,i as Xe,l as Ze,m as Qe,n as $e,o as et,p as tt,r as nt,s as rt,t as it,u as at}from"./chunk-GFQRA5P5-1fzItQ8F.mjs";import{A as ot,B as st,C as ct,D as lt,E as ut,F as dt,H as ft,I as pt,L as mt,M as ht,N as gt,O as _t,P as vt,S as yt,T as bt,V as xt,_ as St,a as Ct,b as wt,c as Tt,d as Et,f as E,g as Dt,h as Ot,i as kt,j as At,k as jt,l as Mt,m as Nt,n as Pt,o as Ft,p as It,r as Lt,s as Rt,t as zt,u as Bt,v as Vt,w as Ht,x as Ut,y as Wt,z as Gt}from"./chunk-FEIOJCZD-C4x0A4rb.mjs";import{a as Kt,c as qt,d as Jt,i as D,l as Yt,n as Xt,o as Zt,r as Qt,s as O,t as $t,u as en}from"./chunk-XHM67O4N-Cg35xc6b.mjs";import{n as tn,r as nn,t as rn}from"./chunk-R6VWJ2ZL-B0CcMPyK.mjs";import{r as an}from"./chunk-CWQS3NFK-DFdwmFxJ.mjs";import"./chunk-DXB73IDG-C774okS0.mjs";import{n as on,t as sn}from"./chunk-5QMZ5MUS-DWTkM0vM.mjs";import{n as cn,t as ln}from"./chunk-A5O5YHGN-C7BVq0eF.mjs";import{n as un,r as dn,t as fn}from"./chunk-OJDRYQWQ-BV5MVRVg.mjs";import{r as pn,t as mn}from"./chunk-24IMIIXA-Bz7rlZT3.mjs";import{n as hn}from"./chunk-3THT3N7L-klp8GP84.mjs";import{t as gn}from"./chunk-44UOCSGV-BUBpWxXm.mjs";import{o as _n,s as vn}from"./start-CtVd4Gd7.mjs";import"./src-DeBzWG40.mjs";import{execFileSync as yn,spawn as bn}from"node:child_process";import*as k from"node:path";import xn,{basename as Sn,dirname as Cn,isAbsolute as wn,join as Tn,relative as En,resolve as Dn}from"node:path";import*as A from"node:fs";import{appendFileSync as On,closeSync as kn,existsSync as An,mkdirSync as jn,openSync as Mn,readFileSync as Nn,readdirSync as Pn,realpathSync as Fn,statSync as In,unlinkSync as Ln,writeFileSync as Rn}from"node:fs";import zn from"node:process";import{homedir as Bn,hostname as Vn,platform as Hn}from"node:os";import{AsyncLocalStorage as Un,AsyncResource as Wn}from"node:async_hooks";import{stripVTControlCharacters as Gn,styleText as Kn}from"node:util";import*as qn from"node:readline";import{fileURLToPath as Jn}from"node:url";import{randomUUID as Yn}from"node:crypto";import{setTimeout as Xn}from"node:timers/promises";import{mkdir as Zn,readFile as Qn,readdir as $n,stat as er}from"node:fs/promises";import{createServer as tr,request as nr}from"node:http";import{lookup as rr}from"node:dns";import{createInterface as ir}from"node:readline/promises";var ar=i();const or=`open-knowledge`;var sr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(or,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(or,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(or,e).deletePassword()}catch{}}},cr=class{backend=`file`;authFile;constructor(e){this.authFile=e??Tn(Bn(),`.open-knowledge`,`auth.yml`)}read(){if(!An(this.authFile))return{};try{return(0,ar.parse)(Nn(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=Cn(this.authFile);An(t)||jn(t,{recursive:!0,mode:448}),Rn(this.authFile,(0,ar.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 lr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(or,`__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-wByiX8MO.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-klIiSe5w.mjs";import{$ as u,B as d,G as f,H as p,J as m,K as h,Q as g,R as _,U as v,V as y,W as b,X as x,Y as S,Z as ee,ct as te,dt as ne,et as C,ft as w,g as re,gt as ie,h as T,ht as ae,it as oe,lt as se,mt as ce,pt as le,q as ue,rt as de,st as fe,tt as pe,ut as me,w as he,z as ge}from"./dist-CIeZOXfv.mjs";import{n as _e,t as ve}from"./paths-DHCHC69r.mjs";import{l as ye,o as be,s as xe}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as Se}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{$t as Ce,A as we,C as Te,Ct as Ee,P as De,Qt as Oe,bt as ke,en as Ae,nn as je,tn as Me}from"./dist-zf-BoTF_.mjs";import{r as Ne}from"./init-BIyMdhLL.mjs";import{i as Pe,n as Fe,o as Ie,r as Le,s as Re,t as ze}from"./colors-DoPZvo1q.mjs";import{t as Be}from"./is-object-BNVklKxg.mjs";import{i as Ve,n as He,t as Ue}from"./loader-Cbt92LQl.mjs";import{t as We}from"./chunk-YNYSPYQ5-BpP11HXS.mjs";import{a as Ge,c as Ke,d as qe,f as Je,h as Ye,i as Xe,l as Ze,m as Qe,n as $e,o as et,p as tt,r as nt,s as rt,t as it,u as at}from"./chunk-GFQRA5P5-1fzItQ8F.mjs";import{A as ot,B as st,C as ct,D as lt,E as ut,F as dt,H as ft,I as pt,L as mt,M as ht,N as gt,O as _t,P as vt,S as yt,T as bt,V as xt,_ as St,a as Ct,b as wt,c as Tt,d as Et,f as E,g as Dt,h as Ot,i as kt,j as At,k as jt,l as Mt,m as Nt,n as Pt,o as Ft,p as It,r as Lt,s as Rt,t as zt,u as Bt,v as Vt,w as Ht,x as Ut,y as Wt,z as Gt}from"./chunk-FEIOJCZD-C4x0A4rb.mjs";import{a as Kt,c as qt,d as Jt,i as D,l as Yt,n as Xt,o as Zt,r as Qt,s as O,t as $t,u as en}from"./chunk-XHM67O4N-Cg35xc6b.mjs";import{n as tn,r as nn,t as rn}from"./chunk-R6VWJ2ZL-B0CcMPyK.mjs";import{r as an}from"./chunk-CWQS3NFK-DFdwmFxJ.mjs";import"./chunk-DXB73IDG-C774okS0.mjs";import{n as on,t as sn}from"./chunk-5QMZ5MUS-DWTkM0vM.mjs";import{n as cn,t as ln}from"./chunk-A5O5YHGN-C7BVq0eF.mjs";import{n as un,r as dn,t as fn}from"./chunk-OJDRYQWQ-BV5MVRVg.mjs";import{r as pn,t as mn}from"./chunk-24IMIIXA-Bz7rlZT3.mjs";import{n as hn}from"./chunk-3THT3N7L-klp8GP84.mjs";import{t as gn}from"./chunk-44UOCSGV-BUBpWxXm.mjs";import{o as _n,s as vn}from"./start-DUpc-bZp.mjs";import"./src-BrGv1aC7.mjs";import{execFileSync as yn,spawn as bn}from"node:child_process";import*as k from"node:path";import xn,{basename as Sn,dirname as Cn,isAbsolute as wn,join as Tn,relative as En,resolve as Dn}from"node:path";import*as A from"node:fs";import{appendFileSync as On,closeSync as kn,existsSync as An,mkdirSync as jn,openSync as Mn,readFileSync as Nn,readdirSync as Pn,realpathSync as Fn,statSync as In,unlinkSync as Ln,writeFileSync as Rn}from"node:fs";import zn from"node:process";import{homedir as Bn,hostname as Vn,platform as Hn}from"node:os";import{AsyncLocalStorage as Un,AsyncResource as Wn}from"node:async_hooks";import{stripVTControlCharacters as Gn,styleText as Kn}from"node:util";import*as qn from"node:readline";import{fileURLToPath as Jn}from"node:url";import{randomUUID as Yn}from"node:crypto";import{setTimeout as Xn}from"node:timers/promises";import{mkdir as Zn,readFile as Qn,readdir as $n,stat as er}from"node:fs/promises";import{createServer as tr,request as nr}from"node:http";import{lookup as rr}from"node:dns";import{createInterface as ir}from"node:readline/promises";var ar=i();const or=`open-knowledge`;var sr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(or,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(or,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(or,e).deletePassword()}catch{}}},cr=class{backend=`file`;authFile;constructor(e){this.authFile=e??Tn(Bn(),`.open-knowledge`,`auth.yml`)}read(){if(!An(this.authFile))return{};try{return(0,ar.parse)(Nn(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=Cn(this.authFile);An(t)||jn(t,{recursive:!0,mode:448}),Rn(this.authFile,(0,ar.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 lr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(or,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new sr}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new cr(e)}}async function ur(e,t,n){let r=dr(await fr(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 dr(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 fr(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 pr(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 ur(process.stdin,process.stdout,t);process.exit(n)}),t}function mr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function hr(e,t,n){let r={baseUrl:mr(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 gr(e){let t=e.request||s,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),hr(t,`POST /login/device/code`,n)}async function _r(e){let t=await hr(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=vr(e,t.data.expires_in),n.refreshTokenExpiresAt=vr(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function vr(e,t){return new Date(e+t*1e3).toISOString()}async function yr(e,t){let n=br(e,t.auth);if(n)return n;let{data:r}=await gr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Sr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function br(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 xr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Sr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await _r({...i,clientType:`oauth-app`}):await _r({...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 xr(r.interval),Sr(e,t,n,r);if(a===`slow_down`)return await xr(r.interval+7),Sr(e,t,n,r);throw i}}async function Cr(e,t){return yr(e,{auth:t})}async function wr(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 yr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Tr=`0.0.0-development`;function Er(e){let t=e.request||s.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Tr} ${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(Cr.bind(null,i),{hook:wr.bind(null,i)})}async function Dr(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=Er({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 Or(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const kr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Ar(e){let t=e.toLowerCase().replace(/:\d+$/,``);kr.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 jr(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Mr(e,t,n,r=Dr){let i=Or(n),{host:a,json:o}=e;Ar(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?jr(!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?jr(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Nr(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 Mr(n,await t(),e())})}const Pr=e=>e.name===`enter`||e.name===`return`;var Fr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Ir=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Lr=class extends Error{name=`ExitPromptError`},Rr=class extends Error{name=`HookError`},zr=class extends Error{name=`ValidationError`};const Br=new Un;function Vr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Hr(e,t){let n=Vr(e);return Br.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function Ur(){let e=Br.getStore();if(!e)throw new Rr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Wr(){return Ur().rl}function Gr(e){return Wn.bind((...t)=>{let n=Ur(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Kr(e){let t=Ur(),{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 qr(){Ur().handleChange()}const Jr={queue(e){let t=Ur(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Wr());if(r!=null&&typeof r!=`function`)throw new zr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=Ur();Gr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=Ur();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Yr(e){return typeof e==`function`}function Xr(e){return Kr(t=>{let n=Wn.bind(function(e){t.get()!==e&&(t.set(e),qr())});if(t.initialized)return[t.get(),n];let r=Yr(e)?e():e;return t.set(r),[r,n]})}function Zr(e,t){Kr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Jr.queue(e),n.set(t)})}function Qr(){return zn.platform.startsWith(`win`)?!!zn.env.CI||!!zn.env.WT_SESSION||!!zn.env.TERMINUS_SUBLIME||zn.env.ConEmuTask===`{cmd::Cmder}`||zn.env.TERM_PROGRAM===`Terminus-Sublime`||zn.env.TERM_PROGRAM===`vscode`||zn.env.TERM===`xterm-256color`||zn.env.TERM===`alacritty`||zn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:zn.env.TERM!==`linux`}const $r={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:`╱`},ei={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:`⅒`},ti={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`},ni={...$r,...ei},ri={...$r,...ti},ii=Qr()?ni:ri;Object.entries(ei);const ai={prefix:{idle:Kn(`blue`,`?`),done:Kn(`green`,ii.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>Kn(`yellow`,e))},style:{answer:e=>Kn(`cyan`,e),message:e=>Kn(`bold`,e),error:e=>Kn(`red`,`> ${e}`),defaultAnswer:e=>Kn(`dim`,`(${e})`),help:e=>Kn(`dim`,e),highlight:e=>Kn(`cyan`,e),key:e=>Kn(`cyan`,Kn(`bold`,`<${e}>`))}};function oi(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 si(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=oi(n)&&oi(r)?si(n,r):r}return t}function ci(...e){return si(ai,...e.filter(e=>e!=null))}function li({status:e=`idle`,theme:t}){let[n,r]=Xr(!1),[i,a]=Xr(0),{prefix:o,spinner:s}=ci(t);return Zr(()=>{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 ui(e){return Xr({current:e})[0]}function di(e){let t=ui(e);t.current=e,Zr(e=>{let n=!1,r=Gr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var fi=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 pi=(()=>{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}})(),mi=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,hi=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,gi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_i=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,vi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,yi=/\t{1,1000}/y,bi=/[\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,xi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Si=/\p{M}+/gu,Ci={limit:1/0,ellipsis:``},wi=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?wi(i,Ci,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[xi,l],[gi,0],[_i,o],[yi,s],[bi,c],[vi,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(Si,``)){let t=e.codePointAt(0)||0;if(S=mi(t)?2:hi(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===vi?pi(e.slice(p,n.lastIndex)):n===bi?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}},Ti={limit:1/0,ellipsis:``,ellipsisWidth:0},Ei=(e,t={})=>wi(e,Ti,t).width,Di=`]8;;`,Oi=RegExp(`(?:\\[(?<code>\\d+)m|\\${Di}(?<uri>.*))`,`y`),ki=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},Ai=e=>`[${e}m`,ji=e=>`${Di}${e}`,Mi=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ei(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ei(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Di,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())},Ni=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ei(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Pi=(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=Ei(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=Ei(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(``),Mi(s,r,t),c=Ei(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Mi(s,r,t),c=Ei(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Mi(s,r,t),c=Ei(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ni(e)));let l=s.join(`
@@ -21,10 +21,10 @@ 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 po(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 fo(t,await e())})}async function mo(e,t){let{host:n,json:r}=e;Ar(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 uo({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 ho(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 mo(t,await e())})}async function go(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function _o(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await go(t,await e())})}async function vo(e,t){let{host:n,json:r}=e;Ar(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 uo({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 yo(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 vo(t,await e())})}function bo(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>lr(),i=e??(()=>({}));return t.addCommand(Nr(i,n)),t.addCommand(yo(n)),t.addCommand(ho(n)),t.addCommand(_o(n)),t.addCommand(po(n)),t.addCommand(pr(n)),t}function xo(e,t,n={}){let r=xe(e,t);if(!An(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Nn(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??Vn();return a.hostname===o?(n.isAlive??be)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function So(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 Co(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.unlink??(e=>Ln(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=So(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 wo(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{Co({lockDir:_e(ve(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function To(){try{let e=yn(`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 Eo(e,t,n={},r=To){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 Do(e){return e.replace(/:\d+$/,``)}function Oo(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Do(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Do(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Do(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 ko=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ao(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 ko)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function jo(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Mo(e,t,n,r=process.cwd()){let i=Oo(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?Dn(r,t.dir):Dn(r,i.name);if(An(a)&&Pn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await lr(),s=await Eo(i.hostname,o,{}),c=Se({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
23
23
  `)){let n=Ao(e);n&&n.pct!==l&&(l=n.pct,jo(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
- `);try{let{runInit:e}=await import(`./init-XmHyXWXs.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?jo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{No(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function No(e){let t=Tn(e,`.git`,`info`,`exclude`);if(!An(t))return`no-exclude`;let n=Nn(t,`utf-8`),r=new Set([T,`${T}/`,`/${T}`,`/${T}/`]);return n.split(`
24
+ `);try{let{runInit:e}=await import(`./init-8J2V1Tcs.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?jo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{No(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?jo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function No(e){let t=Tn(e,`.git`,`info`,`exclude`);if(!An(t))return`no-exclude`;let n=Nn(t,`utf-8`),r=new Set([T,`${T}/`,`/${T}`,`/${T}/`]);return n.split(`
25
25
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(Rn(t,`${n}${n.length===0||n.endsWith(`
26
26
  `)?``:`
27
- `}${T}/\n`,`utf-8`),`appended`)}function Po(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 Mo(t,{json:r.json,dir:n},i);if(r.json)jo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-3Hy5XBnx.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?jo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}function Fo(e=Bn()){return Tn(e,`Downloads`,`openknowledge.skill`)}function Io(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 Lo(e={}){let t=Dn(e.out??Fo()),n=e.platformName??Hn(),r=e.spawnFn??bn;try{await Zn(Cn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Le(`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:`${Le(`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:[Ie(`Built ${i.outputPath}`),Fe(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Pe(` Open the Claude Desktop App, then: ${ze(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
27
+ `}${T}/\n`,`utf-8`),`appended`)}function Po(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 Mo(t,{json:r.json,dir:n},i);if(r.json)jo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-9trF3lxw.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?jo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}function Fo(e=Bn()){return Tn(e,`Downloads`,`openknowledge.skill`)}function Io(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 Lo(e={}){let t=Dn(e.out??Fo()),n=e.platformName??Hn(),r=e.spawnFn??bn;try{await Zn(Cn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Le(`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:`${Le(`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:[Ie(`Built ${i.outputPath}`),Fe(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Pe(` Open the Claude Desktop App, then: ${ze(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
28
28
  `),exitCode:0};let a=Io(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:[Ie(`Built ${i.outputPath}`),Fe(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}… • CLI v${i.cliVersion}`),Pe(` Claude Desktop App opened. Now upload the file manually:`),` 1. ${ze(`Customize`)} (sidebar) → ${ze(`Skills`)}`,` 2. Click the ${ze(`+`)} button`,` 3. Click ${ze(`Create skill`)}`,` 4. Click ${ze(`Upload skill`)}`,` 5. Pick ${ze(`openknowledge.skill`)} from Downloads`,Fe(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${i.outputPath}`)].join(`
29
29
  `),exitCode:0}:{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Ie(`Built ${i.outputPath}`),Re(` Handoff failed: ${a.message}`),Pe(` Open the Claude Desktop App, then: ${ze(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
30
30
  `),exitCode:0}}function Ro(){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 Lo({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var j;(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})(j||={});var zo;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(zo||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Bo=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=j.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 Vo=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,j.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()}};Vo.create=e=>new Vo(e);const Ho=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.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}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.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 N.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 N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let Uo=Ho;function Wo(){return Uo}const Go=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 P(e,t){let n=Wo(),r=Go({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ho?void 0:Ho].filter(e=>!!e)});e.common.issues.push(r)}var Ko=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 F;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 F;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 F=Object.freeze({status:`aborted`}),qo=e=>({status:`dirty`,value:e}),Jo=e=>({status:`valid`,value:e}),Yo=e=>e.status===`aborted`,Xo=e=>e.status===`dirty`,Zo=e=>e.status===`valid`,Qo=e=>typeof Promise<`u`&&e instanceof Promise;var I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var $o=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 es=(e,t)=>{if(Zo(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 Vo(e.common.issues),this._error}}};function L(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 R=class{get description(){return this._def.description}_getType(e){return Bo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Bo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ko,ctx:{common:e.parent.common,data:e.data,parsedType:Bo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Qo(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:Bo(e)};return es(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:Bo(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Zo(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=>Zo(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:Bo(e)},r=this._parse({data:e,path:n.path,parent:n});return es(n,await(Qo(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:N.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 nc({schema:this,typeName:z.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 rc.create(this,this._def)}nullable(){return ic.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ls.create(this)}promise(){return tc.create(this,this._def)}or(e){return Bs.create([this,e],this._def)}and(e){return Ws.create(this,e,this._def)}transform(e){return new nc({...L(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ac({...L(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new cc({typeName:z.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new oc({...L(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return lc.create(this,e)}readonly(){return uc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ts=/^c[^\s-]{8,}$/i,ns=/^[0-9a-z]+$/,rs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,is=/^[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,as=/^[a-z0-9_-]{21}$/i,os=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ss=/^[-+]?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)?)??$/,cs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ls;const us=/^(?:(?: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])$/,ds=/^(?:(?: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])$/,fs=/^(([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]))$/,ps=/^(([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])$/,ms=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gs=`((\\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])))`,_s=RegExp(`^${gs}$`);function vs(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 ys(e){return RegExp(`^${vs(e)}$`)}function bs(e){let t=`${gs}T${vs(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xs(e,t){return!!((t===`v4`||!t)&&us.test(e)||(t===`v6`||!t)&&fs.test(e))}function Ss(e,t){if(!os.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 Cs(e,t){return!!((t===`v4`||!t)&&ds.test(e)||(t===`v6`||!t)&&ps.test(e))}var ws=class e extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new Ko,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.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?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)cs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ls||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),ls.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)is.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)as.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ts.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ns.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)rs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.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),P(n,{validation:`regex`,code:N.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),P(n,{code:N.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),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_s.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ys(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?ss.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ss(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Cs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ms.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?hs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.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}};ws.create=e=>new ws({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...L(e)});function Ts(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 Es=class e extends R{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)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new Ko;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ts(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.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`&&j.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)}};Es.create=e=>new Es({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...L(e)});var Ds=class e extends R{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)!==M.bigint)return this._getInvalidInput(e);let t,n=new Ko;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),P(t,{code:N.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),P(t,{code:N.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),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.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:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.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}};Ds.create=e=>new Ds({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var Os=class extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return Jo(e.data)}};Os.create=e=>new Os({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var ks=class e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new Ko,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.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),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.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:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.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)}};ks.create=e=>new ks({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...L(e)});var As=class extends R{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return Jo(e.data)}};As.create=e=>new As({typeName:z.ZodSymbol,...L(e)});var js=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return Jo(e.data)}};js.create=e=>new js({typeName:z.ZodUndefined,...L(e)});var Ms=class extends R{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return Jo(e.data)}};Ms.create=e=>new Ms({typeName:z.ZodNull,...L(e)});var Ns=class extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return Jo(e.data)}};Ns.create=e=>new Ns({typeName:z.ZodAny,...L(e)});var Ps=class extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Jo(e.data)}};Ps.create=e=>new Ps({typeName:z.ZodUnknown,...L(e)});var Fs=class extends R{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};Fs.create=e=>new Fs({typeName:z.ZodNever,...L(e)});var Is=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return Jo(e.data)}};Is.create=e=>new Is({typeName:z.ZodVoid,...L(e)});var Ls=class e extends R{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.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&&(P(t,{code:N.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&&(P(t,{code:N.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 $o(t,e,t.path,n)))).then(e=>Ko.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new $o(t,e,t.path,n)));return Ko.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};Ls.create=(e,t)=>new Ls({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...L(t)});function Rs(e){if(e instanceof zs){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rc.create(Rs(r))}return new zs({...e._def,shape:()=>t})}else if(e instanceof Ls)return new Ls({...e._def,type:Rs(e.element)});else if(e instanceof rc)return rc.create(Rs(e.unwrap()));else if(e instanceof ic)return ic.create(Rs(e.unwrap()));else if(e instanceof Gs)return Gs.create(e.items.map(e=>Rs(e)));else return e}var zs=class e extends R{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:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fs&&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 $o(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Fs){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&&(P(n,{code:N.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 $o(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=>Ko.mergeObjectSync(t,e)):Ko.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.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:I.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:z.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 j.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 j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Rs(this)}partial(t){let n={};for(let e of j.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 j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Qs(j.objectKeys(this.shape))}};zs.create=(e,t)=>new zs({shape:()=>e,unknownKeys:`strip`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)}),zs.strictCreate=(e,t)=>new zs({shape:()=>e,unknownKeys:`strict`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)}),zs.lazycreate=(e,t)=>new zs({shape:e,unknownKeys:`strip`,catchall:Fs.create(),typeName:z.ZodObject,...L(t)});var Bs=class extends R{_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 Vo(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}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 Vo(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};Bs.create=(e,t)=>new Bs({options:e,typeName:z.ZodUnion,...L(t)});const Vs=e=>e instanceof Xs?Vs(e.schema):e instanceof nc?Vs(e.innerType()):e instanceof Zs?[e.value]:e instanceof $s?e.options:e instanceof ec?j.objectValues(e.enum):e instanceof ac?Vs(e._def.innerType):e instanceof js?[void 0]:e instanceof Ms?[null]:e instanceof rc?[void 0,...Vs(e.unwrap())]:e instanceof ic?[null,...Vs(e.unwrap())]:e instanceof cc||e instanceof uc?Vs(e.unwrap()):e instanceof oc?Vs(e._def.innerType):[];var Hs=class e extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;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}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=Vs(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:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function Us(e,t){let n=Bo(e),r=Bo(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Us(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.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=Us(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Ws=class extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Yo(e)||Yo(r))return F;let i=Us(e.value,r.value);return i.valid?((Xo(e)||Xo(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};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}))}};Ws.create=(e,t,n)=>new Ws({left:e,right:t,typeName:z.ZodIntersection,...L(n)});var Gs=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.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 $o(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Ko.mergeArray(t,e)):Ko.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Gs.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Gs({items:e,typeName:z.ZodTuple,rest:null,...L(t)})};var Ks=class e extends R{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!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new $o(n,e,n.path,e)),value:a._parse(new $o(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Ko.mergeObjectAsync(t,r):Ko.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof R?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...L(r)}):new e({keyType:ws.create(),valueType:t,typeName:z.ZodRecord,...L(n)})}},qs=class extends R{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!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new $o(n,e,n.path,[a,`key`])),value:i._parse(new $o(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 F;(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 F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qs.create=(e,t,n)=>new qs({valueType:t,keyType:e,typeName:z.ZodMap,...L(n)});var Js=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.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&&(P(n,{code:N.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 F;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 $o(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:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Js.create=(e,t)=>new Js({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...L(t)});var Ys=class e extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return Go({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wo(),Ho].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return Go({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wo(),Ho].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof tc){let e=this;return Jo(async function(...t){let o=new Vo([]),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 Jo(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Vo([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Vo([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:Gs.create(t).rest(Ps.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||Gs.create([]).rest(Ps.create()),returns:n||Ps.create(),typeName:z.ZodFunction,...L(r)})}},Xs=class extends R{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})}};Xs.create=(e,t)=>new Xs({getter:e,typeName:z.ZodLazy,...L(t)});var Zs=class extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Zs.create=(e,t)=>new Zs({value:e,typeName:z.ZodLiteral,...L(t)});function Qs(e,t){return new $s({values:e,typeName:z.ZodEnum,...L(t)})}var $s=class e extends R{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:j.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return Jo(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})}};$s.create=Qs;var ec=class extends R{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return P(n,{expected:j.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return Jo(e.data)}get enum(){return this._def.values}};ec.create=(e,t)=>new ec({values:e,typeName:z.ZodNativeEnum,...L(t)});var tc=class extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):Jo((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tc.create=(e,t)=>new tc({type:e,typeName:z.ZodPromise,...L(t)});var nc=class extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.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=>{P(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 F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?qo(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?qo(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`?F:(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`?F:(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(!Zo(e))return F;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=>Zo(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);j.assertNever(r)}};nc.create=(e,t,n)=>new nc({schema:e,typeName:z.ZodEffects,effect:t,...L(n)}),nc.createWithPreprocess=(e,t,n)=>new nc({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...L(n)});var rc=class extends R{_parse(e){return this._getType(e)===M.undefined?Jo(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rc.create=(e,t)=>new rc({innerType:e,typeName:z.ZodOptional,...L(t)});var ic=class extends R{_parse(e){return this._getType(e)===M.null?Jo(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ic.create=(e,t)=>new ic({innerType:e,typeName:z.ZodNullable,...L(t)});var ac=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ac.create=(e,t)=>new ac({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var oc=class extends R{_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 Qo(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Vo(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Vo(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};oc.create=(e,t)=>new oc({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var sc=class extends R{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};sc.create=e=>new sc({typeName:z.ZodNaN,...L(e)});var cc=class extends R{_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}},lc=class e extends R{_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`?F:e.status===`dirty`?(t.dirty(),qo(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`?F: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:z.ZodPipeline})}},uc=class extends R{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Zo(e)&&(e.value=Object.freeze(e.value)),e);return Qo(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};uc.create=(e,t)=>new uc({innerType:e,typeName:z.ZodReadonly,...L(t)}),zs.lazycreate;var z;(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`})(z||={}),ws.create,Es.create,sc.create,Ds.create,Os.create,ks.create,As.create,js.create,Ms.create,Ns.create,Ps.create,Fs.create,Is.create,Ls.create;const dc=zs.create;zs.strictCreate,Bs.create,Hs.create,Ws.create,Gs.create,Ks.create,qs.create,Js.create,Ys.create,Xs.create,Zs.create,$s.create,ec.create,tc.create,nc.create,rc.create,ic.create,nc.createWithPreprocess,lc.create;const fc=ie(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);te.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>se(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ne(e,t,n),e.parseAsync=async(t,n)=>me(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>w(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)=>le(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),pc=ie(`ZodMiniObject`,(e,t)=>{fe.init(e,t),fc.init(e,t),ce(e,`shape`,()=>t.shape)});function mc(e,t){return new pc({type:`object`,shape:e??{},...ae(t)})}function hc(e){return!!e._zod}function gc(e){let t=Object.values(e);if(t.length===0)return mc({});let n=t.every(hc),r=t.every(e=>!hc(e));if(n)return mc(e);if(r)return dc(e);throw Error(`Mixed Zod versions detected in object shape.`)}function _c(e,t){return hc(e)?ne(e,t):e.safeParse(t)}async function vc(e,t){return hc(e)?await w(e,t):await e.safeParseAsync(t)}function yc(e){if(!e)return;let t;if(t=hc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function bc(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 gc(e)}}if(hc(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 xc(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 Sc(e){return e.description}function Cc(e){if(hc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function wc(e){if(hc(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 Tc=`2025-11-25`,Ec=[Tc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Dc=`io.modelcontextprotocol/related-task`,Oc=v(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),kc=C([u(),m().int()]),Ac=u();ue({ttl:m().optional(),pollInterval:m().optional()});const jc=S({ttl:m().optional()}),Mc=S({taskId:u()}),Nc=ue({progressToken:kc.optional(),[Dc]:Mc.optional()}),Pc=S({_meta:Nc.optional()}),Fc=Pc.extend({task:jc.optional()}),Ic=e=>Fc.safeParse(e).success,Lc=S({method:u(),params:Pc.loose().optional()}),Rc=S({_meta:Nc.optional()}),zc=S({method:u(),params:Rc.loose().optional()}),Bc=ue({_meta:Nc.optional()}),Vc=C([u(),m().int()]),Hc=S({jsonrpc:h(`2.0`),id:Vc,...Lc.shape}).strict(),Uc=e=>Hc.safeParse(e).success,Wc=S({jsonrpc:h(`2.0`),...zc.shape}).strict(),Gc=e=>Wc.safeParse(e).success,Kc=S({jsonrpc:h(`2.0`),id:Vc,result:Bc}).strict(),qc=e=>Kc.safeParse(e).success;var B;(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`})(B||={});const Jc=S({jsonrpc:h(`2.0`),id:Vc.optional(),error:S({code:m().int(),message:u(),data:pe().optional()})}).strict(),Yc=e=>Jc.safeParse(e).success,Xc=C([Hc,Wc,Kc,Jc]);C([Kc,Jc]);const Zc=Bc.strict(),Qc=Rc.extend({requestId:Vc.optional(),reason:u().optional()}),$c=zc.extend({method:h(`notifications/cancelled`),params:Qc}),el=S({icons:y(S({src:u(),mimeType:u().optional(),sizes:y(u()).optional(),theme:ge([`light`,`dark`]).optional()})).optional()}),tl=S({name:u(),title:u().optional()}),nl=tl.extend({...tl.shape,...el.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),rl=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,f(S({form:f(S({applyDefaults:p().optional()}),g(u(),pe())).optional(),url:Oc.optional()}),g(u(),pe()).optional())),il=ue({list:Oc.optional(),cancel:Oc.optional(),requests:ue({sampling:ue({createMessage:Oc.optional()}).optional(),elicitation:ue({create:Oc.optional()}).optional()}).optional()}),al=ue({list:Oc.optional(),cancel:Oc.optional(),requests:ue({tools:ue({call:Oc.optional()}).optional()}).optional()}),ol=S({experimental:g(u(),Oc).optional(),sampling:S({context:Oc.optional(),tools:Oc.optional()}).optional(),elicitation:rl.optional(),roots:S({listChanged:p().optional()}).optional(),tasks:il.optional(),extensions:g(u(),Oc).optional()}),sl=Pc.extend({protocolVersion:u(),capabilities:ol,clientInfo:nl}),cl=Lc.extend({method:h(`initialize`),params:sl}),ll=S({experimental:g(u(),Oc).optional(),logging:Oc.optional(),completions:Oc.optional(),prompts:S({listChanged:p().optional()}).optional(),resources:S({subscribe:p().optional(),listChanged:p().optional()}).optional(),tools:S({listChanged:p().optional()}).optional(),tasks:al.optional(),extensions:g(u(),Oc).optional()}),ul=Bc.extend({protocolVersion:u(),capabilities:ll,serverInfo:nl,instructions:u().optional()}),dl=zc.extend({method:h(`notifications/initialized`),params:Rc.optional()}),fl=Lc.extend({method:h(`ping`),params:Pc.optional()}),pl=S({progress:m(),total:x(m()),message:x(u())}),ml=S({...Rc.shape,...pl.shape,progressToken:kc}),hl=zc.extend({method:h(`notifications/progress`),params:ml}),gl=Pc.extend({cursor:Ac.optional()}),_l=Lc.extend({params:gl.optional()}),vl=Bc.extend({nextCursor:Ac.optional()}),yl=ge([`working`,`input_required`,`completed`,`failed`,`cancelled`]),bl=S({taskId:u(),status:yl,ttl:C([m(),d()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:x(m()),statusMessage:x(u())}),xl=Bc.extend({task:bl}),Sl=Rc.merge(bl),Cl=zc.extend({method:h(`notifications/tasks/status`),params:Sl}),wl=Lc.extend({method:h(`tasks/get`),params:Pc.extend({taskId:u()})}),Tl=Bc.merge(bl),El=Lc.extend({method:h(`tasks/result`),params:Pc.extend({taskId:u()})});Bc.loose();const Dl=_l.extend({method:h(`tasks/list`)}),Ol=vl.extend({tasks:y(bl)}),kl=Lc.extend({method:h(`tasks/cancel`),params:Pc.extend({taskId:u()})}),Al=Bc.merge(bl),jl=S({uri:u(),mimeType:x(u()),_meta:g(u(),pe()).optional()}),Ml=jl.extend({text:u()}),Nl=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Pl=jl.extend({blob:Nl}),Fl=ge([`user`,`assistant`]),Il=S({audience:y(Fl).optional(),priority:m().min(0).max(1).optional(),lastModified:de({offset:!0}).optional()}),Ll=S({...tl.shape,...el.shape,uri:u(),description:x(u()),mimeType:x(u()),size:x(m()),annotations:Il.optional(),_meta:x(ue({}))}),Rl=S({...tl.shape,...el.shape,uriTemplate:u(),description:x(u()),mimeType:x(u()),annotations:Il.optional(),_meta:x(ue({}))}),zl=_l.extend({method:h(`resources/list`)}),Bl=vl.extend({resources:y(Ll)}),Vl=_l.extend({method:h(`resources/templates/list`)}),Hl=vl.extend({resourceTemplates:y(Rl)}),Ul=Pc.extend({uri:u()}),Wl=Ul,Gl=Lc.extend({method:h(`resources/read`),params:Wl}),Kl=Bc.extend({contents:y(C([Ml,Pl]))}),ql=zc.extend({method:h(`notifications/resources/list_changed`),params:Rc.optional()}),Jl=Ul,Yl=Lc.extend({method:h(`resources/subscribe`),params:Jl}),Xl=Ul,Zl=Lc.extend({method:h(`resources/unsubscribe`),params:Xl}),Ql=Rc.extend({uri:u()}),$l=zc.extend({method:h(`notifications/resources/updated`),params:Ql}),eu=S({name:u(),description:x(u()),required:x(p())}),tu=S({...tl.shape,...el.shape,description:x(u()),arguments:x(y(eu)),_meta:x(ue({}))}),nu=_l.extend({method:h(`prompts/list`)}),ru=vl.extend({prompts:y(tu)}),iu=Pc.extend({name:u(),arguments:g(u(),u()).optional()}),au=Lc.extend({method:h(`prompts/get`),params:iu}),ou=S({type:h(`text`),text:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),su=S({type:h(`image`),data:Nl,mimeType:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),cu=S({type:h(`audio`),data:Nl,mimeType:u(),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),lu=S({type:h(`tool_use`),name:u(),id:u(),input:g(u(),pe()),_meta:g(u(),pe()).optional()}),uu=S({type:h(`resource`),resource:C([Ml,Pl]),annotations:Il.optional(),_meta:g(u(),pe()).optional()}),du=C([ou,su,cu,Ll.extend({type:h(`resource_link`)}),uu]),fu=S({role:Fl,content:du}),pu=Bc.extend({description:u().optional(),messages:y(fu)}),mu=zc.extend({method:h(`notifications/prompts/list_changed`),params:Rc.optional()}),hu=S({title:u().optional(),readOnlyHint:p().optional(),destructiveHint:p().optional(),idempotentHint:p().optional(),openWorldHint:p().optional()}),gu=S({taskSupport:ge([`required`,`optional`,`forbidden`]).optional()}),_u=S({...tl.shape,...el.shape,description:u().optional(),inputSchema:S({type:h(`object`),properties:g(u(),Oc).optional(),required:y(u()).optional()}).catchall(pe()),outputSchema:S({type:h(`object`),properties:g(u(),Oc).optional(),required:y(u()).optional()}).catchall(pe()).optional(),annotations:hu.optional(),execution:gu.optional(),_meta:g(u(),pe()).optional()}),vu=_l.extend({method:h(`tools/list`)}),yu=vl.extend({tools:y(_u)}),bu=Bc.extend({content:y(du).default([]),structuredContent:g(u(),pe()).optional(),isError:p().optional()});bu.or(Bc.extend({toolResult:pe()}));const xu=Fc.extend({name:u(),arguments:g(u(),pe()).optional()}),Su=Lc.extend({method:h(`tools/call`),params:xu}),Cu=zc.extend({method:h(`notifications/tools/list_changed`),params:Rc.optional()});S({autoRefresh:p().default(!0),debounceMs:m().int().nonnegative().default(300)});const wu=ge([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Tu=Pc.extend({level:wu}),Eu=Lc.extend({method:h(`logging/setLevel`),params:Tu}),Du=Rc.extend({level:wu,logger:u().optional(),data:pe()}),Ou=zc.extend({method:h(`notifications/message`),params:Du}),ku=S({hints:y(S({name:u().optional()})).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),Au=S({mode:ge([`auto`,`required`,`none`]).optional()}),ju=S({type:h(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:y(du).default([]),structuredContent:S({}).loose().optional(),isError:p().optional(),_meta:g(u(),pe()).optional()}),Mu=b(`type`,[ou,su,cu]),Nu=b(`type`,[ou,su,cu,lu,ju]),Pu=S({role:Fl,content:C([Nu,y(Nu)]),_meta:g(u(),pe()).optional()}),Fu=Fc.extend({messages:y(Pu),modelPreferences:ku.optional(),systemPrompt:u().optional(),includeContext:ge([`none`,`thisServer`,`allServers`]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(u()).optional(),metadata:Oc.optional(),tools:y(_u).optional(),toolChoice:Au.optional()}),Iu=Lc.extend({method:h(`sampling/createMessage`),params:Fu}),Lu=Bc.extend({model:u(),stopReason:x(ge([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:Fl,content:Mu}),Ru=Bc.extend({model:u(),stopReason:x(ge([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:Fl,content:C([Nu,y(Nu)])}),zu=S({type:h(`boolean`),title:u().optional(),description:u().optional(),default:p().optional()}),Bu=S({type:h(`string`),title:u().optional(),description:u().optional(),minLength:m().optional(),maxLength:m().optional(),format:ge([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),Vu=S({type:ge([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),Hu=S({type:h(`string`),title:u().optional(),description:u().optional(),enum:y(u()),default:u().optional()}),Uu=S({type:h(`string`),title:u().optional(),description:u().optional(),oneOf:y(S({const:u(),title:u()})),default:u().optional()}),Wu=C([C([S({type:h(`string`),title:u().optional(),description:u().optional(),enum:y(u()),enumNames:y(u()).optional(),default:u().optional()}),C([Hu,Uu]),C([S({type:h(`array`),title:u().optional(),description:u().optional(),minItems:m().optional(),maxItems:m().optional(),items:S({type:h(`string`),enum:y(u())}),default:y(u()).optional()}),S({type:h(`array`),title:u().optional(),description:u().optional(),minItems:m().optional(),maxItems:m().optional(),items:S({anyOf:y(S({const:u(),title:u()}))}),default:y(u()).optional()})])]),zu,Bu,Vu]),Gu=C([Fc.extend({mode:h(`form`).optional(),message:u(),requestedSchema:S({type:h(`object`),properties:g(u(),Wu),required:y(u()).optional()})}),Fc.extend({mode:h(`url`),message:u(),elicitationId:u(),url:u().url()})]),Ku=Lc.extend({method:h(`elicitation/create`),params:Gu}),qu=Rc.extend({elicitationId:u()}),Ju=zc.extend({method:h(`notifications/elicitation/complete`),params:qu}),Yu=Bc.extend({action:ge([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,g(u(),C([u(),m(),p(),y(u())])).optional())}),Xu=S({type:h(`ref/resource`),uri:u()}),Zu=S({type:h(`ref/prompt`),name:u()}),Qu=Pc.extend({ref:C([Zu,Xu]),argument:S({name:u(),value:u()}),context:S({arguments:g(u(),u()).optional()}).optional()}),$u=Lc.extend({method:h(`completion/complete`),params:Qu});function ed(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function td(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const nd=Bc.extend({completion:ue({values:y(u()).max(100),total:x(m().int()),hasMore:x(p())})}),rd=S({uri:u().startsWith(`file://`),name:u().optional(),_meta:g(u(),pe()).optional()}),id=Lc.extend({method:h(`roots/list`),params:Pc.optional()}),ad=Bc.extend({roots:y(rd)}),od=zc.extend({method:h(`notifications/roots/list_changed`),params:Rc.optional()});C([fl,cl,$u,Eu,au,nu,zl,Vl,Gl,Yl,Zl,Su,vu,wl,El,Dl,kl]),C([$c,hl,dl,od,Cl]),C([Zc,Lu,Ru,Yu,ad,Tl,Ol,xl]),C([fl,Iu,Ku,id,wl,El,Dl,kl]),C([$c,hl,Ou,$l,ql,Cu,mu,Cl,Ju]),C([Zc,ul,nd,pu,ru,Bl,Hl,Kl,bu,yu,Tl,Ol,xl]);var V=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===B.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new sd(e.elicitations,n)}return new e(t,n,r)}},sd=class extends V{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function cd(e){return e===`completed`||e===`failed`||e===`cancelled`}const ld=Symbol(`Let zodToJsonSchema decide on which parser to use`),ud={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`},dd=e=>typeof e==`string`?{...ud,name:e}:{...ud,...e},fd=e=>{let t=dd(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 pd(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,pd(e,t,r,i)}const md=(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 hd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?md(t,e.currentPath):t.join(`/`)}}function gd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=U(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function _d(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?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function vd(){return{type:`boolean`}}function yd(e,t){return U(e.type._def,t)}const bd=(e,t)=>U(e.innerType._def,t);function xd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>xd(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 Sd(e,t)}}const Sd=(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`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Cd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function wd(e,t){return t.effectStrategy===`input`?U(e.schema._def,t):hd(t)}function Td(e){return{type:`string`,enum:Array.from(e.values)}}const Ed=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Dd(e,t){let n=[U(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),U(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(Ed(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 Od(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 kd;const Ad={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:()=>(kd===void 0&&(kd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),kd),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 jd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(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`:Fd(n,`email`,r.message,t);break;case`format:idn-email`:Fd(n,`idn-email`,r.message,t);break;case`pattern:zod`:Id(n,Ad.email,r.message,t);break}break;case`url`:Fd(n,`uri`,r.message,t);break;case`uuid`:Fd(n,`uuid`,r.message,t);break;case`regex`:Id(n,r.regex,r.message,t);break;case`cuid`:Id(n,Ad.cuid,r.message,t);break;case`cuid2`:Id(n,Ad.cuid2,r.message,t);break;case`startsWith`:Id(n,RegExp(`^${Md(r.value,t)}`),r.message,t);break;case`endsWith`:Id(n,RegExp(`${Md(r.value,t)}$`),r.message,t);break;case`datetime`:Fd(n,`date-time`,r.message,t);break;case`date`:Fd(n,`date`,r.message,t);break;case`time`:Fd(n,`time`,r.message,t);break;case`duration`:Fd(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Id(n,RegExp(Md(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Fd(n,`ipv4`,r.message,t),r.version!==`v4`&&Fd(n,`ipv6`,r.message,t);break;case`base64url`:Id(n,Ad.base64url,r.message,t);break;case`jwt`:Id(n,Ad.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Id(n,Ad.ipv4Cidr,r.message,t),r.version!==`v4`&&Id(n,Ad.ipv6Cidr,r.message,t);break;case`emoji`:Id(n,Ad.emoji(),r.message,t);break;case`ulid`:Id(n,Ad.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Fd(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Id(n,Ad.base64,r.message,t);break}break;case`nanoid`:Id(n,Ad.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Md(e,t){return t.patternStrategy===`escape`?Pd(e):e}const Nd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Pd(e){let t=``;for(let n=0;n<e.length;n++)Nd.has(e[n])||(t+=`\\`),t+=e[n];return t}function Fd(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}}})):H(e,`format`,t,n,r)}function Id(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:Ld(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,Ld(t,r),n,r)}function Ld(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
@@ -918,7 +918,7 @@ ${e.terminator}`}function dx(e){return`(${rx(e.body)})${nx(e.redirections)}`}fun
918
918
  `)}var yx=new TextDecoder(`utf-8`,{fatal:!0});function bx(e){if(!e)return e;let t=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>255)return e;r>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);try{return yx.decode(n)}catch{return e}}var xx=[`EACCES`,`escaping sandbox`,`EFBIG`],Sx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=k.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$t(this.root,`ReadWriteFs`),this.canonicalRoot=A.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?Zt(e,this.canonicalRoot):Qt(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=k.dirname(e),r=this.resolveAndValidate(n,t);return k.join(r,k.basename(e))}toRealPath(e){let t=D(e),n=k.join(this.root,t);return k.resolve(n)}async readFile(e,t){return rn(await this.readFileBuffer(e),tn(t))}async readFileBuffer(e){O(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(n,t);try{if(this.maxFileReadSize>0){let t=await r.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await r.readFile();return new Uint8Array(t)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,n){O(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=nn(t,tn(n)),o=k.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_TRUNC|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,n){O(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=nn(t,tn(n)),o=k.dirname(i);try{await A.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:A.constants.O_NOFOLLOW,n=A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_APPEND|t,s=await A.promises.open(i,n,438);try{await s.writeFile(a)}finally{await s.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let n=this.resolveAndValidate(t,e);return await A.promises.access(n),!0}catch{return!1}}async stat(e){O(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await A.promises.lstat(n);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){O(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await A.promises.lstat(n);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){O(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.mkdir(r,{recursive:t?.recursive})}catch(t){let n=t;if(n.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){O(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await A.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await A.promises.readdir(n,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){O(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await A.promises.rm(r,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(n){let r=n;if(r.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(r.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(n,e,`rm`)}}async cp(e,t,n){O(e,`cp`),O(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await A.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(A.lstatSync(e).isSymbolicLink()){let t=await A.promises.realpath(e).catch(()=>null);return t===null?!1:Kt(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(n.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){O(e,`mv`),O(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await A.promises.lstat(i)).isSymbolicLink()){let n=await A.promises.readlink(i),r=k.resolve(k.dirname(a),n);if(!Kt(await A.promises.realpath(r).catch(()=>r),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(n.message?.includes(`EACCES`)||n.message?.includes(`escaping sandbox`))throw t}let o=k.dirname(a);try{await A.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await A.promises.rename(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(r.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(n,e,`mv`)}try{if(A.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await A.promises.rename(a,i),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return Jt(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){Xt(e,t,n,xx)}findEscapingSymlinks(e){let t=[];try{let n=A.readdirSync(e);for(let r of n){let n=k.join(e,r);try{let r=A.lstatSync(n);if(r.isSymbolicLink()){let r=A.readlinkSync(n),i=k.resolve(e,r),a;try{a=A.realpathSync(i)}catch{a=i}Kt(a,this.canonicalRoot)||t.push(n)}else r.isDirectory()&&t.push(...this.findEscapingSymlinks(n))}catch{}}}catch{}return t}scanDir(e,t){let n=this.toRealPath(e),r;try{r=this.resolveAndValidate(n,e)}catch{return}try{let n=A.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=k.join(r,i);A.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){O(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,n=await A.promises.open(r,e);try{await n.chmod(t)}finally{await n.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);O(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=D(t),a=D(k.dirname(i)),o=e.startsWith(`/`)?D(e):D(a===`/`?`/${e}`:`${a}/${e}`),s=k.join(this.canonicalRoot,o),c=k.dirname(r),l=e.startsWith(`/`)?s:k.relative(c,s)||`.`;try{await A.promises.symlink(l,r)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){O(e,`link`),O(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await A.promises.link(i,a)}catch(n){let r=n;if(r.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(r.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(r.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(n,e,`link`)}}async readlink(e){O(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await A.promises.readlink(n),r=D(e),i=k.dirname(r),a=k.isAbsolute(t)?t:k.resolve(k.dirname(n),t),o=await A.promises.realpath(a).catch(()=>a);if(Kt(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:k.relative(i,e)}return k.basename(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){O(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let n;try{n=await A.promises.realpath(t)}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(n.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(Kt(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){O(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?A.constants.O_RDONLY:A.constants.O_RDONLY|A.constants.O_NOFOLLOW,r=await A.promises.open(i,e);try{await r.utimes(t,n)}finally{await r.close()}}catch(t){let n=t;if(n.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(n.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}};function Cx(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const wx=16*1024*1024;var Tx=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,n){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=n}};function Ex(e){if(!wn(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new _x({cwd:`/`,fs:new Sx({root:Dn(e),allowSymlinks:!1})})}async function Dx(e,t){let n=await e.exec(t);if(n.stdout.length>wx)throw new Tx(wx,n.stdout.length,{stdout:n.stdout.slice(0,wx),stderr:n.stderr,exitCode:n.exitCode});return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}function Ox(e){return e.startsWith(`**/`)?e.slice(3):e}async function kx(e,t,n={}){let r=Ex(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Cx(Ox(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Cx(Ox(e))}`),i.push(`--exclude-dir=${Cx(Ox(e))}`);let a=n.paths?.length?n.paths.map(Cx):[`.`],o=`grep ${i.join(` `)} ${Cx(e)} ${a.join(` `)}`,s;try{s=await Dx(r,o)}catch(e){if(e instanceof Tx)s=e.partial;else throw e}if(s.exitCode===1&&!s.stdout)return[];if(s.exitCode!==0&&s.exitCode!==1&&!s.stdout)throw Error(`grep exited ${s.exitCode}: ${s.stderr}`);let c=[],l=n.maxResults??1/0;for(let e of s.stdout.split(`
919
919
  `)){if(!e)continue;if(c.length>=l)break;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.indexOf(`:`,t+1);if(n===-1)continue;let r=e.slice(0,t),i=e.slice(t+1,n),a=e.slice(n+1),o=Number.parseInt(i,10);Number.isFinite(o)&&c.push({path:r,line:o,text:a})}return c}const Ax=new Set([`.git`,T,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function jx(e){let t=Dn(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await $n(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&Ax.has(s.name))continue;let o=Dn(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await er(o);n.set(En(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function Mx(e,t){let n=[];for(let[r,i]of t){let t=e.get(r);(t===void 0||t!==i)&&n.push(r)}for(let[r]of e)t.has(r)||n.push(r);return{changed:n}}var Nx=n(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),Px=n(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`"((\\\\"|[^"])*?)"`,o=`'((\\\\'|[^'])*?)'`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r.push(i),t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,m=h(e,new RegExp([`(`+n+`)`,`(`+p+`|`+a+`|`+o+`)+`].join(`|`),`g`));if(m.length===0)return[];t||={};var _=!1;return m.map(function(n){var i=n[0];if(!i||_)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,p=!1,m;function h(){m+=1;var e,n,r=i.charAt(m);if(r===`{`){if(m+=1,i.charAt(m)===`}`)throw Error(`Bad substitution: `+i.slice(m-2,m+1));if(e=i.indexOf(`}`,m),e<0)throw Error(`Bad substitution: `+i.slice(m));n=i.slice(m,e),m=e}else if(/[*@#?$!_-]/.test(r))n=r,m+=1;else{var a=i.slice(m);e=a.match(/[^\w\d_]/),e?(n=a.slice(0,e.index),m+=e.index-1):(n=a,m=i.length)}return g(t,``,n)}for(m=0;m<i.length;m++){var v=i.charAt(m);if(p||=!a&&(v===`*`||v===`?`),o)d+=v,o=!1;else if(a)v===a?a=!1:a==c?d+=v:v===f?(m+=1,v=i.charAt(m),v===l||v===f||v===u?d+=v:d+=f+v):v===u?d+=h():d+=v;else if(v===l||v===c)a=v;else if(r.test(v))return{op:i};else if(s.test(v)){_=!0;var y={comment:e.slice(n.index+m+1)};return d.length?[d,y]:[y]}else v===f?o=!0:v===u?d+=h():d+=v}return p?{op:`glob`,pattern:d}:d}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?e.concat(n[0]):e.concat(n.filter(Boolean).map(function(e){return m.test(e)?JSON.parse(e.split(d)[1]):e}))},[]):r}})),Fx=t(n((e=>{e.quote=Nx(),e.parse=Px()}))(),1);const Ix=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,T,`.claude`];function Lx(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const Rx=[{command:`grep`,applies:e=>e.slice(1).some(Lx),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let n of e)t.push(`-not`,`-path`,`*/${n}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function zx(e){return e.map(e=>{let t=Rx.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(Ix),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function Bx(e){return e.map(e=>e.args.map(Cx).join(` `)).join(` | `)}const Vx=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),Hx=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),Ux=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),Wx=new Set([`-o`,`--output-file`,`--output`]),Gx=[`-o=`,`--output-file=`,`--output=`],Kx=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),qx=/[`]|\$\(|\$\{|\$'/;function Jx(e){return typeof e==`object`&&!!e&&`op`in e}function Yx(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return Hx.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:Ux.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function Xx(e){let t=[];for(let n of e){if(typeof n==`string`){if(qx.test(n))return{error:{category:`shell_construct_blocked`,message:`Argument '${n}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(n);continue}if(!Jx(n))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(n.op===`glob`&&typeof n.pattern==`string`){t.push(n.pattern);continue}return typeof n.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:Yx(n)}}return{args:t}}function Zx(e){if(!Vx.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut.`};for(let t of e.args.slice(1)){if(Wx.has(t)||Gx.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&Kx.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function Qx(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=Fx.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let r=[],i=[];for(let e of n){if(Jx(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=Xx(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let n={command:t.args[0],args:t.args},r=Zx(n);if(r)return{error:r};a.push(n)}return{stages:a}}const $x=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function eS(e,t){let n=e.match($x);if(!n)return null;try{let e=(0,ar.parse)(n[1]);if(Be(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}var tS=t(Oe(),1);const nS=new WeakMap;function rS(e){let t=nS.get(e);if(t)return t;let n=e.map(e=>(0,tS.default)(e.match,{dot:!0}));return nS.set(e,n),n}function iS(e,t){if(e.length===0)return{};let n=rS(e),r={},i=[],a=!1;for(let o=0;o<e.length;o++){if(!n[o](t))continue;a=!0;let s=e[o].frontmatter;if(s.title!==void 0&&(r.title=s.title),s.description!==void 0&&(r.description=s.description),s.tags!==void 0)for(let e of s.tags)i.includes(e)||i.push(e)}return a?(i.length>0&&(r.tags=i),r):{}}function aS(e){try{return In(Dn(e,`.git`)).isDirectory()}catch{return!1}}function oS(e){return Se({baseDir:Dn(e),timeout:{block:5e3}})}async function sS(e,t,n=5){if(!aS(e))return{commits:[],source:`git-absent`};let r=oS(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
920
920
  `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const cS=5e3;async function lS(e){try{let t=(await Se({baseDir:e,timeout:{block:cS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function uS(e,t){return Se({baseDir:t,timeout:{block:cS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function dS(e,t){let n=Ae(t);return e.startsWith(n)?e.slice(n.length):e}async function fS(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=dS(t,r),s=Me(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:je(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function pS(e,t,n=5){let r=Ce(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await lS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=uS(r,Dn(e)),o=``;try{o=await a.raw(`for-each-ref`,Ae(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
921
- `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>fS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const mS=1e3,hS=new Set([`.git`,T,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),gS=/\.(md|mdx)$/i,_S=S({title:u().optional(),description:u().optional(),tags:y(u()).default([])});function vS(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function yS(e){try{let t=eS(await Qn(e,`utf-8`),_S);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function bS(e,t){if(!e)return null;let n=await Bm(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function xS(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await Bm(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function SS(e,t){if(!e)return null;let n=await Bm(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function CS(e,t,n){let r=t??[],i=r.length===0?{}:iS(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function wS(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=Dn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=yS(i);if(!o){let e=CS(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,bS(t.serverUrl,vS(r)).catch(()=>null),SS(t.serverUrl,vS(r)).catch(()=>null),pS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),sS(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=CS(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function TS(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=mS){n.truncated=!0;break}let a;try{a=await $n(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=mS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(hS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&gS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await er(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:En(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function ES(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await TS(Dn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await yS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??Sn(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=iS(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const DS=50*1024,OS=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,kS=["**STOP — native tools on in-scope markdown.** Do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code and non-markdown paths only.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
921
+ `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>fS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const mS=1e3,hS=new Set([`.git`,T,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),gS=/\.(md|mdx)$/i,_S=S({title:u().optional(),description:u().optional(),tags:y(u()).default([])});function vS(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function yS(e){try{let t=eS(await Qn(e,`utf-8`),_S);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function bS(e,t){if(!e)return null;let n=await Bm(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function xS(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await Bm(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function SS(e,t){if(!e)return null;let n=await Bm(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function CS(e,t,n){let r=t??[],i=r.length===0?{}:iS(r,n),a=e?.title??i.title,o=e?.description??i.description,s=e?.tags??[],c=i.tags??[],l;if(c.length===0)l=s;else{let e=new Set;l=[];for(let t of c)e.has(t)||(e.add(t),l.push(t));for(let t of s)e.has(t)||(e.add(t),l.push(t))}return{title:a,description:o,tags:l}}async function wS(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=Dn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=yS(i);if(!o){let e=CS(await s,t.folderRules,r);return{path:r,title:e.title,description:e.description,tags:e.tags,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[c,l,u,d,f]=await Promise.all([s,bS(t.serverUrl,vS(r)).catch(()=>null),SS(t.serverUrl,vS(r)).catch(()=>null),pS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),sS(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=CS(c,t.folderRules,r);return{path:r,title:p.title,description:p.description,tags:p.tags,backlinkCount:l?.length??null,backlinks:l,forwardLinkCount:u?.length??null,forwardLinks:u,history:d.commits,historySource:d.source,projectHistory:f.commits,projectHistorySource:f.source}}async function TS(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=mS){n.truncated=!0;break}let a;try{a=await $n(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=mS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(hS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&gS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await er(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:En(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function ES(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await TS(Dn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await yS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??Sn(r.mostRecent.relPath),updatedAt:new Date(r.mostRecent.mtimeMs).toISOString()}}let a={path:n,type:`directory`,directMdCount:r.directMdCount,recursiveMdCount:r.recursiveMdCount,childDirCount:r.childDirCount,mostRecentMd:i,truncated:r.truncated},o=t.folderRules??[];if(o.length>0){let e=iS(o,n);e.title!==void 0&&(a.title=e.title),e.description!==void 0&&(a.description=e.description),e.tags!==void 0&&e.tags.length>0&&(a.tags=e.tags)}return a}const DS=50*1024,OS=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,kS=["**STOP — native tools on in-scope markdown (when project has `.open-knowledge/`).** When the active project contains `.open-knowledge/`, do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code, non-markdown paths, and projects without `.open-knowledge/`.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
922
922
  `);function AS(e){let t=e.split(`
923
923
  `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=DS)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>DS)break;a++}let o=t.slice(0,a).join(`
924
924
  `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function jS(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||OS.test(e)&&t.push(e);return t}function MS(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function NS(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=MS(n.args),i=t.split(`
@@ -1013,7 +1013,7 @@ If the source is directly relevant to an existing article or research doc, updat
1013
1013
  - **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source
1014
1014
  `}const rC=[`Fetch an external source (URL or local file) and save raw content as reference material in the project content directory.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
1015
1015
  `);function iC(e,t){e.tool(`ingest`,rC,{source:u().describe(`URL, file path, or identifier of the source to ingest`),cwd:u().optional().describe(Om)},async e=>{let n=await Lm(t.resolveCwd,t.config,e.cwd);return n.ok?q(nC(e.source,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const aC=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,`Returns document names, optionally filtered by directory.`,``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory"].join(`
1016
- `);function oC(e,t){e.tool(`list_documents`,aC,{dir:u().optional().describe(`Optional directory to filter documents`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=await Bm(i,`/api/documents${e.dir?`?dir=${encodeURIComponent(e.dir)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await Xm(t,r),d=(c.documents??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,documents:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const sC=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"Prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
1016
+ `);function oC(e,t){e.tool(`list_documents`,aC,{dir:u().optional().describe(`Optional directory to filter documents`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=await Bm(i,`/api/documents${e.dir?`?dir=${encodeURIComponent(e.dir)}`:``}`);if(!a.ok)return K(`Error: ${a.error}`,!0);let{ok:o,...s}=a,c=s,{resolve:l,ui:u}=await Xm(t,r),d=(c.documents??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,n=t?l(t):null;return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}}),f={...c,documents:d,ui:u,cwd:r};return q(JSON.stringify(f,null,2),f)})}const sC=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4. In projects without `.open-knowledge/`, use native `Read` as usual.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
1017
1017
  `);function cC(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let n of e){let e=n.writerClassification===`agent`?`agent: ${n.writerName}`:n.writerClassification===`principal`?`human: ${n.writerName}`:`${n.writerClassification}: ${n.writerName}`,r=n.hash.slice(0,7);t.push(`- ${r} ${n.date} [${e}] ${n.message}`)}return t.join(`
1018
1018
  `)}function lC(e){if(!e||e.length===0)return``;let t=[``,`### Commit history (project git)`,``];for(let n of e){let e=n.hash.slice(0,7);t.push(`- ${e} ${n.date} ${n.authorName} — ${n.subject}`)}return t.join(`
1019
1019
  `)}function uC(e){if(!e||e.length===0)return``;let t=[``,`### Backlinks (${e.length})`,``];for(let n of e){let e=n.title?` — "${n.title}"`:``,r=n.snippet?` — "${n.snippet}"`:``;t.push(`- ${n.source}${e}${r}`)}return t.join(`
@@ -1375,14 +1375,14 @@ In headless mode, write the recap into the research article's "Further reading"
1375
1375
  `);function CC(e,t){e.tool(`research`,SC,{topic:u().describe(`The topic, question, or anchor URL to research`),cwd:u().optional().describe(Om)},async e=>{let n=await Lm(t.resolveCwd,t.config,e.cwd);return n.ok?q(xC(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}const wC=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1376
1376
  `);function TC(e,t){e.tool(`rollback_to_version`,wC,{docName:u().describe(`Document name to restore`),commitSha:u().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:km.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=a.docName,s=await Bm(i,`/api/history/${e.commitSha}?docName=${encodeURIComponent(o)}`);if(!s.ok)return K(`Error: ${s.error??`Version not found`}`,!0);let c=t.identityRef?.current,l=await Vm(i,`/api/rollback`,{docName:o,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...c?{agentId:c.connectionId,agentName:c.displayName,clientName:c.clientInfo?.name,colorSeed:c.colorSeed}:{}});if(!l.ok)return K(`Error: ${l.error}`,!0);let u=l.summary&&typeof l.summary==`object`?l.summary:void 0,d=typeof u?.hint==`string`?u.hint:void 0,f=[`Restored "${o}" to version ${e.commitSha.slice(0,8)} (${s.author}, ${s.timestamp}). The change has been applied to all connected editors.`];d&&f.push(d);let p=await Jm(o,{config:t.config,resolveCwd:t.resolveCwd},r);return q(f.join(`
1377
1377
  `),{previewUrl:p?.url??null,...p?{previewUrlSource:p.source}:{},...u?{summary:u}:{}})})}const EC=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
1378
- `);function DC(e,t,n,r,i){e.tool(`save_version`,EC,{cwd:u().optional().describe(Om)},async(e={})=>{let a=await Rm(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Am,!0);let{url:o}=a,s=i?.current,c=await Vm(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const OC=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"Prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
1378
+ `);function DC(e,t,n,r,i){e.tool(`save_version`,EC,{cwd:u().optional().describe(Om)},async(e={})=>{let a=await Rm(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Am,!0);let{url:o}=a,s=i?.current,c=await Vm(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const OC=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.open-knowledge/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
1379
1379
  `);function kC(e){let t=new Map;for(let n of e){let e=t.get(n.path);e?e.push(n):t.set(n.path,[n])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function AC(e,t){let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:i,url:a}=n,o=i.mcp.tools.search.maxResults,s=i.content.include,c=i.content.exclude,l=await kx(e.query,r,{caseInsensitive:!(e.case_sensitive??!1),include:s,exclude:[...c,`node_modules`,`.git`,`.claude`,`.changeset`,T],maxResults:o+1}),u=l.length>o,d=u?l.slice(0,o):l,{resolve:f,ui:p}=await Xm({config:i,resolveCwd:async()=>r},r);if(d.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:p,cwd:r}};let m=kC(d),h=new Map,g=i.folders;await Promise.all(m.map(async e=>{try{let t=await wS(e.path,{projectDir:r,serverUrl:a,folderRules:g});h.set(e.path,t)}catch{}}));let _=[];_.push(`## Search results for "${e.query}" (${d.length} match${d.length===1?``:`es`} in ${m.length} file${m.length===1?``:`s`})`,``);let v=[];for(let e of m){let t=h.get(e.path),n=t?.title??e.path;_.push(`### ${n} (${e.path})`),t?.tags?.length&&_.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&_.push(`${t.description}`);for(let t of e.matches)_.push(`- Line ${t.line}: ${t.text}`);_.push(``);let r=Zm(e.path),i=f(r);v.push({path:e.path,docName:r,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:i?.url??null,...i?{previewUrlSource:i.source}:{}})}return u&&_.push(`_${d.length} of ${l.length}+ matches shown. Raise \`mcp.tools.search.maxResults\` in config.yml to see more._`),{text:_.join(`
1380
1380
  `),structured:{query:e.query,matchCount:d.length,fileCount:m.length,truncated:u,results:v,ui:p,cwd:r}}}function jC(e,t){e.tool(`search`,OC,{query:u().describe(`Literal text to search for`),case_sensitive:p().optional().describe(`Case-sensitive search (default false)`),cwd:u().optional().describe("Absolute host path to search in. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let{text:n,structured:r}=await AC(e,t);return r?q(n,r):K(n)}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const MC=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
1381
1381
  `);function NC(e,t){e.tool(`suggest_links`,MC,{docName:u().describe(`Target page docName`),cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Am,!0);let a=zm(e.docName);if(!a.ok)return K(a.error,!0);let o=await Bm(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await Jm(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const PC=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1382
1382
  `);function FC(e,t){e.tool(`write_document`,PC,{docName:u().describe(`Document name to write to`),markdown:u().describe(`Markdown content to write`),position:ge([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:km,cwd:u().optional().describe(Om)},async e=>{let n=await Rm(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Am,!0);let o=zm(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await Vm(a,`/api/agent-write-md`,{docName:o.docName,markdown:e.markdown,position:e.position,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=_e(ve(i,r)),u=Qm(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=Array.isArray(c.hints)?c.hints:void 0,h=c.summary&&typeof c.summary==`object`?c.summary:void 0,g=typeof h?.hint==`string`?h.hint:void 0,_=[`Written successfully (${e.position}).`];if(u&&_.push(`Preview: ${u.url}`),f&&_.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),g&&_.push(g),m)for(let e of m)e.message&&_.push(e.message);let v=_.join(`
1383
1383
  `);if(!u&&!f&&!p&&!m&&!h)return K(v);let y={};return u&&(y.previewUrl=u.url,y.previewUrlSource=u.source),f&&(y.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(y.hints=m),h&&(y.summary=h),q(v,y)})}function IC(e,t){let n=t.logger,r=Dm(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(pm()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(pm()??n)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...r?{explicit:r}:{}}),t}};US(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),iC(r,{config:t.config,resolveCwd:i(`ingest`)}),CC(r,{config:t.config,resolveCwd:i(`research`)}),Wm(r,{config:t.config,resolveCwd:i(`consolidate`)}),hC(r,{resolveCwd:i(`read_document`),config:t.config,serverUrl:t.serverUrl}),jC(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl}),NC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`suggest_links`)}),FC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write_document`),identityRef:t.identityRef}),eh(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit_document`),identityRef:t.identityRef}),bC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_document`),identityRef:t.identityRef}),ZS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_history`)}),DC(r,t.config,t.serverUrl,i(`save_version`),t.identityRef),TC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rollback_to_version`),identityRef:t.identityRef}),oC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`list_documents`)}),GS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_backlinks`)}),YS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_forward_links`)}),tC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_orphans`)}),$S(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_hubs`)}),qS(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_dead_links`)})}function LC(e){return e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`?e.code:e instanceof Error&&e.name?e.name:typeof e}var RC=class extends Error{};function zC(e){let t=Ve(e.startupCwd),n=null,r=null,i=async()=>n===null?(r||=(async()=>{let t=await e.listRoots(),r=await Promise.all(t.roots.map(async e=>e.uri.startsWith(`file://`)?await Ve(Jn(e.uri)):null)),i=[...new Set(r.filter(e=>e!==null))];return n=i,e.logger?.info(`roots resolved`,{roots:i,count:i.length}),i})().finally(()=>{r=null}),await r):n;return{async resolveCwd(n){if(n){let t=await Ve(n);return e.logger?.debug(`cwd resolved`,{cwd:t,routing:`explicit`}),t}if(e.bypassProjectSelection){let n=await t;return e.logger?.debug(`cwd resolved`,{cwd:n,routing:`bypass`}),n}let r;try{r=await i()}catch(t){throw e.logger?.warn(`roots/list unavailable`,{error:t instanceof Error?t.message:String(t),errorType:LC(t)}),new RC(`Client roots unavailable; pass cwd explicitly.`)}if(r.length===0)throw new RC(`No client roots available; pass cwd explicitly.`);if(r.length>1)throw new RC(`Multiple roots available; pass cwd explicitly.`);return e.logger?.debug(`cwd resolved`,{cwd:r[0],routing:`single-root`}),r[0]},invalidateRoots(){n=null,r=null,e.logger?.info(`roots cache invalidated`)}}}function BC(e){let t=Ve(e.startupCwd),n;return{async resolveCwdForTools(t){let r=await e.resolveCwd(t);return n=r,r},async getKeepaliveCwd(){return e.bypassProjectSelection?await t:n}}}let VC;function HC(e,t){let{dir:n,include:r,exclude:i}=e.content,a=i.length>0?i.map(e=>`\`${e}\``).join(`, `):`(none)`;return`# Open Knowledge (OK) — collaborative markdown via MCP
1384
1384
 
1385
- **STOP native tools on in-scope \`.md\` / \`.mdx\`.** Do NOT use host-native \`Read\`, \`Grep\`, \`Glob\`, \`Edit\`, \`Write\` on markdown inside the content dir. Reads: \`exec\` / \`read_document\` / \`search\`. Writes: \`write_document\` / \`edit_document\` ONLY.
1385
+ **STOP** *(when \`.open-knowledge/\` exists)* do NOT use native \`Read\`, \`Grep\`, \`Glob\`, \`Edit\`, \`Write\` on in-scope \`.md\` / \`.mdx\`. Reads: \`exec\` / \`read_document\` / \`search\`. Writes: \`write_document\` / \`edit_document\` ONLY.
1386
1386
 
1387
1387
  **Preview:** open the browser at session start if not already open. On \`attach-preview-once\` in a write response, open \`previewUrl\` one-shot.
1388
1388
 
@@ -1400,9 +1400,9 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
1400
1400
 
1401
1401
  Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
1402
1402
 
1403
- **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.
1404
- `}async function UC(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 WC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(VC=dm(),VC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await UC(n,VC);VC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else VC.info(`server discovery is lazy per effective cwd`);let o=new Yp({name:l,version:c},{instructions:HC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=zC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:VC}),u=BC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(od,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=Yn(),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},VC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},IC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:VC});let g=new cm;await o.connect(g),VC.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:VC.child(`keepalive`)}),y=e=>{VC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}const GC=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],KC=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function qC(e){if(!e||e.length===0)return`unknown`;for(let t of GC)if(e.includes(t))return`npx-cache`;return KC.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function JC(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function YC(e){return e?/\bENOENT\b/i.test(e):!1}function XC(e){switch(qC(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function ZC(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return YC(e)&&(r+=`\n\n${XC(n)}`),r}function QC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function $C(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 n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=qC(o),c=JC(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}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 ew(e){let t=e.readLock??(()=>ye(e.lockDir)),n=e.isAlive??be,r=e.sleep??(e=>Xn(e)),i=e.spawn??bn,a=e.readErrorLog??(e=>An(e)?Nn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Mn(e,`w`)),s=e.closeFd??kn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=$C({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);An(e.lockDir)||jn(e.lockDir,{recursive:!0});let f=Tn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=vn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}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(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function tw(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??ew,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ve(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=ve(i,o),s=_e(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,launchPath:e.launchPath});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 nw(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=Ue({startupCwd:r,startupConfig:n}),a=QC(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=tw({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 WC({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 rw(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-9ZcqMu7e.mjs`),r=e(),i=process.cwd(),a=ve(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 iw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function aw(e,t,n=process.cwd()){let r=e.op??`sync`,i=ye(_e(ve(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}`)}iw(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=Se({baseDir:n});if(r===`sync`||r===`pull`){iw(e.json,{type:`step`,step:`pull`});let t=await a.pull();iw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(iw(e.json,{type:`step`,step:`push`}),await a.push(),iw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1403
+ **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.open-knowledge/\`, when no OK MCP is registered, or right after a failed OK MCP call (then prefix with \`Open Knowledge MCP unavailable:\`). Non-markdown: native tools always.
1404
+ `}async function UC(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 WC(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(VC=dm(),VC.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await UC(n,VC);VC.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else VC.info(`server discovery is lazy per effective cwd`);let o=new Yp({name:l,version:c},{instructions:HC(i,{dynamicConfig:typeof r==`function`&&!a})}),s=zC({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:VC}),u=BC({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),d=u.resolveCwdForTools;o.server.setNotificationHandler(od,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=Yn(),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},VC?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},IC(o,{serverUrl:f,resolveCwd:d,config:r,identityRef:h,logger:VC});let g=new cm;await o.connect(g),VC.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:VC.child(`keepalive`)}),y=e=>{VC?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}const GC=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],KC=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function qC(e){if(!e||e.length===0)return`unknown`;for(let t of GC)if(e.includes(t))return`npx-cache`;return KC.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function JC(e,t){switch(e){case`npx-cache`:return"This MCP was launched via a package-manager cache (npx / bunx / pnpm dlx) and just resolved a different package version than the running server. Stop `ok start` so the next launch matches, or run `ok init --pin` for a stable launch path.";case`stable-shim`:return"The CLI shim was likely upgraded while a project server is still running (a desktop auto-update or `npm i -g` / `brew upgrade` will do this). Close and reopen the project window, or stop `ok start`, so the next launch matches.";case`absolute-pin`:return`This MCP is launched from a pinned path${t?` (${t})`:``} that no longer matches the running server. Re-run \`ok init --pin\` from your current install to refresh, or stop \`ok start\` so the next launch matches.`;default:return"Stop `ok start` and retry, or align CLI versions across your installs."}}function YC(e){return e?/\bENOENT\b/i.test(e):!1}function XC(e){switch(qC(e)){case`absolute-pin`:return"This failure usually means the CLI entry script no longer exists at the pinned path (common after changing how you installed Open Knowledge or removing an old global package). Re-run `ok init --pin` from your current install and update your editor MCP config, or use an unpinned launcher such as `npx @inkeep/open-knowledge mcp`.";case`stable-shim`:return"The expected `ok` shim is missing on disk. Reinstall or repair your Open Knowledge CLI. If you switched install sources, run `ok init --pin` again so your editor matches the binary you have.";case`npx-cache`:return"The package-manager cache copy used for this launch may have been removed. Retry once, or run `ok init --pin` so your editor uses a durable absolute path.";default:return"Often means the configured launcher path does not exist (stale pin, moved install, or missing runtime). Re-run `ok init --pin` from your current install or fix the MCP command in your editor settings."}}function ZC(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return YC(e)&&(r+=`\n\n${XC(n)}`),r}function QC(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function $C(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 n=e.expectedProtocolVersion??1,r=t.protocolVersion;if(r===n){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}let i=r===void 0?`unknown (pre-version-field lock)`:`v${r}`,a=t.runtimeVersion?` runtime ${t.runtimeVersion}`:``,o=e.launchPath??process.argv[1],s=qC(o),c=JC(s,o);return{action:`incompatible`,message:`Open Knowledge server at port ${t.port} (pid ${t.pid}${a}) speaks protocol ${i}; this MCP needs protocol v${n}.\n`+c,expectedProtocolVersion:n,actualProtocolVersion:r,lock:t,launchShape:s,launchPath:o}}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 ew(e){let t=e.readLock??(()=>ye(e.lockDir)),n=e.isAlive??be,r=e.sleep??(e=>Xn(e)),i=e.spawn??bn,a=e.readErrorLog??(e=>An(e)?Nn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Mn(e,`w`)),s=e.closeFd??kn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=$C({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n,launchPath:e.launchPath});if(e.logger?.info(`auto-start decision`,{action:d.action,message:d.message,contentDir:e.contentDir}),d.action===`connect`)return{serverUrl:d.url,message:d.message};if(d.action===`disk-only`)return{serverUrl:void 0,message:d.message};if(d.action===`incompatible`)throw e.logger?.error(`protocol mismatch — refusing to connect`,void 0,{expectedProtocolVersion:d.expectedProtocolVersion,actualProtocolVersion:d.actualProtocolVersion,lockPid:d.lock.pid,lockPort:d.lock.port,lockRuntimeVersion:d.lock.runtimeVersion,launchShape:d.launchShape,launchPath:d.launchPath}),Error(d.message);An(e.lockDir)||jn(e.lockDir,{recursive:!0});let f=Tn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=vn();e.logger?.info(`spawning server`,{command:g.command,cwd:e.contentDir,timeoutMs:c});try{try{m=i(g.command,[...g.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,p],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`,OK_PARENT_PID:String(process.pid)}}),m.on(`error`,e=>{h=e instanceof Error?e.message:String(e)}),m.unref()}catch(e){h=e instanceof Error?e.message:String(e)}}finally{try{s(p)}catch{}}let _=Date.now()+c;for(;Date.now()<_;){if(h){let t=a(f);throw e.logger?.error(`spawn failed`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}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(h){let t=a(f);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:h,stderr:t,launchPath:u,stalePinHint:YC(h)}),Error(ZC(h,t,u))}let v=a(f),y=(c/1e3).toFixed(c%1e3==0?0:2),b=m?.pid,x=``;throw typeof b==`number`&&(x=n(b)?` child pid=${b} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${b} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:b,childAlive:typeof b==`number`?n(b):void 0,stderr:v||void 0}),Error(`server did not start within ${y}s.${x}${v?` stderr:\n${v}`:``}`)}function tw(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??ew,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ve(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=ve(i,o),s=_e(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,launchPath:e.launchPath});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 nw(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=Ue({startupCwd:r,startupConfig:n}),a=QC(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=tw({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 WC({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 rw(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-B4CVyYbD.mjs`),r=e(),i=process.cwd(),a=ve(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 iw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function aw(e,t,n=process.cwd()){let r=e.op??`sync`,i=ye(_e(ve(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}`)}iw(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=Se({baseDir:n});if(r===`sync`||r===`pull`){iw(e.json,{type:`step`,step:`pull`});let t=await a.pull();iw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(iw(e.json,{type:`step`,step:`push`}),await a.push(),iw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1405
1405
  `)),iw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function ow(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 aw({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 sw(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await aw({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 cw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await aw({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 lw(e={}){let t=Dn(e.cwd??process.cwd()),n;try{n=await ke({projectDir:t,rootDir:e.root})}catch(e){return e instanceof Te?{status:`prerequisite-missing`,message:`${Le(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Le(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Ie(`Your knowledge base is already seeded.`)}\n${Fe(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${ze(`Plan (dry-run — no changes made):`)}\n\n${uw(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await dw(`${ze(`Plan:`)}\n\n${uw(n,t)}\n\n${ze(`Apply?`)} ${Fe(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Fe(`Cancelled.`),plan:n,exitCode:0};let r=await we(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Le(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Re(`Applied`)} ${r.applied} entries, ${Re(String(r.errors.length))} error(s):`,...e].join(`
1406
1406
  `),plan:n,exitCode:1}}return{status:`applied`,message:`${Ie(`✓ Seeded knowledge base`)} ${Fe(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function uw(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(ze(`Folders to create:`));for(let e of r)n.push(` ${Ie(`+`)} ${Pe(En(t,Dn(t,e.path))||e.path)}${Fe(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(ze(`Files to create:`));for(let e of i)n.push(` ${Ie(`+`)} ${Pe(En(t,Dn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push(ze(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Ie(`+`)} ${Pe(t.folderMatch)} ${Fe(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Fe(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Fe(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Re(`Warnings:`));for(let t of e.warnings)n.push(` ${Re(`!`)} ${t}`)}return n.join(`
1407
- `)}async function dw(e,t){let n=ir({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 fw(){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 lw({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 pw(e,t){return{server:mw(`server`,e),ui:mw(`ui`,t)}}function mw(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 hw(e){return`${gw(e.server)}\n${gw(e.ui)}`}function gw(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 _w(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=pw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(hw(r)),r}function vw(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=>{_w({lockDir:_e(ve(e(),process.cwd())),json:t.json===!0})})}function yw(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 bw(e){let t=e.inspect??(t=>xo(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=yw(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 xw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{bw({lockDir:_e(ve(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Sw=1e4,Cw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function ww(e){let t=e.upstreamTimeoutMs??Sw,n=tr((n,r)=>{Ew(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 Tw(e,t,n){Ew(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Sw)}function Ew(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Cw)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=nr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Cw)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 Dw(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Ow(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-CNDKfHI8.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-CHT8xXaj.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}Tw(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):kw(t)});return}if(h){h(e,t);return}kw(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(y);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let ee=S;_=ee,s(f,ee);let te=e.scheduler??he,ne=e.safetyNetMs??432e5,C=null,w=!1,re=!1,ie=()=>{w||(w=!0,C!==null&&(te.clearTimeout(C),C=null))},T=()=>{if(ie(),!re){re=!0;try{o(f)}catch{}}},ae=()=>{w||ne<=0||(C!==null&&(te.clearTimeout(C),C=null),C=te.setTimeout(()=>{C=null,console.warn(`[ui] safety-net (${ne}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}T()},ne))},oe=()=>{w||ne<=0||ae()};return v=oe,ae(),{httpServers:x,port:ee,release:T,detachSafetyNet:ie,nudgeSafetyNet:oe}}function kw(e){e.writeHead(404),e.end(`Not found`)}function Aw(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 jw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-CNDKfHI8.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 ww({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mw(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-CNDKfHI8.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-CHT8xXaj.mjs`),o=e(),s=t.host,c;try{c=Aw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Ow({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)}};Dw(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 jw({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 Nw=new r;let Pw;Nw.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}=He(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),Pw=r});const Fw=_n(()=>Pw);Nw.addCommand(Fw,{isDefault:!0});const Iw=nw(()=>Pw);Nw.addCommand(Iw),Nw.addCommand(Ne()),Nw.addCommand(fw()),Nw.addCommand(Ro());const Lw=rw(()=>Pw);Nw.addCommand(Lw);const Rw=Mw(()=>Pw);Nw.addCommand(Rw),Nw.addCommand(xw(()=>Pw)),Nw.addCommand(wo(()=>Pw)),Nw.addCommand(vw(()=>Pw)),Nw.addCommand(bo(()=>Pw)),Nw.addCommand(Po(()=>Pw)),Nw.addCommand(ow(()=>Pw)),Nw.addCommand(cw(()=>Pw)),Nw.addCommand(sw(()=>Pw)),await Nw.parseAsync();export{};
1407
+ `)}async function dw(e,t){let n=ir({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 fw(){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 lw({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 pw(e,t){return{server:mw(`server`,e),ui:mw(`ui`,t)}}function mw(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 hw(e){return`${gw(e.server)}\n${gw(e.ui)}`}function gw(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 _w(e){let t=e.inspect??(t=>xo(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=pw(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(hw(r)),r}function vw(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=>{_w({lockDir:_e(ve(e(),process.cwd())),json:t.json===!0})})}function yw(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 bw(e){let t=e.inspect??(t=>xo(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=yw(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 xw(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{bw({lockDir:_e(ve(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const Sw=1e4,Cw=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function ww(e){let t=e.upstreamTimeoutMs??Sw,n=tr((n,r)=>{Ew(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 Tw(e,t,n){Ew(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Sw)}function Ew(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Cw)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=nr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Cw)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 Dw(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Ow(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-C_IerCyc.mjs`),{default:c}=await import(`./build-D4l8tfO0.mjs`),{resolveContentDir:l,resolveLockDir:u}=await import(`./paths-DVek6mWp.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}Tw(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):kw(t)});return}if(h){h(e,t);return}kw(t)},b=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],x=[],S=e.port;try{for(let e of b){let t=n(y);x.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(S,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(S=e.port),n()})})}}catch(e){await Promise.all(x.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{o(f)}catch{}throw e}let ee=S;_=ee,s(f,ee);let te=e.scheduler??he,ne=e.safetyNetMs??432e5,C=null,w=!1,re=!1,ie=()=>{w||(w=!0,C!==null&&(te.clearTimeout(C),C=null))},T=()=>{if(ie(),!re){re=!0;try{o(f)}catch{}}},ae=()=>{w||ne<=0||(C!==null&&(te.clearTimeout(C),C=null),C=te.setTimeout(()=>{C=null,console.warn(`[ui] safety-net (${ne}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of x)try{e.close()}catch{}T()},ne))},oe=()=>{w||ne<=0||ae()};return v=oe,ae(),{httpServers:x,port:ee,release:T,detachSafetyNet:ie,nudgeSafetyNet:oe}}function kw(e){e.writeHead(404),e.end(`Not found`)}function Aw(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 jw(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-C_IerCyc.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 ww({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mw(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-C_IerCyc.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-DVek6mWp.mjs`),o=e(),s=t.host,c;try{c=Aw(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Ow({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)}};Dw(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 jw({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 Nw=new r;let Pw;Nw.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}=He(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),Pw=r});const Fw=_n(()=>Pw);Nw.addCommand(Fw,{isDefault:!0});const Iw=nw(()=>Pw);Nw.addCommand(Iw),Nw.addCommand(Ne()),Nw.addCommand(fw()),Nw.addCommand(Ro());const Lw=rw(()=>Pw);Nw.addCommand(Lw);const Rw=Mw(()=>Pw);Nw.addCommand(Rw),Nw.addCommand(xw(()=>Pw)),Nw.addCommand(wo(()=>Pw)),Nw.addCommand(vw(()=>Pw)),Nw.addCommand(bo(()=>Pw)),Nw.addCommand(Po(()=>Pw)),Nw.addCommand(ow(()=>Pw)),Nw.addCommand(cw(()=>Pw)),Nw.addCommand(sw(()=>Pw)),await Nw.parseAsync();export{};
1408
1408
  //# sourceMappingURL=cli.mjs.map