@inkeep/open-knowledge 0.0.0-dev-20260501144307 → 0.0.0-dev-20260501170533

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-B8HpPaWG.mjs +2 -0
  3. package/dist/{dist-B-uWyCj3.mjs → dist-BVnVlgjQ.mjs} +1 -1
  4. package/dist/{dist-WQbZIrx7.mjs → dist-CDuTCUx1.mjs} +7 -8
  5. package/dist/{dist-CUghvkAf.mjs → dist-oDoSs1Bl.mjs} +7 -7
  6. package/dist/index.mjs +1 -1
  7. package/dist/{init-qoXDcT6N.mjs → init-Bf7LOYAr.mjs} +2 -2
  8. package/dist/init-BhfL8UL0.mjs +1 -0
  9. package/dist/{init-DpiVQYhQ.mjs → init-CPq6B11A.mjs} +3 -3
  10. package/dist/init-DkzHwyzJ.mjs +1 -0
  11. package/dist/loader-5abUX3Eq.mjs +1 -0
  12. package/dist/{loader-BEUtMT2_.mjs → loader-C79dNoU-.mjs} +2 -2
  13. package/dist/paths-BIsyTDX6.mjs +1 -0
  14. package/dist/paths-Drz5vBVF.mjs +2 -0
  15. package/dist/{preview-BIrbsSSc.mjs → preview-AXEdeZ4w.mjs} +2 -2
  16. package/dist/preview-DUYE2XxR.mjs +1 -0
  17. package/dist/public/assets/{ActivityModeContent-C3KENqJ7.js → ActivityModeContent-CCJOMAyp.js} +1 -1
  18. package/dist/public/assets/DocumentContext-BHFNw5NZ.js +37 -0
  19. package/dist/public/assets/{GraphPanel-YIuSwj1X.js → GraphPanel-BuZEMdl-.js} +2 -2
  20. package/dist/public/assets/{McpConsentDialogBody-Dx67JoKA.js → McpConsentDialogBody-CI9rAMX9.js} +1 -1
  21. package/dist/public/assets/OutlinePanel-CnKUM65X.js +2 -0
  22. package/dist/public/assets/SettingsPane-B3rEEyMP.js +6 -0
  23. package/dist/public/assets/{SourceEditor-DGIgtF_h.js → SourceEditor-CE_X9auW.js} +2 -2
  24. package/dist/public/assets/{config-validation-events-Dlj9dOCp.js → config-validation-events-DqfR4UtM.js} +1 -1
  25. package/dist/public/assets/{index-DiLfeu2w.css → index-CKzUuzYV.css} +1 -1
  26. package/dist/public/assets/index-NVu982rh.js +1850 -0
  27. package/dist/public/assets/{target-navigation-intent-BeUCdVKa.js → target-navigation-intent-1238Z_HW.js} +1 -1
  28. package/dist/public/assets/{toggle-group-CyBGhndP.js → toggle-group-C5MXNna8.js} +3 -3
  29. package/dist/public/assets/{tooltip-FdwzzIbl.js → tooltip-BMlqVI54.js} +1 -1
  30. package/dist/public/index.html +9 -9
  31. package/dist/{server-Bc0tGxRk.mjs → server-Cb1yd7Zc.mjs} +2 -2
  32. package/dist/src-CPe0c6hz.mjs +1 -0
  33. package/dist/start-COO3npTl.mjs +1 -0
  34. package/dist/{start-BSqokDQs.mjs → start-Dl1pApAn.mjs} +2 -2
  35. package/package.json +2 -2
  36. package/dist/constants-D4b3yFb4.mjs +0 -2
  37. package/dist/init-CleqrmS6.mjs +0 -1
  38. package/dist/init-D1vMwuMO.mjs +0 -1
  39. package/dist/loader-CwvZAVlq.mjs +0 -1
  40. package/dist/paths-B1biT3Kh.mjs +0 -2
  41. package/dist/paths-BQoQfIvS.mjs +0 -1
  42. package/dist/preview-BNMytxTe.mjs +0 -1
  43. package/dist/public/assets/DocumentContext-gM6_1mHt.js +0 -34
  44. package/dist/public/assets/SettingsPane-tlYUoGwR.js +0 -6
  45. package/dist/public/assets/clipboard-CW1hOwDY.js +0 -5
  46. package/dist/public/assets/index-n9oW9uU-.js +0 -1848
  47. package/dist/src-CGZcpVS_.mjs +0 -1
  48. package/dist/start-C7hQj_dW.mjs +0 -1
  49. /package/dist/public/assets/{mcp-consent-store-BBTXqzE6.js → mcp-consent-store-B9QLSyUV.js} +0 -0
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{A as i,At as a,Ct as o,Dt as s,F as c,Ft as l,It as u,Lt as d,M as f,Mt as p,Nt as m,Ot as h,Pt as g,Q as _,St as v,_t as y,at as b,bt as x,ct as S,dt as C,ft as w,g as ee,gt as T,ht as E,jt as te,kt as ne,lt as D,mt as re,n as ie,ot as O,pt as k,st as ae,ut as oe,v as A,vt as se,wt as ce,x as le,xt as j,y as M,yt as N}from"./dist-CUghvkAf.mjs";import{n as ue,r as de,t as fe}from"./dist-bundle-BSdjl7Rj.mjs";import{i as pe,r as me}from"./constants-D4b3yFb4.mjs";import{n as he,t as ge}from"./paths-B1biT3Kh.mjs";import{l as _e,o as P,s as ve}from"./server-lock-BAi_a4NX-CRPhQdIH.mjs";import{i as ye}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as be,C as xe,Dt as Se,F as Ce,an as we,in as Te,on as Ee,q as De,rn as Oe,wt as ke}from"./dist-WQbZIrx7.mjs";import{a as Ae,i as je,n as Me,t as Ne}from"./server-Bc0tGxRk.mjs";import{t as Pe}from"./is-object-CEU0BgQ5.mjs";import{i as Fe,n as Ie,r as Le,t as Re}from"./loader-BEUtMT2_.mjs";import{r as ze}from"./init-DpiVQYhQ.mjs";import{i as Be,n as Ve,o as He,r as Ue,s as We,t as Ge}from"./colors-BdAXRiXe.mjs";import{t as Ke}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as qe,c as Je,d as Ye,f as Xe,h as Ze,i as Qe,l as $e,m as et,n as tt,o as nt,p as rt,r as it,s as at,t as ot,u as st}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as ct,B as lt,C as ut,D as dt,E as ft,F as pt,H as mt,I as ht,L as gt,M as _t,N as vt,O as yt,P as bt,S as xt,T as St,V as Ct,_ as wt,a as Tt,b as Et,c as Dt,d as Ot,f as F,g as kt,h as At,i as jt,j as Mt,k as Nt,l as Pt,m as Ft,n as It,o as Lt,p as Rt,r as zt,s as Bt,t as Vt,u as Ht,v as Ut,w as Wt,x as Gt,y as Kt,z as qt}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as Jt,c as Yt,d as Xt,i as Zt,l as Qt,n as $t,o as en,r as tn,s as I,t as nn,u as rn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as an,r as on,t as sn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as cn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as ln,t as un}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as dn,t as fn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as pn,r as mn,t as hn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as gn,t as _n}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as vn}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as yn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as bn,s as xn}from"./start-BSqokDQs.mjs";import"./src-CGZcpVS_.mjs";import{execFileSync as Sn,spawn as Cn}from"node:child_process";import*as wn from"node:path";import Tn,{basename as En,dirname as Dn,isAbsolute as On,join as kn,relative as An,resolve as jn}from"node:path";import*as L from"node:fs";import{appendFileSync as Mn,closeSync as Nn,existsSync as Pn,mkdirSync as Fn,openSync as In,readFileSync as Ln,readdirSync as Rn,realpathSync as zn,statSync as Bn,unlinkSync as Vn,writeFileSync as Hn}from"node:fs";import Un from"node:process";import{homedir as Wn,hostname as Gn}from"node:os";import{AsyncLocalStorage as Kn,AsyncResource as qn}from"node:async_hooks";import{stripVTControlCharacters as Jn,styleText as Yn}from"node:util";import*as Xn from"node:readline";import{fileURLToPath as Zn}from"node:url";import{randomUUID as Qn}from"node:crypto";import{readFile as $n,readdir as er,stat as tr}from"node:fs/promises";import{setTimeout as nr}from"node:timers/promises";import{createServer as rr,request as ir}from"node:http";import{lookup as ar}from"node:dns";import{createInterface as or}from"node:readline/promises";var sr=d();const cr=`open-knowledge`;var lr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(cr,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(cr,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(cr,e).deletePassword()}catch{}}},ur=class{backend=`file`;authFile;constructor(e){this.authFile=e??kn(Wn(),`.ok`,`auth.yml`)}read(){if(!Pn(this.authFile))return{};try{return(0,sr.parse)(Ln(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=Dn(this.authFile);Pn(t)||Fn(t,{recursive:!0,mode:448}),Hn(this.authFile,(0,sr.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 dr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(cr,`__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{A as i,At as a,Ct as o,Dt as s,F as c,Ft as l,It as u,Lt as d,M as f,Mt as p,Nt as m,Ot as h,Pt as g,Q as _,St as v,_t as y,at as b,bt as x,ct as S,dt as C,ft as w,g as ee,gt as T,ht as E,jt as te,kt as ne,lt as D,mt as re,n as ie,ot as O,pt as k,st as ae,ut as oe,v as A,vt as se,wt as ce,x as le,xt as j,y as M,yt as N}from"./dist-oDoSs1Bl.mjs";import{n as ue,r as de,t as fe}from"./dist-bundle-BSdjl7Rj.mjs";import{i as pe,r as me}from"./constants-B8HpPaWG.mjs";import{n as he,t as ge}from"./paths-Drz5vBVF.mjs";import{l as _e,o as P,s as ve}from"./server-lock-BAi_a4NX-CRPhQdIH.mjs";import{i as ye}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as be,C as xe,Dt as Se,F as Ce,an as we,cn as Te,on as Ee,q as De,sn as Oe,wt as ke}from"./dist-CDuTCUx1.mjs";import{a as Ae,i as je,n as Me,t as Ne}from"./server-Cb1yd7Zc.mjs";import{t as Pe}from"./is-object-CEU0BgQ5.mjs";import{i as Fe,n as Ie,r as Le,t as Re}from"./loader-C79dNoU-.mjs";import{r as ze}from"./init-CPq6B11A.mjs";import{i as Be,n as Ve,o as He,r as Ue,s as We,t as Ge}from"./colors-BdAXRiXe.mjs";import{t as Ke}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as qe,c as Je,d as Ye,f as Xe,h as Ze,i as Qe,l as $e,m as et,n as tt,o as nt,p as rt,r as it,s as at,t as ot,u as st}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as ct,B as lt,C as ut,D as dt,E as ft,F as pt,H as mt,I as ht,L as gt,M as _t,N as vt,O as yt,P as bt,S as xt,T as St,V as Ct,_ as wt,a as Tt,b as Et,c as Dt,d as Ot,f as F,g as kt,h as At,i as jt,j as Mt,k as Nt,l as Pt,m as Ft,n as It,o as Lt,p as Rt,r as zt,s as Bt,t as Vt,u as Ht,v as Ut,w as Wt,x as Gt,y as Kt,z as qt}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as Jt,c as Yt,d as Xt,i as Zt,l as Qt,n as $t,o as en,r as tn,s as I,t as nn,u as rn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as an,r as on,t as sn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as cn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as ln,t as un}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as dn,t as fn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as pn,r as mn,t as hn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as gn,t as _n}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as vn}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as yn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as bn,s as xn}from"./start-Dl1pApAn.mjs";import"./src-CPe0c6hz.mjs";import{execFileSync as Sn,spawn as Cn}from"node:child_process";import*as wn from"node:path";import Tn,{basename as En,dirname as Dn,isAbsolute as On,join as kn,relative as An,resolve as jn}from"node:path";import*as L from"node:fs";import{appendFileSync as Mn,closeSync as Nn,existsSync as Pn,mkdirSync as Fn,openSync as In,readFileSync as Ln,readdirSync as Rn,realpathSync as zn,statSync as Bn,unlinkSync as Vn,writeFileSync as Hn}from"node:fs";import Un from"node:process";import{homedir as Wn,hostname as Gn}from"node:os";import{AsyncLocalStorage as Kn,AsyncResource as qn}from"node:async_hooks";import{stripVTControlCharacters as Jn,styleText as Yn}from"node:util";import*as Xn from"node:readline";import{fileURLToPath as Zn}from"node:url";import{randomUUID as Qn}from"node:crypto";import{readFile as $n,readdir as er,stat as tr}from"node:fs/promises";import{setTimeout as nr}from"node:timers/promises";import{createServer as rr,request as ir}from"node:http";import{lookup as ar}from"node:dns";import{createInterface as or}from"node:readline/promises";var sr=d();const cr=`open-knowledge`;var lr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(cr,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(cr,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(cr,e).deletePassword()}catch{}}},ur=class{backend=`file`;authFile;constructor(e){this.authFile=e??kn(Wn(),`.ok`,`auth.yml`)}read(){if(!Pn(this.authFile))return{};try{return(0,sr.parse)(Ln(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=Dn(this.authFile);Pn(t)||Fn(t,{recursive:!0,mode:448}),Hn(this.authFile,(0,sr.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 dr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(cr,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new lr}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
4
4
  `),new ur(e)}}async function fr(e,t,n){let r=pr(await mr(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 pr(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 mr(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 hr(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 fr(process.stdin,process.stdout,t);process.exit(n)}),t}function gr(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function _r(e,t,n){let r={baseUrl:gr(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ue(`${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 vr(e){let t=e.request||fe,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),_r(t,`POST /login/device/code`,n)}async function yr(e){let t=await _r(e.request||fe,`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=br(e,t.data.expires_in),n.refreshTokenExpiresAt=br(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function br(e,t){return new Date(e+t*1e3).toISOString()}async function xr(e,t){let n=Sr(e,t.auth);if(n)return n;let{data:r}=await vr({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await wr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Sr(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 Cr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function wr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await yr({...i,clientType:`oauth-app`}):await yr({...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 Cr(r.interval),wr(e,t,n,r);if(a===`slow_down`)return await Cr(r.interval+7),wr(e,t,n,r);throw i}}async function Tr(e,t){return xr(e,{auth:t})}async function Er(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 xr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Dr=`0.0.0-development`;function Or(e){let t=e.request||fe.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Dr} ${de()}`}}),{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(Tr.bind(null,i),{hook:Er.bind(null,i)})}async function kr(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=Or({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 Ar(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const jr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Mr(e){let t=e.toLowerCase().replace(/:\d+$/,``);jr.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 Nr(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Pr(e,t,n,r=kr){let i=Ar(n),{host:a,json:o}=e;Mr(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?Nr(!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?Nr(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Fr(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 Pr(n,await t(),e())})}const Ir=e=>e.name===`enter`||e.name===`return`;var Lr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Rr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},zr=class extends Error{name=`ExitPromptError`},Br=class extends Error{name=`HookError`},Vr=class extends Error{name=`ValidationError`};const Hr=new Kn;function Ur(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Wr(e,t){let n=Ur(e);return Hr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function Gr(){let e=Hr.getStore();if(!e)throw new Br(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Kr(){return Gr().rl}function qr(e){return qn.bind((...t)=>{let n=Gr(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function Jr(e){let t=Gr(),{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 Yr(){Gr().handleChange()}const Xr={queue(e){let t=Gr(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Kr());if(r!=null&&typeof r!=`function`)throw new Vr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=Gr();qr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=Gr();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Zr(e){return typeof e==`function`}function Qr(e){return Jr(t=>{let n=qn.bind(function(e){t.get()!==e&&(t.set(e),Yr())});if(t.initialized)return[t.get(),n];let r=Zr(e)?e():e;return t.set(r),[r,n]})}function $r(e,t){Jr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&Xr.queue(e),n.set(t)})}function ei(){return Un.platform.startsWith(`win`)?!!Un.env.CI||!!Un.env.WT_SESSION||!!Un.env.TERMINUS_SUBLIME||Un.env.ConEmuTask===`{cmd::Cmder}`||Un.env.TERM_PROGRAM===`Terminus-Sublime`||Un.env.TERM_PROGRAM===`vscode`||Un.env.TERM===`xterm-256color`||Un.env.TERM===`alacritty`||Un.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:Un.env.TERM!==`linux`}const ti={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:`╱`},ni={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:`⅒`},ri={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`},ii={...ti,...ni},ai={...ti,...ri},oi=ei()?ii:ai;Object.entries(ni);const si={prefix:{idle:Yn(`blue`,`?`),done:Yn(`green`,oi.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>Yn(`yellow`,e))},style:{answer:e=>Yn(`cyan`,e),message:e=>Yn(`bold`,e),error:e=>Yn(`red`,`> ${e}`),defaultAnswer:e=>Yn(`dim`,`(${e})`),help:e=>Yn(`dim`,e),highlight:e=>Yn(`cyan`,e),key:e=>Yn(`cyan`,Yn(`bold`,`<${e}>`))}};function ci(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 li(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ci(n)&&ci(r)?li(n,r):r}return t}function ui(...e){return li(si,...e.filter(e=>e!=null))}function di({status:e=`idle`,theme:t}){let[n,r]=Qr(!1),[i,a]=Qr(0),{prefix:o,spinner:s}=ui(t);return $r(()=>{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 fi(e){return Qr({current:e})[0]}function pi(e){let t=fi(e);t.current=e,$r(e=>{let n=!1,r=qr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var mi=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 hi=(()=>{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}})(),gi=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,_i=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,vi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,yi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,bi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,xi=/\t{1,1000}/y,Si=/[\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,Ci=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wi=/\p{M}+/gu,Ti={limit:1/0,ellipsis:``},Ei=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ei(i,Ti,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ci,l],[vi,0],[yi,o],[xi,s],[Si,c],[bi,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(wi,``)){let t=e.codePointAt(0)||0;if(S=gi(t)?2:_i(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===bi?hi(e.slice(p,n.lastIndex)):n===Si?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}},Di={limit:1/0,ellipsis:``,ellipsisWidth:0},Oi=(e,t={})=>Ei(e,Di,t).width,ki=`]8;;`,Ai=RegExp(`(?:\\[(?<code>\\d+)m|\\${ki}(?<uri>.*))`,`y`),ji=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},Mi=e=>`[${e}m`,Ni=e=>`${ki}${e}`,Pi=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Oi(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Oi(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(ki,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())},Fi=e=>{let t=e.split(` `),n=t.length;for(;n&&!Oi(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ii=(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=Oi(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=Oi(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(``),Pi(s,r,t),c=Oi(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Pi(s,r,t),c=Oi(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Pi(s,r,t),c=Oi(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Fi(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 ho(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 mo(t,await e())})}async function go(e,t){let{host:n,json:r}=e;Mr(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 po({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 _o(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 go(t,await e())})}async function vo(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function yo(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await vo(t,await e())})}async function bo(e,t){let{host:n,json:r}=e;Mr(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 po({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 xo(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 bo(t,await e())})}function So(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>dr(),i=e??(()=>({}));return t.addCommand(Fr(i,n)),t.addCommand(xo(n)),t.addCommand(_o(n)),t.addCommand(yo(n)),t.addCommand(ho(n)),t.addCommand(hr(n)),t}function Co(e,t,n={}){let r=ve(e,t);if(!Pn(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Ln(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??Gn();return a.hostname===o?(n.isAlive??P)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function wo(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 To(e){let t=e.inspect??(t=>Co(e.lockDir,t)),n=e.unlink??(e=>Vn(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=wo(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 Eo(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{To({lockDir:he(ge(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function Do(){try{let e=Sn(`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 Oo(e,t,n={},r=Do){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 ko(e){return e.replace(/:\d+$/,``)}function Ao(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:ko(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:ko(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:ko(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 jo=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Mo(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 jo)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function No(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Po(e,t,n,r=process.cwd()){let i=Ao(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?jn(r,t.dir):jn(r,i.name);if(Pn(a)&&Rn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await dr(),s=await Oo(i.hostname,o,{}),c=ye({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;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=Mo(e);n&&n.pct!==l&&(l=n.pct,No(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-CleqrmS6.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?No(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?No(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Fo(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?No(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Fo(e){let t=kn(e,`.git`,`info`,`exclude`);if(!Pn(t))return`no-exclude`;let n=Ln(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
24
+ `);try{let{runInit:e}=await import(`./init-BhfL8UL0.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?No(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?No(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Fo(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?No(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Fo(e){let t=kn(e,`.git`,`info`,`exclude`);if(!Pn(t))return`no-exclude`;let n=Ln(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
25
25
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(Hn(t,`${n}${n.length===0||n.endsWith(`
26
26
  `)?``:`
27
- `}.ok/\n`,`utf-8`),`appended`)}function Io(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 Po(t,{json:r.json,dir:n},i);if(r.json)No(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-C7hQj_dW.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?No(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Lo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function Ro(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ie;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function zo(e){let t=(0,sr.parseDocument)(Ln(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Lo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Bo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vo(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Bo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ho(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:je(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:je(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Pn(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=zo(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Vo(Lo.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){l.push({path:n,scope:t,found:r,removed:[],error:c(s.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function Uo(){let e=new r(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Ro({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ho({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const Wo=[` 1. ${Ge(`Customize`)} (sidebar) → ${Ge(`Skills`)}`,` 2. Click the ${Ge(`+`)} button`,` 3. Click ${Ge(`Create skill`)}`,` 4. Click ${Ge(`Upload skill`)}`,` 5. Pick ${Ge(`openknowledge.skill`)} from Downloads`],Go=Be(` Open the Claude Desktop App, then: ${Ge(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Ko(e){let t=[He(`Built ${e.outputPath}`),Ve(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(We(` Handoff failed: ${e.handoffError.message}`)),t.push(Go),t.join(`
27
+ `}.ok/\n`,`utf-8`),`appended`)}function Io(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 Po(t,{json:r.json,dir:n},i);if(r.json)No(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-COO3npTl.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?No(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Lo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function Ro(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ie;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function zo(e){let t=(0,sr.parseDocument)(Ln(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Lo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Bo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vo(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Bo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ho(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??Ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:je(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:je(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Pn(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=zo(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Vo(Lo.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){l.push({path:n,scope:t,found:r,removed:[],error:c(s.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function Uo(){let e=new r(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Ro({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ho({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}const Wo=[` 1. ${Ge(`Customize`)} (sidebar) → ${Ge(`Skills`)}`,` 2. Click the ${Ge(`+`)} button`,` 3. Click ${Ge(`Create skill`)}`,` 4. Click ${Ge(`Upload skill`)}`,` 5. Pick ${Ge(`openknowledge.skill`)} from Downloads`],Go=Be(` Open the Claude Desktop App, then: ${Ge(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`);function Ko(e){let t=[He(`Built ${e.outputPath}`),Ve(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}…`)];return e.handoffError&&t.push(We(` Handoff failed: ${e.handoffError.message}`)),t.push(Go),t.join(`
28
28
  `)}function qo(e){return[He(`Built ${e.outputPath}`),Ve(` ${e.size} bytes • sha256 ${e.sha256?.slice(0,12)}… • CLI v${e.cliVersion}`),Be(` Claude Desktop App opened. Now upload the file manually:`),...Wo,Ve(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${e.outputPath}`)].join(`
29
29
  `)}function Jo(e){return`${Ue(`Error:`)} ${e.buildError??`unknown build failure`}`}async function Yo(e={}){let t=await Ce(e);return t.status===`failed`?{...t,message:Jo(t),exitCode:1}:t.status===`installed`?{...t,message:qo(t),exitCode:0}:{...t,message:Ko(t),exitCode:0}}function Xo(){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 Yo({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var R;(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})(R||={});var Zo;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Zo||={});const z=R.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Qo=e=>{switch(typeof e){case`undefined`:return z.undefined;case`string`:return z.string;case`number`:return Number.isNaN(e)?z.nan:z.number;case`boolean`:return z.boolean;case`function`:return z.function;case`bigint`:return z.bigint;case`symbol`:return z.symbol;case`object`:return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?z.promise:typeof Map<`u`&&e instanceof Map?z.map:typeof Set<`u`&&e instanceof Set?z.set:typeof Date<`u`&&e instanceof Date?z.date:z.object;default:return z.unknown}},B=R.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 $o=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,R.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()}};$o.create=e=>new $o(e);const es=(e,t)=>{let n;switch(e.code){case B.invalid_type:n=e.received===z.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case B.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,R.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:n=`Unrecognized key(s) in object: ${R.joinValues(e.keys,`, `)}`;break;case B.invalid_union:n=`Invalid input`;break;case B.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${R.joinValues(e.options)}`;break;case B.invalid_enum_value:n=`Invalid enum value. Expected ${R.joinValues(e.options)}, received '${e.received}'`;break;case B.invalid_arguments:n=`Invalid function arguments`;break;case B.invalid_return_type:n=`Invalid function return type`;break;case B.invalid_date:n=`Invalid date`;break;case B.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}"`:R.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case B.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 B.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 B.custom:n=`Invalid input`;break;case B.invalid_intersection_types:n=`Intersection results could not be merged`;break;case B.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case B.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,R.assertNever(e)}return{message:n}};let ts=es;function ns(){return ts}const rs=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 V(e,t){let n=ns(),r=rs({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===es?void 0:es].filter(e=>!!e)});e.common.issues.push(r)}var is=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 H;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 H;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 H=Object.freeze({status:`aborted`}),as=e=>({status:`dirty`,value:e}),os=e=>({status:`valid`,value:e}),ss=e=>e.status===`aborted`,cs=e=>e.status===`dirty`,ls=e=>e.status===`valid`,us=e=>typeof Promise<`u`&&e instanceof Promise;var U;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(U||={});var ds=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 fs=(e,t)=>{if(ls(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 $o(e.common.issues),this._error}}};function W(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 G=class{get description(){return this._def.description}_getType(e){return Qo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new is,ctx:{common:e.parent.common,data:e.data,parsedType:Qo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(us(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:Qo(e)};return fs(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:Qo(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ls(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=>ls(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:Qo(e)},r=this._parse({data:e,path:n.path,parent:n});return fs(n,await(us(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:B.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 mc({schema:this,typeName:K.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 hc.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ys.create(this)}promise(){return pc.create(this,this._def)}or(e){return Qs.create([this,e],this._def)}and(e){return nc.create(this,e,this._def)}transform(e){return new mc({...W(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new _c({...W(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new bc({typeName:K.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new vc({...W(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return xc.create(this,e)}readonly(){return Sc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ps=/^c[^\s-]{8,}$/i,ms=/^[0-9a-z]+$/,hs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gs=/^[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,_s=/^[a-z0-9_-]{21}$/i,vs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ys=/^[-+]?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)?)??$/,bs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let xs;const Ss=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Cs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ws=/^(([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]))$/,Ts=/^(([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])$/,Es=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ds=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Os=`((\\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])))`,ks=RegExp(`^${Os}$`);function As(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 js(e){return RegExp(`^${As(e)}$`)}function Ms(e){let t=`${Os}T${As(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Ns(e,t){return!!((t===`v4`||!t)&&Ss.test(e)||(t===`v6`||!t)&&ws.test(e))}function Ps(e,t){if(!vs.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 Fs(e,t){return!!((t===`v4`||!t)&&Cs.test(e)||(t===`v6`||!t)&&Ts.test(e))}var Is=class e extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.string,received:t.parsedType}),H}let t=new is,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.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),V(n,{code:B.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?V(n,{code:B.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&V(n,{code:B.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)bs.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`email`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)xs||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),xs.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`emoji`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)gs.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`uuid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)_s.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`nanoid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ps.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cuid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ms.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cuid2`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)hs.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`ulid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),V(n,{validation:`url`,code:B.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),V(n,{validation:`regex`,code:B.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),V(n,{code:B.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),V(n,{code:B.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ms(r).test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ks.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?js(r).test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?ys.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`duration`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Ns(e.data,r.version)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`ip`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ps(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`jwt`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Fs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cidr`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Es.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`base64`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`base64url`,code:B.invalid_string,message:r.message}),t.dirty()):R.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:B.invalid_string,...U.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...U.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...U.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...U.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...U.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...U.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...U.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...U.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...U.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...U.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...U.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...U.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,...U.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,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...U.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...U.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...U.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...U.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...U.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...U.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...U.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...U.errToObj(t)})}nonempty(e){return this.min(1,U.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}};Is.create=e=>new Is({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...W(e)});function Ls(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 Rs=class e extends G{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)!==z.number){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.number,received:t.parsedType}),H}let t,n=new is;for(let r of this._def.checks)r.kind===`int`?R.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:B.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),V(t,{code:B.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),V(t,{code:B.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ls(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:B.not_finite,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,U.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,U.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,U.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,U.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:U.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:U.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:U.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:U.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:U.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`&&R.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)}};Rs.create=e=>new Rs({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...W(e)});var zs=class e extends G{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)!==z.bigint)return this._getInvalidInput(e);let t,n=new is;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),V(t,{code:B.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),V(t,{code:B.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),V(t,{code:B.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.bigint,received:t.parsedType}),H}gte(e,t){return this.setLimit(`min`,e,!0,U.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,U.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,U.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,U.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.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:U.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:U.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}};zs.create=e=>new zs({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...W(e)});var Bs=class extends G{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.boolean,received:t.parsedType}),H}return os(e.data)}};Bs.create=e=>new Bs({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...W(e)});var Vs=class e extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.date,received:t.parsedType}),H}if(Number.isNaN(e.data.getTime()))return V(this._getOrReturnCtx(e),{code:B.invalid_date}),H;let t=new is,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.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),V(n,{code:B.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):R.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:U.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:U.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)}};Vs.create=e=>new Vs({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...W(e)});var Hs=class extends G{_parse(e){if(this._getType(e)!==z.symbol){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.symbol,received:t.parsedType}),H}return os(e.data)}};Hs.create=e=>new Hs({typeName:K.ZodSymbol,...W(e)});var Us=class extends G{_parse(e){if(this._getType(e)!==z.undefined){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.undefined,received:t.parsedType}),H}return os(e.data)}};Us.create=e=>new Us({typeName:K.ZodUndefined,...W(e)});var Ws=class extends G{_parse(e){if(this._getType(e)!==z.null){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.null,received:t.parsedType}),H}return os(e.data)}};Ws.create=e=>new Ws({typeName:K.ZodNull,...W(e)});var Gs=class extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return os(e.data)}};Gs.create=e=>new Gs({typeName:K.ZodAny,...W(e)});var Ks=class extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return os(e.data)}};Ks.create=e=>new Ks({typeName:K.ZodUnknown,...W(e)});var qs=class extends G{_parse(e){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.never,received:t.parsedType}),H}};qs.create=e=>new qs({typeName:K.ZodNever,...W(e)});var Js=class extends G{_parse(e){if(this._getType(e)!==z.undefined){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.void,received:t.parsedType}),H}return os(e.data)}};Js.create=e=>new Js({typeName:K.ZodVoid,...W(e)});var Ys=class e extends G{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==z.array)return V(t,{code:B.invalid_type,expected:z.array,received:t.parsedType}),H;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(V(t,{code:e?B.too_big:B.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&&(V(t,{code:B.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&&(V(t,{code:B.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 ds(t,e,t.path,n)))).then(e=>is.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ds(t,e,t.path,n)));return is.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:U.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:U.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:U.toString(n)}})}nonempty(e){return this.min(1,e)}};Ys.create=(e,t)=>new Ys({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...W(t)});function Xs(e){if(e instanceof Zs){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=hc.create(Xs(r))}return new Zs({...e._def,shape:()=>t})}else if(e instanceof Ys)return new Ys({...e._def,type:Xs(e.element)});else if(e instanceof hc)return hc.create(Xs(e.unwrap()));else if(e instanceof gc)return gc.create(Xs(e.unwrap()));else if(e instanceof rc)return rc.create(e.items.map(e=>Xs(e)));else return e}var Zs=class e extends G{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:R.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==z.object){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.object,received:t.parsedType}),H}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof qs&&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 ds(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof qs){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&&(V(n,{code:B.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 ds(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=>is.mergeObjectSync(t,e)):is.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return U.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:U.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:K.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 R.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 R.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Xs(this)}partial(t){let n={};for(let e of R.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 R.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof hc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return uc(R.objectKeys(this.shape))}};Zs.create=(e,t)=>new Zs({shape:()=>e,unknownKeys:`strip`,catchall:qs.create(),typeName:K.ZodObject,...W(t)}),Zs.strictCreate=(e,t)=>new Zs({shape:()=>e,unknownKeys:`strict`,catchall:qs.create(),typeName:K.ZodObject,...W(t)}),Zs.lazycreate=(e,t)=>new Zs({shape:e,unknownKeys:`strip`,catchall:qs.create(),typeName:K.ZodObject,...W(t)});var Qs=class extends G{_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 $o(e.ctx.common.issues));return V(t,{code:B.invalid_union,unionErrors:n}),H}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 $o(e));return V(t,{code:B.invalid_union,unionErrors:i}),H}}get options(){return this._def.options}};Qs.create=(e,t)=>new Qs({options:e,typeName:K.ZodUnion,...W(t)});const $s=e=>e instanceof cc?$s(e.schema):e instanceof mc?$s(e.innerType()):e instanceof lc?[e.value]:e instanceof dc?e.options:e instanceof fc?R.objectValues(e.enum):e instanceof _c?$s(e._def.innerType):e instanceof Us?[void 0]:e instanceof Ws?[null]:e instanceof hc?[void 0,...$s(e.unwrap())]:e instanceof gc?[null,...$s(e.unwrap())]:e instanceof bc||e instanceof Sc?$s(e.unwrap()):e instanceof vc?$s(e._def.innerType):[];var ec=class e extends G{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return V(t,{code:B.invalid_type,expected:z.object,received:t.parsedType}),H;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}):(V(t,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),H)}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=$s(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:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...W(r)})}};function tc(e,t){let n=Qo(e),r=Qo(t);if(e===t)return{valid:!0,data:e};if(n===z.object&&r===z.object){let n=R.objectKeys(t),r=R.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=tc(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.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=tc(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===z.date&&r===z.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var nc=class extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ss(e)||ss(r))return H;let i=tc(e.value,r.value);return i.valid?((cs(e)||cs(r))&&t.dirty(),{status:t.value,value:i.data}):(V(n,{code:B.invalid_intersection_types}),H)};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}))}};nc.create=(e,t,n)=>new nc({left:e,right:t,typeName:K.ZodIntersection,...W(n)});var rc=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return V(n,{code:B.invalid_type,expected:z.array,received:n.parsedType}),H;if(n.data.length<this._def.items.length)return V(n,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),H;!this._def.rest&&n.data.length>this._def.items.length&&(V(n,{code:B.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 ds(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>is.mergeArray(t,e)):is.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rc.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new rc({items:e,typeName:K.ZodTuple,rest:null,...W(t)})};var ic=class e extends G{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!==z.object)return V(n,{code:B.invalid_type,expected:z.object,received:n.parsedType}),H;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ds(n,e,n.path,e)),value:a._parse(new ds(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?is.mergeObjectAsync(t,r):is.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof G?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...W(r)}):new e({keyType:Is.create(),valueType:t,typeName:K.ZodRecord,...W(n)})}},ac=class extends G{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!==z.map)return V(n,{code:B.invalid_type,expected:z.map,received:n.parsedType}),H;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ds(n,e,n.path,[a,`key`])),value:i._parse(new ds(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 H;(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 H;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ac.create=(e,t,n)=>new ac({valueType:t,keyType:e,typeName:K.ZodMap,...W(n)});var oc=class e extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return V(n,{code:B.invalid_type,expected:z.set,received:n.parsedType}),H;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(V(n,{code:B.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&&(V(n,{code:B.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 H;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 ds(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:U.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:U.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};oc.create=(e,t)=>new oc({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...W(t)});var sc=class e extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return V(t,{code:B.invalid_type,expected:z.function,received:t.parsedType}),H;function n(e,n){return rs({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ns(),es].filter(e=>!!e),issueData:{code:B.invalid_arguments,argumentsError:n}})}function r(e,n){return rs({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ns(),es].filter(e=>!!e),issueData:{code:B.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof pc){let e=this;return os(async function(...t){let o=new $o([]),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 os(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new $o([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new $o([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:rc.create(t).rest(Ks.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||rc.create([]).rest(Ks.create()),returns:n||Ks.create(),typeName:K.ZodFunction,...W(r)})}},cc=class extends G{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})}};cc.create=(e,t)=>new cc({getter:e,typeName:K.ZodLazy,...W(t)});var lc=class extends G{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return V(t,{received:t.data,code:B.invalid_literal,expected:this._def.value}),H}return{status:`valid`,value:e.data}}get value(){return this._def.value}};lc.create=(e,t)=>new lc({value:e,typeName:K.ZodLiteral,...W(t)});function uc(e,t){return new dc({values:e,typeName:K.ZodEnum,...W(t)})}var dc=class e extends G{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return V(t,{expected:R.joinValues(n),received:t.parsedType,code:B.invalid_type}),H}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return V(t,{received:t.data,code:B.invalid_enum_value,options:n}),H}return os(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})}};dc.create=uc;var fc=class extends G{_parse(e){let t=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let e=R.objectValues(t);return V(n,{expected:R.joinValues(e),received:n.parsedType,code:B.invalid_type}),H}if(this._cache||=new Set(R.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=R.objectValues(t);return V(n,{received:n.data,code:B.invalid_enum_value,options:e}),H}return os(e.data)}get enum(){return this._def.values}};fc.create=(e,t)=>new fc({values:e,typeName:K.ZodNativeEnum,...W(t)});var pc=class extends G{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==z.promise&&t.common.async===!1?(V(t,{code:B.invalid_type,expected:z.promise,received:t.parsedType}),H):os((t.parsedType===z.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};pc.create=(e,t)=>new pc({type:e,typeName:K.ZodPromise,...W(t)});var mc=class extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.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=>{V(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 H;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?as(r.value):r});{if(t.value===`aborted`)return H;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?as(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`?H:(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`?H:(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(!ls(e))return H;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=>ls(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):H);R.assertNever(r)}};mc.create=(e,t,n)=>new mc({schema:e,typeName:K.ZodEffects,effect:t,...W(n)}),mc.createWithPreprocess=(e,t,n)=>new mc({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...W(n)});var hc=class extends G{_parse(e){return this._getType(e)===z.undefined?os(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};hc.create=(e,t)=>new hc({innerType:e,typeName:K.ZodOptional,...W(t)});var gc=class extends G{_parse(e){return this._getType(e)===z.null?os(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gc.create=(e,t)=>new gc({innerType:e,typeName:K.ZodNullable,...W(t)});var _c=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};_c.create=(e,t)=>new _c({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...W(t)});var vc=class extends G{_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 us(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new $o(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new $o(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};vc.create=(e,t)=>new vc({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...W(t)});var yc=class extends G{_parse(e){if(this._getType(e)!==z.nan){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.nan,received:t.parsedType}),H}return{status:`valid`,value:e.data}}};yc.create=e=>new yc({typeName:K.ZodNaN,...W(e)});var bc=class extends G{_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}},xc=class e extends G{_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`?H:e.status===`dirty`?(t.dirty(),as(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`?H: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:K.ZodPipeline})}},Sc=class extends G{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ls(e)&&(e.value=Object.freeze(e.value)),e);return us(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:K.ZodReadonly,...W(t)}),Zs.lazycreate;var K;(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`})(K||={}),Is.create,Rs.create,yc.create,zs.create,Bs.create,Vs.create,Hs.create,Us.create,Ws.create,Gs.create,Ks.create,qs.create,Js.create,Ys.create;const Cc=Zs.create;Zs.strictCreate,Qs.create,ec.create,nc.create,rc.create,ic.create,ac.create,oc.create,sc.create,cc.create,lc.create,dc.create,fc.create,pc.create,mc.create,hc.create,gc.create,mc.createWithPreprocess,xc.create;const wc=u(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);h.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ne(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>te(e,t,n),e.parseAsync=async(t,n)=>a(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>p(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)=>m(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Tc=u(`ZodMiniObject`,(e,t)=>{s.init(e,t),wc.init(e,t),g(e,`shape`,()=>t.shape)});function Ec(e,t){return new Tc({type:`object`,shape:e??{},...l(t)})}function Dc(e){return!!e._zod}function Oc(e){let t=Object.values(e);if(t.length===0)return Ec({});let n=t.every(Dc),r=t.every(e=>!Dc(e));if(n)return Ec(e);if(r)return Cc(e);throw Error(`Mixed Zod versions detected in object shape.`)}function kc(e,t){return Dc(e)?te(e,t):e.safeParse(t)}async function Ac(e,t){return Dc(e)?await p(e,t):await e.safeParseAsync(t)}function jc(e){if(!e)return;let t;if(t=Dc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Mc(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 Oc(e)}}if(Dc(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 Nc(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 Pc(e){return e.description}function Fc(e){if(Dc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Ic(e){if(Dc(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 Lc=`2025-11-25`,Rc=[Lc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],zc=`io.modelcontextprotocol/related-task`,Bc=oe(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Vc=j([x(),E().int()]),Hc=x();re({ttl:E().optional(),pollInterval:E().optional()});const Uc=T({ttl:E().optional()}),Wc=T({taskId:x()}),Gc=re({progressToken:Vc.optional(),[zc]:Wc.optional()}),Kc=T({_meta:Gc.optional()}),qc=Kc.extend({task:Uc.optional()}),Jc=e=>qc.safeParse(e).success,Yc=T({method:x(),params:Kc.loose().optional()}),Xc=T({_meta:Gc.optional()}),Zc=T({method:x(),params:Xc.loose().optional()}),Qc=re({_meta:Gc.optional()}),$c=j([x(),E().int()]),el=T({jsonrpc:k(`2.0`),id:$c,...Yc.shape}).strict(),tl=e=>el.safeParse(e).success,nl=T({jsonrpc:k(`2.0`),...Zc.shape}).strict(),rl=e=>nl.safeParse(e).success,il=T({jsonrpc:k(`2.0`),id:$c,result:Qc}).strict(),al=e=>il.safeParse(e).success;var q;(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`})(q||={});const ol=T({jsonrpc:k(`2.0`),id:$c.optional(),error:T({code:E().int(),message:x(),data:v().optional()})}).strict(),sl=e=>ol.safeParse(e).success,cl=j([el,nl,il,ol]);j([il,ol]);const ll=Qc.strict(),ul=Xc.extend({requestId:$c.optional(),reason:x().optional()}),dl=Zc.extend({method:k(`notifications/cancelled`),params:ul}),fl=T({icons:S(T({src:x(),mimeType:x().optional(),sizes:S(x()).optional(),theme:O([`light`,`dark`]).optional()})).optional()}),pl=T({name:x(),title:x().optional()}),ml=pl.extend({...pl.shape,...fl.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),hl=se(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,w(T({form:w(T({applyDefaults:D().optional()}),N(x(),v())).optional(),url:Bc.optional()}),N(x(),v()).optional())),gl=re({list:Bc.optional(),cancel:Bc.optional(),requests:re({sampling:re({createMessage:Bc.optional()}).optional(),elicitation:re({create:Bc.optional()}).optional()}).optional()}),_l=re({list:Bc.optional(),cancel:Bc.optional(),requests:re({tools:re({call:Bc.optional()}).optional()}).optional()}),vl=T({experimental:N(x(),Bc).optional(),sampling:T({context:Bc.optional(),tools:Bc.optional()}).optional(),elicitation:hl.optional(),roots:T({listChanged:D().optional()}).optional(),tasks:gl.optional(),extensions:N(x(),Bc).optional()}),yl=Kc.extend({protocolVersion:x(),capabilities:vl,clientInfo:ml}),bl=Yc.extend({method:k(`initialize`),params:yl}),xl=T({experimental:N(x(),Bc).optional(),logging:Bc.optional(),completions:Bc.optional(),prompts:T({listChanged:D().optional()}).optional(),resources:T({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:T({listChanged:D().optional()}).optional(),tasks:_l.optional(),extensions:N(x(),Bc).optional()}),Sl=Qc.extend({protocolVersion:x(),capabilities:xl,serverInfo:ml,instructions:x().optional()}),Cl=Zc.extend({method:k(`notifications/initialized`),params:Xc.optional()}),wl=Yc.extend({method:k(`ping`),params:Kc.optional()}),Tl=T({progress:E(),total:y(E()),message:y(x())}),El=T({...Xc.shape,...Tl.shape,progressToken:Vc}),Dl=Zc.extend({method:k(`notifications/progress`),params:El}),Ol=Kc.extend({cursor:Hc.optional()}),kl=Yc.extend({params:Ol.optional()}),Al=Qc.extend({nextCursor:Hc.optional()}),jl=O([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ml=T({taskId:x(),status:jl,ttl:j([E(),ae()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:y(E()),statusMessage:y(x())}),Nl=Qc.extend({task:Ml}),Pl=Xc.merge(Ml),Fl=Zc.extend({method:k(`notifications/tasks/status`),params:Pl}),Il=Yc.extend({method:k(`tasks/get`),params:Kc.extend({taskId:x()})}),Ll=Qc.merge(Ml),Rl=Yc.extend({method:k(`tasks/result`),params:Kc.extend({taskId:x()})});Qc.loose();const zl=kl.extend({method:k(`tasks/list`)}),Bl=Al.extend({tasks:S(Ml)}),Vl=Yc.extend({method:k(`tasks/cancel`),params:Kc.extend({taskId:x()})}),Hl=Qc.merge(Ml),Ul=T({uri:x(),mimeType:y(x()),_meta:N(x(),v()).optional()}),Wl=Ul.extend({text:x()}),Gl=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Kl=Ul.extend({blob:Gl}),ql=O([`user`,`assistant`]),Jl=T({audience:S(ql).optional(),priority:E().min(0).max(1).optional(),lastModified:o({offset:!0}).optional()}),Yl=T({...pl.shape,...fl.shape,uri:x(),description:y(x()),mimeType:y(x()),size:y(E()),annotations:Jl.optional(),_meta:y(re({}))}),Xl=T({...pl.shape,...fl.shape,uriTemplate:x(),description:y(x()),mimeType:y(x()),annotations:Jl.optional(),_meta:y(re({}))}),Zl=kl.extend({method:k(`resources/list`)}),Ql=Al.extend({resources:S(Yl)}),$l=kl.extend({method:k(`resources/templates/list`)}),eu=Al.extend({resourceTemplates:S(Xl)}),tu=Kc.extend({uri:x()}),nu=tu,ru=Yc.extend({method:k(`resources/read`),params:nu}),iu=Qc.extend({contents:S(j([Wl,Kl]))}),au=Zc.extend({method:k(`notifications/resources/list_changed`),params:Xc.optional()}),ou=tu,su=Yc.extend({method:k(`resources/subscribe`),params:ou}),cu=tu,lu=Yc.extend({method:k(`resources/unsubscribe`),params:cu}),uu=Xc.extend({uri:x()}),du=Zc.extend({method:k(`notifications/resources/updated`),params:uu}),fu=T({name:x(),description:y(x()),required:y(D())}),pu=T({...pl.shape,...fl.shape,description:y(x()),arguments:y(S(fu)),_meta:y(re({}))}),mu=kl.extend({method:k(`prompts/list`)}),hu=Al.extend({prompts:S(pu)}),gu=Kc.extend({name:x(),arguments:N(x(),x()).optional()}),_u=Yc.extend({method:k(`prompts/get`),params:gu}),vu=T({type:k(`text`),text:x(),annotations:Jl.optional(),_meta:N(x(),v()).optional()}),yu=T({type:k(`image`),data:Gl,mimeType:x(),annotations:Jl.optional(),_meta:N(x(),v()).optional()}),bu=T({type:k(`audio`),data:Gl,mimeType:x(),annotations:Jl.optional(),_meta:N(x(),v()).optional()}),xu=T({type:k(`tool_use`),name:x(),id:x(),input:N(x(),v()),_meta:N(x(),v()).optional()}),Su=T({type:k(`resource`),resource:j([Wl,Kl]),annotations:Jl.optional(),_meta:N(x(),v()).optional()}),Cu=j([vu,yu,bu,Yl.extend({type:k(`resource_link`)}),Su]),wu=T({role:ql,content:Cu}),Tu=Qc.extend({description:x().optional(),messages:S(wu)}),Eu=Zc.extend({method:k(`notifications/prompts/list_changed`),params:Xc.optional()}),Du=T({title:x().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Ou=T({taskSupport:O([`required`,`optional`,`forbidden`]).optional()}),ku=T({...pl.shape,...fl.shape,description:x().optional(),inputSchema:T({type:k(`object`),properties:N(x(),Bc).optional(),required:S(x()).optional()}).catchall(v()),outputSchema:T({type:k(`object`),properties:N(x(),Bc).optional(),required:S(x()).optional()}).catchall(v()).optional(),annotations:Du.optional(),execution:Ou.optional(),_meta:N(x(),v()).optional()}),Au=kl.extend({method:k(`tools/list`)}),ju=Al.extend({tools:S(ku)}),Mu=Qc.extend({content:S(Cu).default([]),structuredContent:N(x(),v()).optional(),isError:D().optional()});Mu.or(Qc.extend({toolResult:v()}));const Nu=qc.extend({name:x(),arguments:N(x(),v()).optional()}),Pu=Yc.extend({method:k(`tools/call`),params:Nu}),Fu=Zc.extend({method:k(`notifications/tools/list_changed`),params:Xc.optional()});T({autoRefresh:D().default(!0),debounceMs:E().int().nonnegative().default(300)});const Iu=O([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Lu=Kc.extend({level:Iu}),Ru=Yc.extend({method:k(`logging/setLevel`),params:Lu}),zu=Xc.extend({level:Iu,logger:x().optional(),data:v()}),Bu=Zc.extend({method:k(`notifications/message`),params:zu}),Vu=T({hints:S(T({name:x().optional()})).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Hu=T({mode:O([`auto`,`required`,`none`]).optional()}),Uu=T({type:k(`tool_result`),toolUseId:x().describe(`The unique identifier for the corresponding tool call.`),content:S(Cu).default([]),structuredContent:T({}).loose().optional(),isError:D().optional(),_meta:N(x(),v()).optional()}),Wu=C(`type`,[vu,yu,bu]),Gu=C(`type`,[vu,yu,bu,xu,Uu]),Ku=T({role:ql,content:j([Gu,S(Gu)]),_meta:N(x(),v()).optional()}),qu=qc.extend({messages:S(Ku),modelPreferences:Vu.optional(),systemPrompt:x().optional(),includeContext:O([`none`,`thisServer`,`allServers`]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:S(x()).optional(),metadata:Bc.optional(),tools:S(ku).optional(),toolChoice:Hu.optional()}),Ju=Yc.extend({method:k(`sampling/createMessage`),params:qu}),Yu=Qc.extend({model:x(),stopReason:y(O([`endTurn`,`stopSequence`,`maxTokens`]).or(x())),role:ql,content:Wu}),Xu=Qc.extend({model:x(),stopReason:y(O([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(x())),role:ql,content:j([Gu,S(Gu)])}),Zu=T({type:k(`boolean`),title:x().optional(),description:x().optional(),default:D().optional()}),Qu=T({type:k(`string`),title:x().optional(),description:x().optional(),minLength:E().optional(),maxLength:E().optional(),format:O([`email`,`uri`,`date`,`date-time`]).optional(),default:x().optional()}),$u=T({type:O([`number`,`integer`]),title:x().optional(),description:x().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),ed=T({type:k(`string`),title:x().optional(),description:x().optional(),enum:S(x()),default:x().optional()}),td=T({type:k(`string`),title:x().optional(),description:x().optional(),oneOf:S(T({const:x(),title:x()})),default:x().optional()}),nd=j([j([T({type:k(`string`),title:x().optional(),description:x().optional(),enum:S(x()),enumNames:S(x()).optional(),default:x().optional()}),j([ed,td]),j([T({type:k(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({type:k(`string`),enum:S(x())}),default:S(x()).optional()}),T({type:k(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({anyOf:S(T({const:x(),title:x()}))}),default:S(x()).optional()})])]),Zu,Qu,$u]),rd=j([qc.extend({mode:k(`form`).optional(),message:x(),requestedSchema:T({type:k(`object`),properties:N(x(),nd),required:S(x()).optional()})}),qc.extend({mode:k(`url`),message:x(),elicitationId:x(),url:x().url()})]),id=Yc.extend({method:k(`elicitation/create`),params:rd}),ad=Xc.extend({elicitationId:x()}),od=Zc.extend({method:k(`notifications/elicitation/complete`),params:ad}),sd=Qc.extend({action:O([`accept`,`decline`,`cancel`]),content:se(e=>e===null?void 0:e,N(x(),j([x(),E(),D(),S(x())])).optional())}),cd=T({type:k(`ref/resource`),uri:x()}),ld=T({type:k(`ref/prompt`),name:x()}),ud=Kc.extend({ref:j([ld,cd]),argument:T({name:x(),value:x()}),context:T({arguments:N(x(),x()).optional()}).optional()}),dd=Yc.extend({method:k(`completion/complete`),params:ud});function fd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const md=Qc.extend({completion:re({values:S(x()).max(100),total:y(E().int()),hasMore:y(D())})}),hd=T({uri:x().startsWith(`file://`),name:x().optional(),_meta:N(x(),v()).optional()}),gd=Yc.extend({method:k(`roots/list`),params:Kc.optional()}),_d=Qc.extend({roots:S(hd)}),vd=Zc.extend({method:k(`notifications/roots/list_changed`),params:Xc.optional()});j([wl,bl,dd,Ru,_u,mu,Zl,$l,ru,su,lu,Pu,Au,Il,Rl,zl,Vl]),j([dl,Dl,Cl,vd,Fl]),j([ll,Yu,Xu,sd,_d,Ll,Bl,Nl]),j([wl,Ju,id,gd,Il,Rl,zl,Vl]),j([dl,Dl,Bu,du,au,Fu,Eu,Fl,od]),j([ll,Sl,md,Tu,hu,Ql,eu,iu,Mu,ju,Ll,Bl,Nl]);var J=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===q.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new yd(e.elicitations,n)}return new e(t,n,r)}},yd=class extends J{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(q.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function bd(e){return e===`completed`||e===`failed`||e===`cancelled`}const xd=Symbol(`Let zodToJsonSchema decide on which parser to use`),Sd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Cd=e=>typeof e==`string`?{...Sd,name:e}:{...Sd,...e},wd=e=>{let t=Cd(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Td(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Ed(e,t,n,r,i){e[t]=n,Td(e,t,r,i)}const Dd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Od(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Dd(t,e.currentPath):t.join(`/`)}}function kd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==K.ZodAny&&(n.items=bf(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&Ed(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&Ed(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ed(n,`minItems`,e.exactLength.value,e.exactLength.message,t),Ed(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Ad(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?Ed(n,`minimum`,r.value,r.message,t):Ed(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ed(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Ed(n,`maximum`,r.value,r.message,t):Ed(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ed(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Ed(n,`multipleOf`,r.value,r.message,t);break}return n}function jd(){return{type:`boolean`}}function Md(e,t){return bf(e.type._def,t)}const Nd=(e,t)=>bf(e.innerType._def,t);function Pd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Pd(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 Fd(e,t)}}const Fd=(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`:Ed(n,`minimum`,r.value,r.message,t);break;case`max`:Ed(n,`maximum`,r.value,r.message,t);break}return n};function Id(e,t){return{...bf(e.innerType._def,t),default:e.defaultValue()}}function Ld(e,t){return t.effectStrategy===`input`?bf(e.schema._def,t):Od(t)}function Rd(e){return{type:`string`,enum:Array.from(e.values)}}const zd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Bd(e,t){let n=[bf(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),bf(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(zd(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 Vd(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 Hd;const Ud={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:()=>(Hd===void 0&&(Hd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Hd),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 Wd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:Ed(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:Ed(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`:Jd(n,`email`,r.message,t);break;case`format:idn-email`:Jd(n,`idn-email`,r.message,t);break;case`pattern:zod`:Yd(n,Ud.email,r.message,t);break}break;case`url`:Jd(n,`uri`,r.message,t);break;case`uuid`:Jd(n,`uuid`,r.message,t);break;case`regex`:Yd(n,r.regex,r.message,t);break;case`cuid`:Yd(n,Ud.cuid,r.message,t);break;case`cuid2`:Yd(n,Ud.cuid2,r.message,t);break;case`startsWith`:Yd(n,RegExp(`^${Gd(r.value,t)}`),r.message,t);break;case`endsWith`:Yd(n,RegExp(`${Gd(r.value,t)}$`),r.message,t);break;case`datetime`:Jd(n,`date-time`,r.message,t);break;case`date`:Jd(n,`date`,r.message,t);break;case`time`:Jd(n,`time`,r.message,t);break;case`duration`:Jd(n,`duration`,r.message,t);break;case`length`:Ed(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),Ed(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Yd(n,RegExp(Gd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Jd(n,`ipv4`,r.message,t),r.version!==`v4`&&Jd(n,`ipv6`,r.message,t);break;case`base64url`:Yd(n,Ud.base64url,r.message,t);break;case`jwt`:Yd(n,Ud.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Yd(n,Ud.ipv4Cidr,r.message,t),r.version!==`v4`&&Yd(n,Ud.ipv6Cidr,r.message,t);break;case`emoji`:Yd(n,Ud.emoji(),r.message,t);break;case`ulid`:Yd(n,Ud.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Jd(n,`binary`,r.message,t);break;case`contentEncoding:base64`:Ed(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Yd(n,Ud.base64,r.message,t);break}break;case`nanoid`:Yd(n,Ud.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Gd(e,t){return t.patternStrategy===`escape`?qd(e):e}const Kd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function qd(e){let t=``;for(let n=0;n<e.length;n++)Kd.has(e[n])||(t+=`\\`),t+=e[n];return t}function Jd(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}}})):Ed(e,`format`,t,n,r)}function Yd(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:Xd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ed(e,`pattern`,Xd(t,r),n,r)}function Xd(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
30
30
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
@@ -916,7 +916,7 @@ ${e.terminator}`}function Ax(e){return`(${Sx(e.body)})${xx(e.redirections)}`}fun
916
916
  `),n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(r.length>0){let e=r[r.length-1];if((e.stripTabs?i.replace(/^\t+/,``):i)===e.delimiter){n.push(i.trimStart()),r.pop();continue}n.push(i);continue}let a=i.trimStart();n.push(a);for(let e of a.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,n=e[3];r.push({delimiter:n,stripTabs:t})}}return n.join(`
917
917
  `)}var zx=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 zx.decode(n)}catch{return e}}var Vx=[`EACCES`,`escaping sandbox`,`EFBIG`],Hx=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=wn.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,nn(this.root,`ReadWriteFs`),this.canonicalRoot=L.realpathSync(this.root)}resolveAndValidate(e,t){let n=this.allowSymlinks?en(e,this.canonicalRoot):tn(e,this.root,this.canonicalRoot);if(n===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return n}validateParent(e,t){let n=wn.dirname(e),r=this.resolveAndValidate(n,t);return wn.join(r,wn.basename(e))}toRealPath(e){let t=Zt(e),n=wn.join(this.root,t);return wn.resolve(n)}async readFile(e,t){return sn(await this.readFileBuffer(e),an(t))}async readFileBuffer(e){I(e,`open`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,r=await L.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){I(e,`write`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=on(t,an(n)),o=wn.dirname(i);try{await L.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:L.constants.O_NOFOLLOW,n=L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_TRUNC|t,s=await L.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){I(e,`append`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e),a=on(t,an(n)),o=wn.dirname(i);try{await L.promises.mkdir(o,{recursive:!0}),i=this.resolveAndValidate(r,e);let t=this.allowSymlinks?0:L.constants.O_NOFOLLOW,n=L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_APPEND|t,s=await L.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 L.promises.access(n),!0}catch{return!1}}async stat(e){I(e,`stat`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{let t=await L.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){I(e,`lstat`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let e=await L.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){I(e,`mkdir`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await L.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){I(e,`scandir`);let t=this.toRealPath(e),n=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await L.promises.lstat(n)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await L.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){I(e,`rm`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{await L.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){I(e,`cp`),I(t,`cp`);let r=this.toRealPath(e),i=this.toRealPath(t),a=this.resolveAndValidate(r,e),o=this.resolveAndValidate(i,t);try{await L.promises.cp(a,o,{recursive:n?.recursive??!1,filter:async e=>{try{if(L.lstatSync(e).isSymbolicLink()){let t=await L.promises.realpath(e).catch(()=>null);return t===null?!1:Jt(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){I(e,`mv`),I(t,`mv`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.validateParent(n,e),a=this.validateParent(r,t);try{if((await L.promises.lstat(i)).isSymbolicLink()){let n=await L.promises.readlink(i),r=wn.resolve(wn.dirname(a),n);if(!Jt(await L.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=wn.dirname(a);try{await L.promises.mkdir(o,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await L.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(L.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await L.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 Xt(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,n){$t(e,t,n,Vx)}findEscapingSymlinks(e){let t=[];try{let n=L.readdirSync(e);for(let r of n){let n=wn.join(e,r);try{let r=L.lstatSync(n);if(r.isSymbolicLink()){let r=L.readlinkSync(n),i=wn.resolve(e,r),a;try{a=L.realpathSync(i)}catch{a=i}Jt(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=L.readdirSync(r);for(let i of n){let n=e===`/`?`/${i}`:`${e}/${i}`;t.push(n);let a=wn.join(r,i);L.lstatSync(a).isDirectory()&&this.scanDir(n,t)}}catch{}}async chmod(e,t){I(e,`chmod`);let n=this.toRealPath(e),r=this.resolveAndValidate(n,e);try{let e=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,n=await L.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}'`);I(t,`symlink`);let n=this.toRealPath(t),r=this.validateParent(n,t),i=Zt(t),a=Zt(wn.dirname(i)),o=e.startsWith(`/`)?Zt(e):Zt(a===`/`?`/${e}`:`${a}/${e}`),s=wn.join(this.canonicalRoot,o),c=wn.dirname(r),l=e.startsWith(`/`)?s:wn.relative(c,s)||`.`;try{await L.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){I(e,`link`),I(t,`link`);let n=this.toRealPath(e),r=this.toRealPath(t),i=this.resolveAndValidate(n,e),a=this.resolveAndValidate(r,t);try{await L.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){I(e,`readlink`);let t=this.toRealPath(e),n=this.validateParent(t,e);try{let t=await L.promises.readlink(n),r=Zt(e),i=wn.dirname(r),a=wn.isAbsolute(t)?t:wn.resolve(wn.dirname(n),t),o=await L.promises.realpath(a).catch(()=>a);if(Jt(o,this.canonicalRoot)){let e=o.slice(this.canonicalRoot.length)||`/`;return i===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:wn.relative(i,e)}return wn.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){I(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 L.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(Jt(n,this.canonicalRoot))return n.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,n){I(e,`utimes`);let r=this.toRealPath(e),i=this.resolveAndValidate(r,e);try{let e=this.allowSymlinks?L.constants.O_RDONLY:L.constants.O_RDONLY|L.constants.O_NOFOLLOW,r=await L.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 Ux(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const Wx=16*1024*1024;var Gx=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 Kx(e){if(!On(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Lx({cwd:`/`,fs:new Hx({root:jn(e),allowSymlinks:!1})})}async function qx(e,t){let n=await e.exec(t);if(n.stdout.length>Wx)throw new Gx(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 Jx(e){return e.startsWith(`**/`)?e.slice(3):e}async function Yx(e,t,n={}){let r=Kx(t),i=[`-rn`,`-F`];(n.caseInsensitive??!0)&&i.push(`-i`);for(let e of n.include??[])i.push(`--include=${Ux(Jx(e))}`);for(let e of n.exclude??[])i.push(`--exclude=${Ux(Jx(e))}`),i.push(`--exclude-dir=${Ux(Jx(e))}`);let a=n.paths?.length?n.paths.map(Ux):[`.`],o=`grep ${i.join(` `)} ${Ux(e)} ${a.join(` `)}`,s;try{s=await qx(r,o)}catch(e){if(e instanceof Gx)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(`
918
918
  `)){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 Xx=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function Zx(e){let t=jn(e),n=new Map,r=0,i=!1;async function a(e){if(i)return;let o;try{o=await er(e,{withFileTypes:!0})}catch{return}for(let s of o){if(i)return;if(s.isDirectory()&&Xx.has(s.name))continue;let o=jn(e,s.name);if(s.isDirectory()){await a(o);continue}if(s.isFile()){if(r>=1e3){i=!0;return}try{let e=await tr(o);n.set(An(t,o),e.mtimeMs),r++}catch{}}}}return await a(t),{snapshot:n,truncated:i}}function Qx(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 $x=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(` `)}})),eS=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}})),tS=t(n((e=>{e.quote=$x(),e.parse=eS()}))(),1);const nS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function rS(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const iS=[{command:`grep`,applies:e=>e.slice(1).some(rS),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 aS(e){return e.map(e=>{let t=iS.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let n=t.buildExcludeArgs(nS),r=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,r),...n,...e.args.slice(r)]}})}function oS(e){return e.map(e=>e.args.map(Ux).join(` `)).join(` | `)}const sS=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),cS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),lS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),uS=new Set([`-o`,`--output-file`,`--output`]),dS=[`-o=`,`--output-file=`,`--output=`],fS=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),pS=/[`]|\$\(|\$\{|\$'/;function mS(e){return typeof e==`object`&&!!e&&`op`in e}function hS(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return cS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:lS.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 gS(e){let t=[];for(let n of e){if(typeof n==`string`){if(pS.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(!mS(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:hS(n)}}return{args:t}}function _S(e){if(!sS.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(uS.has(t)||dS.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`&&fS.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 vS(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let n;try{n=tS.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(mS(e)&&e.op===`|`){r.push(i),i=[];continue}i.push(e)}r.push(i);let a=[];for(let e of r){let t=gS(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=_S(n);if(r)return{error:r};a.push(n)}return{stages:a}}const yS=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function bS(e,t){let n=e.match(yS);if(!n)return null;try{let e=(0,sr.parse)(n[1]);if(Pe(e)){if(t){let n=t.safeParse(e);return n.success?n.data:null}return e}}catch{}return null}var xS=n(((e,t)=>{let n=`[^\\\\/]`,r=`[^/]`,i=`(?:\\/|$)`,a=`(?:^|\\/)`,o=`\\.{1,2}${i}`,s={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:r,END_ANCHOR:i,DOTS_SLASH:o,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${a}${o})`,NO_DOT_SLASH:`(?!\\.{0,1}${i})`,NO_DOTS_SLASH:`(?!${o})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${r}*?`,START_ANCHOR:a,SEP:`/`},c={...s,SLASH_LITERAL:`[\\\\/]`,QMARK:n,STAR:`${n}*?`,DOTS_SLASH:`\\.{1,2}(?:[\\\\/]|$)`,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))`,NO_DOT_SLASH:`(?!\\.{0,1}(?:[\\\\/]|$))`,NO_DOTS_SLASH:`(?!\\.{1,2}(?:[\\\\/]|$))`,QMARK_NO_DOT:`[^.\\\\/]`,START_ANCHOR:`(?:^|[\\\\/])`,END_ANCHOR:`(?:[\\\\/]|$)`,SEP:`\\`};t.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{__proto__:null,alnum:`a-zA-Z0-9`,alpha:`a-zA-Z`,ascii:`\\x00-\\x7F`,blank:` \\t`,cntrl:`\\x00-\\x1F\\x7F`,digit:`0-9`,graph:`\\x21-\\x7E`,lower:`a-z`,print:`\\x20-\\x7E `,punct:`\\-!"#$%&'()\\*+,./:;<=>?@[\\]^_\`{|}~`,space:` \\t\\r\\n\\v\\f`,upper:`A-Z`,word:`A-Za-z0-9_`,xdigit:`A-Fa-f0-9`},REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":`*`,"**/**":`**`,"**/**/**":`**`},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?c:s}}})),SS=n((e=>{let{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:n,REGEX_SPECIAL_CHARS:r,REGEX_SPECIAL_CHARS_GLOBAL:i}=xS();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>r.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,`\\$1`),e.toPosixSlashes=e=>e.replace(t,`/`),e.isWindows=()=>{if(typeof navigator<`u`&&navigator.platform){let e=navigator.platform.toLowerCase();return e===`win32`||e===`windows`}return typeof process<`u`&&process.platform?process.platform===`win32`:!1},e.removeBackslashes=e=>e.replace(n,e=>e===`\\`?``:e),e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r},e.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:`/`),r=n[n.length-1];return r===``?n[n.length-2]:r}})),CS=n(((e,t)=>{let n=SS(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=xS(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],ee=[],T=e,E=-1,te=0,ne=0,D=!1,re=!1,ie=!1,O=!1,k=!1,ae=!1,oe=!1,A=!1,se=!1,ce=!1,le=0,j,M,N={value:``,depth:0,isGlob:!1},ue=()=>E>=x,de=()=>T.charCodeAt(E+1),fe=()=>(j=M,T.charCodeAt(++E));for(;E<x;){M=fe();let e;if(M===a){oe=N.backslashes=!0,M=fe(),M===u&&(ae=!0);continue}if(ae===!0||M===u){for(le++;ue()!==!0&&(M=fe());){if(M===a){oe=N.backslashes=!0,fe();continue}if(M===u){le++;continue}if(ae!==!0&&M===s&&(M=fe())===s){if(D=N.isBrace=!0,ie=N.isGlob=!0,ce=!0,S===!0)continue;break}if(ae!==!0&&M===o){if(D=N.isBrace=!0,ie=N.isGlob=!0,ce=!0,S===!0)continue;break}if(M===h&&(le--,le===0)){ae=!1,D=N.isBrace=!0,ce=!0;break}}if(S===!0)continue;break}if(M===l){if(C.push(E),w.push(N),N={value:``,depth:0,isGlob:!1},ce===!0)continue;if(j===s&&E===te+1){te+=2;continue}ne=E+1;continue}if(b.noext!==!0&&(M===p||M===i||M===r||M===m||M===c)&&de()===d){if(ie=N.isGlob=!0,O=N.isExtglob=!0,ce=!0,M===c&&E===te&&(se=!0),S===!0){for(;ue()!==!0&&(M=fe());){if(M===a){oe=N.backslashes=!0,M=fe();continue}if(M===g){ie=N.isGlob=!0,ce=!0;break}}continue}break}if(M===r){if(j===r&&(k=N.isGlobstar=!0),ie=N.isGlob=!0,ce=!0,S===!0)continue;break}if(M===m){if(ie=N.isGlob=!0,ce=!0,S===!0)continue;break}if(M===f){for(;ue()!==!0&&(e=fe());){if(e===a){oe=N.backslashes=!0,fe();continue}if(e===_){re=N.isBracket=!0,ie=N.isGlob=!0,ce=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&M===c&&E===te){A=N.negated=!0,te++;continue}if(b.noparen!==!0&&M===d){if(ie=N.isGlob=!0,S===!0){for(;ue()!==!0&&(M=fe());){if(M===d){oe=N.backslashes=!0,M=fe();continue}if(M===g){ce=!0;break}}continue}break}if(ie===!0){if(ce=!0,S===!0)continue;break}}b.noext===!0&&(O=!1,ie=!1);let pe=T,me=``,he=``;te>0&&(me=T.slice(0,te),T=T.slice(te),ne-=te),pe&&ie===!0&&ne>0?(pe=T.slice(0,ne),he=T.slice(ne)):ie===!0?(pe=``,he=T):pe=T,pe&&pe!==``&&pe!==`/`&&pe!==T&&v(pe.charCodeAt(pe.length-1))&&(pe=pe.slice(0,-1)),b.unescape===!0&&(he&&=n.removeBackslashes(he),pe&&oe===!0&&(pe=n.removeBackslashes(pe)));let ge={prefix:me,input:e,start:te,base:pe,glob:he,isBrace:D,isBracket:re,isGlob:ie,isExtglob:O,isGlobstar:k,negated:A,negatedExtglob:se};if(b.tokens===!0&&(ge.maxDepth=0,v(M)||w.push(N),ge.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:te,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&te!==0?(w[n].isPrefix=!0,w[n].value=me):w[n].value=a,y(w[n]),ge.maxDepth+=w[n].depth),(n!==0||a!==``)&&ee.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);ee.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),ge.maxDepth+=w[w.length-1].depth)}ge.slashes=C,ge.parts=ee}return ge}})),wS=n(((e,t)=>{let n=xS(),r=SS(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=e=>{let t=[],n=0,r=0,i=0,a=``,o=!1;for(let s of e){if(o===!0){a+=s,o=!1;continue}if(s===`\\`){a+=s,o=!0;continue}if(s===`"`){i=i===1?0:1,a+=s;continue}if(i===0){if(s===`[`)n++;else if(s===`]`&&n>0)n--;else if(n===0){if(s===`(`)r++;else if(s===`)`&&r>0)r--;else if(s===`|`&&r===0){t.push(a),a=``;continue}}}a+=s}return t.push(a),t},f=e=>{let t=!1;for(let n of e){if(t===!0){t=!1;continue}if(n===`\\`){t=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},p=e=>{let t=e.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=!0);if(f(t))return t.replace(/\\(.)/g,`$1`)},m=e=>{let t=e.map(p).filter(Boolean);for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=t[e],i=t[n],a=r[0];if(!(!a||r!==a.repeat(r.length)||i!==a.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},h=(e,t=!0)=>{if(e[0]!==`+`&&e[0]!==`*`||e[1]!==`(`)return;let n=0,r=0,i=0,a=!1;for(let o=1;o<e.length;o++){let s=e[o];if(a===!0){a=!1;continue}if(s===`\\`){a=!0;continue}if(s===`"`){i=i===1?0:1;continue}if(i!==1){if(s===`[`){n++;continue}if(s===`]`&&n>0){n--;continue}if(!(n>0)){if(s===`(`){r++;continue}if(s===`)`&&(r--,r===0))return t===!0&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},g=e=>{let t=0,n=[];for(;t<e.length;){let r=h(e.slice(t),!1);if(!r||r.type!==`*`)return;let i=d(r.body).map(e=>e.trim());if(i.length!==1)return;let a=p(i[0]);if(!a||a.length!==1)return;n.push(a),t+=r.end+1}if(!(n.length<1))return`${n.length===1?r.escapeRegex(n[0]):`[${n.map(e=>r.escapeRegex(e)).join(``)}]`}*`},_=e=>{let t=0,n=e.trim(),r=h(n);for(;r;)t++,n=r.body.trim(),r=h(n);return t},v=(e,t)=>{if(t.maxExtglobRecursion===!1)return{risky:!1};let r=typeof t.maxExtglobRecursion==`number`?t.maxExtglobRecursion:n.DEFAULT_MAX_EXTGLOB_RECURSION,i=d(e).map(e=>e.trim());if(i.length>1&&(i.some(e=>e===``)||i.some(e=>/^[*?]+$/.test(e))||m(i)))return{risky:!0};for(let e of i){let t=g(e);if(t)return{risky:!0,safeOutput:t};if(_(e)>r)return{risky:!0}}return{risky:!1}},y=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let d={...t},f=typeof d.maxLength==`number`?Math.min(i,d.maxLength):i,p=e.length;if(p>f)throw SyntaxError(`Input length: ${p}, exceeds maximum allowed length: ${f}`);let m={type:`bos`,value:``,output:d.prepend||``},h=[m],g=d.capture?``:`?:`,_=n.globChars(d.windows),b=n.extglobChars(_),{DOT_LITERAL:x,PLUS_LITERAL:S,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:ee,NO_DOT:T,NO_DOT_SLASH:E,NO_DOTS_SLASH:te,QMARK:ne,QMARK_NO_DOT:D,STAR:re,START_ANCHOR:ie}=_,O=e=>`(${g}(?:(?!${ie}${e.dot?ee:x}).)*?)`,k=d.dot?``:T,ae=d.dot?ne:D,oe=d.bash===!0?O(d):re;d.capture&&(oe=`(${oe})`),typeof d.noext==`boolean`&&(d.noextglob=d.noext);let A={input:e,index:-1,start:0,dot:d.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:h};e=r.removePrefix(e,A),p=e.length;let se=[],ce=[],le=[],j=m,M,N=()=>A.index===p-1,ue=A.peek=(t=1)=>e[A.index+t],de=A.advance=()=>e[++A.index]||``,fe=()=>e.slice(A.index+1),pe=(e=``,t=0)=>{A.consumed+=e,A.index+=t},me=e=>{A.output+=e.output==null?e.value:e.output,pe(e.value)},he=()=>{let e=1;for(;ue()===`!`&&(ue(2)!==`(`||ue(3)===`?`);)de(),A.start++,e++;return e%2==0?!1:(A.negated=!0,A.start++,!0)},ge=e=>{A[e]++,le.push(e)},_e=e=>{A[e]--,le.pop()},P=e=>{if(j.type===`globstar`){let t=A.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||se.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(A.output=A.output.slice(0,-j.output.length),j.type=`star`,j.value=`*`,j.output=oe,A.output+=j.output)}if(se.length&&e.type!==`paren`&&(se[se.length-1].inner+=e.value),(e.value||e.output)&&me(e),j&&j.type===`text`&&e.type===`text`){j.output=(j.output||j.value)+e.value,j.value+=e.value;return}e.prev=j,h.push(e),j=e},ve=(e,t)=>{let n={...b[t],conditions:1,inner:``};n.prev=j,n.parens=A.parens,n.output=A.output,n.startIndex=A.index,n.tokensIndex=h.length;let r=(d.capture?`(`:``)+n.open;ge(`parens`),P({type:e,value:t,output:A.output?``:w}),P({type:`paren`,extglob:!0,value:de(),output:r}),se.push(n)},ye=n=>{let i=e.slice(n.startIndex,A.index+1),a=v(e.slice(n.startIndex+2,A.index),d);if((n.type===`plus`||n.type===`star`)&&a.risky){let e=a.safeOutput?(n.output?``:w)+(d.capture?`(${a.safeOutput})`:a.safeOutput):void 0,t=h[n.tokensIndex];t.type=`text`,t.value=i,t.output=e||r.escapeRegex(i);for(let e=n.tokensIndex+1;e<h.length;e++)h[e].value=``,h[e].output=``,delete h[e].suffix;A.output=n.output+t.output,A.backtrack=!0,P({type:`paren`,extglob:!0,value:M,output:``}),_e(`parens`);return}let o=n.close+(d.capture?`)`:``),s;if(n.type===`negate`){let e=oe;n.inner&&n.inner.length>1&&n.inner.includes(`/`)&&(e=O(d)),(e!==oe||N()||/^\)+$/.test(fe()))&&(o=n.close=`)$))${e}`),n.inner.includes(`*`)&&(s=fe())&&/^\.[^\\/.]+$/.test(s)&&(o=n.close=`)${y(s,{...t,fastpaths:!1}).output})${e})`),n.prev.type===`bos`&&(A.negatedExtglob=!0)}P({type:`paren`,extglob:!0,value:M,output:o}),_e(`parens`)};if(d.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?ne.repeat(a.length):``):o===0?ae+(a?ne.repeat(a.length):``):ne.repeat(r.length):i===`.`?x.repeat(r.length):i===`*`?t?t+i+(a?oe:``):oe:t?e:`\\${e}`);return n===!0&&(i=d.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&d.contains===!0?(A.output=e,A):(A.output=r.wrapOutput(i,A,t),A)}for(;!N();){if(M=de(),M===`\0`)continue;if(M===`\\`){let e=ue();if(e===`/`&&d.bash!==!0||e===`.`||e===`;`)continue;if(!e){M+=`\\`,P({type:`text`,value:M});continue}let t=/^\\+/.exec(fe()),n=0;if(t&&t[0].length>2&&(n=t[0].length,A.index+=n,n%2!=0&&(M+=`\\`)),d.unescape===!0?M=de():M+=de(),A.brackets===0){P({type:`text`,value:M});continue}}if(A.brackets>0&&(M!==`]`||j.value===`[`||j.value===`[^`)){if(d.posix!==!1&&M===`:`){let e=j.value.slice(1);if(e.includes(`[`)&&(j.posix=!0,e.includes(`:`))){let e=j.value.lastIndexOf(`[`),t=j.value.slice(0,e),n=a[j.value.slice(e+2)];if(n){j.value=t+n,A.backtrack=!0,de(),!m.output&&h.indexOf(j)===1&&(m.output=w);continue}}}(M===`[`&&ue()!==`:`||M===`-`&&ue()===`]`)&&(M=`\\${M}`),M===`]`&&(j.value===`[`||j.value===`[^`)&&(M=`\\${M}`),d.posix===!0&&M===`!`&&j.value===`[`&&(M=`^`),j.value+=M,me({value:M});continue}if(A.quotes===1&&M!==`"`){M=r.escapeRegex(M),j.value+=M,me({value:M});continue}if(M===`"`){A.quotes=A.quotes===1?0:1,d.keepQuotes===!0&&P({type:`text`,value:M});continue}if(M===`(`){ge(`parens`),P({type:`paren`,value:M});continue}if(M===`)`){if(A.parens===0&&d.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=se[se.length-1];if(e&&A.parens===e.parens+1){ye(se.pop());continue}P({type:`paren`,value:M,output:A.parens?`)`:`\\)`}),_e(`parens`);continue}if(M===`[`){if(d.nobracket===!0||!fe().includes(`]`)){if(d.nobracket!==!0&&d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));M=`\\${M}`}else ge(`brackets`);P({type:`bracket`,value:M});continue}if(M===`]`){if(d.nobracket===!0||j&&j.type===`bracket`&&j.value.length===1){P({type:`text`,value:M,output:`\\${M}`});continue}if(A.brackets===0){if(d.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));P({type:`text`,value:M,output:`\\${M}`});continue}_e(`brackets`);let e=j.value.slice(1);if(j.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(M=`/${M}`),j.value+=M,me({value:M}),d.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(j.value);if(A.output=A.output.slice(0,-j.value.length),d.literalBrackets===!0){A.output+=t,j.value=t;continue}j.value=`(${g}${t}|${j.value})`,A.output+=j.value;continue}if(M===`{`&&d.nobrace!==!0){ge(`braces`);let e={type:`brace`,value:M,output:`(`,outputIndex:A.output.length,tokensIndex:A.tokens.length};ce.push(e),P(e);continue}if(M===`}`){let e=ce[ce.length-1];if(d.nobrace===!0||!e){P({type:`text`,value:M,output:M});continue}let t=`)`;if(e.dots===!0){let e=h.slice(),n=[];for(let t=e.length-1;t>=0&&(h.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,d),A.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=A.output.slice(0,e.outputIndex),r=A.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,M=t=`\\}`,A.output=n;for(let e of r)A.output+=e.output||e.value}P({type:`brace`,value:M,output:t}),_e(`braces`),ce.pop();continue}if(M===`|`){se.length>0&&se[se.length-1].conditions++,P({type:`text`,value:M});continue}if(M===`,`){let e=M,t=ce[ce.length-1];t&&le[le.length-1]===`braces`&&(t.comma=!0,e=`|`),P({type:`comma`,value:M,output:e});continue}if(M===`/`){if(j.type===`dot`&&A.index===A.start+1){A.start=A.index+1,A.consumed=``,A.output=``,h.pop(),j=m;continue}P({type:`slash`,value:M,output:C});continue}if(M===`.`){if(A.braces>0&&j.type===`dot`){j.value===`.`&&(j.output=x);let e=ce[ce.length-1];j.type=`dots`,j.output+=M,j.value+=M,e.dots=!0;continue}if(A.braces+A.parens===0&&j.type!==`bos`&&j.type!==`slash`){P({type:`text`,value:M,output:x});continue}P({type:`dot`,value:M,output:x});continue}if(M===`?`){if(!(j&&j.value===`(`)&&d.noextglob!==!0&&ue()===`(`&&ue(2)!==`?`){ve(`qmark`,M);continue}if(j&&j.type===`paren`){let e=ue(),t=M;(j.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(fe()))&&(t=`\\${M}`),P({type:`text`,value:M,output:t});continue}if(d.dot!==!0&&(j.type===`slash`||j.type===`bos`)){P({type:`qmark`,value:M,output:D});continue}P({type:`qmark`,value:M,output:ne});continue}if(M===`!`){if(d.noextglob!==!0&&ue()===`(`&&(ue(2)!==`?`||!/[!=<:]/.test(ue(3)))){ve(`negate`,M);continue}if(d.nonegate!==!0&&A.index===0){he();continue}}if(M===`+`){if(d.noextglob!==!0&&ue()===`(`&&ue(2)!==`?`){ve(`plus`,M);continue}if(j&&j.value===`(`||d.regex===!1){P({type:`plus`,value:M,output:S});continue}if(j&&(j.type===`bracket`||j.type===`paren`||j.type===`brace`)||A.parens>0){P({type:`plus`,value:M});continue}P({type:`plus`,value:S});continue}if(M===`@`){if(d.noextglob!==!0&&ue()===`(`&&ue(2)!==`?`){P({type:`at`,extglob:!0,value:M,output:``});continue}P({type:`text`,value:M});continue}if(M!==`*`){(M===`$`||M===`^`)&&(M=`\\${M}`);let e=o.exec(fe());e&&(M+=e[0],A.index+=e[0].length),P({type:`text`,value:M});continue}if(j&&(j.type===`globstar`||j.star===!0)){j.type=`star`,j.star=!0,j.value+=M,j.output=oe,A.backtrack=!0,A.globstar=!0,pe(M);continue}let t=fe();if(d.noextglob!==!0&&/^\([^?]/.test(t)){ve(`star`,M);continue}if(j.type===`star`){if(d.noglobstar===!0){pe(M);continue}let n=j.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(d.bash===!0&&(!i||t[0]&&t[0]!==`/`)){P({type:`star`,value:M,output:``});continue}let o=A.braces>0&&(n.type===`comma`||n.type===`brace`),s=se.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){P({type:`star`,value:M,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[A.index+4];if(n&&n!==`/`)break;t=t.slice(3),pe(`/**`,3)}if(n.type===`bos`&&N()){j.type=`globstar`,j.value+=M,j.output=O(d),A.output=j.output,A.globstar=!0,pe(M);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&N()){A.output=A.output.slice(0,-(n.output+j.output).length),n.output=`(?:${n.output}`,j.type=`globstar`,j.output=O(d)+(d.strictSlashes?`)`:`|$)`),j.value+=M,A.globstar=!0,A.output+=n.output+j.output,pe(M);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;A.output=A.output.slice(0,-(n.output+j.output).length),n.output=`(?:${n.output}`,j.type=`globstar`,j.output=`${O(d)}${C}|${C}${e})`,j.value+=M,A.output+=n.output+j.output,A.globstar=!0,pe(M+de()),P({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){j.type=`globstar`,j.value+=M,j.output=`(?:^|${C}|${O(d)}${C})`,A.output=j.output,A.globstar=!0,pe(M+de()),P({type:`slash`,value:`/`,output:``});continue}A.output=A.output.slice(0,-j.output.length),j.type=`globstar`,j.output=O(d),j.value+=M,A.output+=j.output,A.globstar=!0,pe(M);continue}let n={type:`star`,value:M,output:oe};if(d.bash===!0){n.output=`.*?`,(j.type===`bos`||j.type===`slash`)&&(n.output=k+n.output),P(n);continue}if(j&&(j.type===`bracket`||j.type===`paren`)&&d.regex===!0){n.output=M,P(n);continue}(A.index===A.start||j.type===`slash`||j.type===`dot`)&&(j.type===`dot`?(A.output+=E,j.output+=E):d.dot===!0?(A.output+=te,j.output+=te):(A.output+=k,j.output+=k),ue()!==`*`&&(A.output+=w,j.output+=w)),P(n)}for(;A.brackets>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));A.output=r.escapeLast(A.output,`[`),_e(`brackets`)}for(;A.parens>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));A.output=r.escapeLast(A.output,`(`),_e(`parens`)}for(;A.braces>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));A.output=r.escapeLast(A.output,`{`),_e(`braces`)}if(d.strictSlashes!==!0&&(j.type===`star`||j.type===`bracket`)&&P({type:`maybe_slash`,value:``,output:`${C}?`}),A.backtrack===!0){A.output=``;for(let e of A.tokens)A.output+=e.output==null?e.value:e.output,e.suffix&&(A.output+=e.suffix)}return A};y.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let{DOT_LITERAL:l,SLASH_LITERAL:u,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:m,NO_DOTS_SLASH:h,STAR:g,START_ANCHOR:_}=n.globChars(a.windows),v=a.dot?m:p,y=a.dot?h:p,b=a.capture?``:`?:`,x={negated:!1,prefix:``},S=a.bash===!0?`.*?`:g;a.capture&&(S=`(${S})`);let C=e=>e.noglobstar===!0?S:`(${b}(?:(?!${_}${e.dot?f:l}).)*?)`,w=e=>{switch(e){case`*`:return`${v}${d}${S}`;case`.*`:return`${l}${d}${S}`;case`*.*`:return`${v}${S}${l}${d}${S}`;case`*/*`:return`${v}${S}${u}${d}${y}${S}`;case`**`:return v+C(a);case`**/*`:return`(?:${v}${C(a)}${u})?${y}${d}${S}`;case`**/*.*`:return`(?:${v}${C(a)}${u})?${y}${S}${l}${d}${S}`;case`**/.*`:return`(?:${v}${C(a)}${u})?${l}${d}${S}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=w(t[1]);return n?n+l+t[2]:void 0}}},ee=w(r.removePrefix(e,x));return ee&&a.strictSlashes!==!0&&(ee+=`${u}?`),ee},t.exports=y})),TS=n(((e,t)=>{let n=CS(),r=wS(),i=SS(),a=xS(),o=e=>e&&typeof e==`object`&&!Array.isArray(e),s=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>s(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=o(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},a=i.windows,c=r?s.compileRe(e,t):s.makeRe(e,t,!1,!0),l=c.state;delete c.state;let u=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};u=s(i.ignore,e,n)}let d=(n,r=!1)=>{let{isMatch:o,match:d,output:f}=s.test(n,c,t,{glob:e,posix:a}),p={glob:e,state:l,regex:c,posix:a,input:n,output:f,match:d,isMatch:o};return typeof i.onResult==`function`&&i.onResult(p),o===!1?(p.isMatch=!1,r?p:!1):u(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(d.state=l),d};s.test=(e,t,n,{glob:r,posix:a}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},c=o.format||(a?i.toPosixSlashes:null),l=e===r,u=l&&c?c(e):e;return l===!1&&(u=c?c(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?s.matchBase(e,t,n,a):t.exec(u)),{isMatch:!!l,match:l,output:u}},s.matchBase=(e,t,n)=>(t instanceof RegExp?t:s.makeRe(t,n)).test(i.basename(e)),s.isMatch=(e,t,n)=>s(t,n)(e),s.parse=(e,t)=>Array.isArray(e)?e.map(e=>s.parse(e,t)):r(e,{...t,fastpaths:!1}),s.scan=(e,t)=>n(e,t),s.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,c=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let l=s.toRegex(c,t);return r===!0&&(l.state=e),l},s.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=r.fastpaths(e,t)),a.output||(a=r(e,t)),s.compileRe(a,t,n,i)},s.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},s.constants=a,t.exports=s})),ES=t(n(((e,t)=>{let n=TS(),r=SS();function i(e,t,i=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:r.isWindows()}),n(e,t,i)}Object.assign(i,n),t.exports=i}))(),1);const DS=new WeakMap;function OS(e){let t=DS.get(e);if(t)return t;let n=e.map(e=>(0,ES.default)(e.match,{dot:!0}));return DS.set(e,n),n}function kS(e,t){if(e.length===0)return{};let n=OS(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 Bn(jn(e,`.git`)).isDirectory()}catch{return!1}}function jS(e){return ye({baseDir:jn(e),timeout:{block:5e3}})}async function MS(e,t,n=5){if(!AS(e))return{commits:[],source:`git-absent`};let r=jS(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(`
919
- `)){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 NS=5e3;async function PS(e){try{let t=(await ye({baseDir:e,timeout:{block:NS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function FS(e,t){return ye({baseDir:t,timeout:{block:NS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function IS(e,t){let n=Te(t);return e.startsWith(n)?e.slice(n.length):e}async function LS(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=IS(t,r),s=we(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:Ee(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function RS(e,t,n=5){let r=Oe(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await PS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=FS(r,jn(e)),o=``;try{o=await a.raw(`for-each-ref`,Te(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
919
+ `)){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 NS=5e3;async function PS(e){try{let t=(await ye({baseDir:e,timeout:{block:NS}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function FS(e,t){return ye({baseDir:t,timeout:{block:NS}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function IS(e,t){let n=Ee(t);return e.startsWith(n)?e.slice(n.length):e}async function LS(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=IS(t,r),s=Oe(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:Te(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function RS(e,t,n=5){let r=we(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await PS(e);if(!i)return{commits:[],source:`shadow-repo`};let a=FS(r,jn(e)),o=``;try{o=await a.raw(`for-each-ref`,Ee(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
920
920
  `).map(e=>e.trim()).filter(Boolean);return s.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(s.map(e=>LS(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n),source:`shadow-repo`}}const zS=1e3,BS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),VS=/\.(md|mdx)$/i,HS=T({title:x().optional(),description:x().optional(),tags:S(x()).default([])});function US(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}async function WS(e){try{let t=bS(await $n(e,`utf-8`),HS);return t?{title:t.title,description:t.description,tags:t.tags??[]}:{tags:[]}}catch{return null}}async function GS(e,t){if(!e)return null;let n=await th(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 KS(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 th(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 qS(e,t){if(!e)return null;let n=await th(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 JS(e,t,n){let r=t??[],i=r.length===0?{}:kS(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 YS(e,t,n={}){let r=e.replace(/^\.\//,``).replace(/^\/+/,``),i=jn(t.projectDir,r),a=t.historyDepth??5,o=n.includeRichFields===!0,s=WS(i);if(!o){let e=JS(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,GS(t.serverUrl,US(r)).catch(()=>null),qS(t.serverUrl,US(r)).catch(()=>null),RS(t.projectDir,r,a).catch(()=>({commits:[],source:`shadow-repo`})),MS(t.projectDir,r,a).catch(()=>({commits:[],source:`git`}))]),p=JS(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 XS(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>=zS){n.truncated=!0;break}let a;try{a=await er(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=zS){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(BS.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&VS.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await tr(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:An(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function ZS(e,t){let n=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),r=await XS(jn(t.projectDir,n),t.projectDir),i;if(r.mostRecent){let e=await WS(r.mostRecent.absPath);i={path:r.mostRecent.relPath,title:e?.title??En(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=kS(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 QS=50*1024,$S=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,eC=["**STOP — native tools on in-scope markdown (when project has `.ok/`).** When the active project contains `.ok/`, 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 `.ok/`.",``,`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
921
  `);function tC(e){let t=e.split(`
922
922
  `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=QS)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>QS)break;a++}let o=t.slice(0,a).join(`
@@ -1405,8 +1405,8 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
1405
1405
  Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
1406
1406
 
1407
1407
  **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.ok/\`, 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.
1408
- `}async function Lw(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 Rw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(Fw=Tm(),Fw.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Lw(n,Fw);Fw.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else Fw.info(`server discovery is lazy per effective cwd`);let o=new lm({name:me,version:pe},{instructions:Iw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Nw({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:Fw}),c=Pw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(vd,async()=>{s.invalidateRoots()});let u=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await l();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},d=Qn(),f=process.env.AGENT_LABEL||void 0,p={current:{connectionId:d,label:f,displayName:f??`Agent`,colorSeed:f??d}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();p.current={connectionId:d,clientInfo:e?{name:e.name,version:e.version}:void 0,label:f,displayName:f??e?.name??`Agent`,colorSeed:f??e?.name??d},Fw?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},Aw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:Fw});let m=new Sm;await o.connect(m),Fw.info(`MCP server running on stdio`);let{startKeepalive:h}=await import(`./keepalive-BIRIvYdO.mjs`),g=h({resolveWsUrl:async()=>{let e=await c.getKeepaliveCwd();if(!e)return;let t=await u(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${d}`,logger:Fw.child(`keepalive`)}),_=e=>{Fw?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const zw=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],Bw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Vw(e){if(!e||e.length===0)return`unknown`;for(let t of zw)if(e.includes(t))return`npx-cache`;return Bw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function Hw(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 Uw(e){return e?/\bENOENT\b/i.test(e):!1}function Ww(e){switch(Vw(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 Gw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Uw(e)&&(r+=`\n\n${Ww(n)}`),r}function Kw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function qw(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=Vw(o),c=Hw(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 Jw(e){let t=e.readLock??(()=>_e(e.lockDir)),n=e.isAlive??P,r=e.sleep??(e=>nr(e)),i=e.spawn??Cn,a=e.readErrorLog??(e=>Pn(e)?Ln(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>In(e,`w`)),s=e.closeFd??Nn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=qw({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);Pn(e.lockDir)||Fn(e.lockDir,{recursive:!0});let f=kn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=xn();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:Uw(h)}),Error(Gw(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:Uw(h)}),Error(Gw(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 Yw(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??Jw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Fe(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=ge(i,o),s=he(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 Xw(e,t){return t===void 0?!Pn(jn(e,`.ok`)):!1}function Zw(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();if(Xw(r,t.port)){process.stderr.write(`[mcp] ${r} is not an Open Knowledge project (no .ok/); exiting. Run \`ok init\` to scaffold one.\n`),process.exitCode=1;return}let i=Re({startupCwd:r,startupConfig:n}),a=Kw(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=Yw({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 Rw({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 Qw(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-BNMytxTe.mjs`),r=e(),i=process.cwd(),a=ge(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function $w(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function eT(e,t,n=process.cwd()){let r=e.op??`sync`,i=_e(he(ge(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}`)}$w(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=ye({baseDir:n});if(r===`sync`||r===`pull`){$w(e.json,{type:`step`,step:`pull`});let t=await a.pull();$w(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&($w(e.json,{type:`step`,step:`push`}),await a.push(),$w(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1408
+ `}async function Lw(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 Rw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(Fw=Tm(),Fw.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Lw(n,Fw);Fw.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else Fw.info(`server discovery is lazy per effective cwd`);let o=new lm({name:me,version:pe},{instructions:Iw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Nw({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:Fw}),c=Pw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(vd,async()=>{s.invalidateRoots()});let u=async e=>{if(typeof n==`string`)return n.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await l();return(typeof n==`function`?await n(t):n)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},d=Qn(),f=process.env.AGENT_LABEL||void 0,p={current:{connectionId:d,label:f,displayName:f??`Agent`,colorSeed:f??d}};o.server.oninitialized=()=>{let e=o.server.getClientVersion();p.current={connectionId:d,clientInfo:e?{name:e.name,version:e.version}:void 0,label:f,displayName:f??e?.name??`Agent`,colorSeed:f??e?.name??d},Fw?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},Aw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:Fw});let m=new Sm;await o.connect(m),Fw.info(`MCP server running on stdio`);let{startKeepalive:h}=await import(`./keepalive-BIRIvYdO.mjs`),g=h({resolveWsUrl:async()=>{let e=await c.getKeepaliveCwd();if(!e)return;let t=await u(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},connectionId:`agent-${d}`,logger:Fw.child(`keepalive`)}),_=e=>{Fw?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const zw=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],Bw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Vw(e){if(!e||e.length===0)return`unknown`;for(let t of zw)if(e.includes(t))return`npx-cache`;return Bw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function Hw(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 Uw(e){return e?/\bENOENT\b/i.test(e):!1}function Ww(e){switch(Vw(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 Gw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Uw(e)&&(r+=`\n\n${Ww(n)}`),r}function Kw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function qw(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=Vw(o),c=Hw(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 Jw(e){let t=e.readLock??(()=>_e(e.lockDir)),n=e.isAlive??P,r=e.sleep??(e=>nr(e)),i=e.spawn??Cn,a=e.readErrorLog??(e=>Pn(e)?Ln(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>In(e,`w`)),s=e.closeFd??Nn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=qw({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);Pn(e.lockDir)||Fn(e.lockDir,{recursive:!0});let f=kn(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=xn();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:Uw(h)}),Error(Gw(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:Uw(h)}),Error(Gw(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 Yw(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??Jw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Fe(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=ge(i,o),s=he(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 Xw(e,t){return t===void 0?!Pn(jn(e,`.ok`)):!1}function Zw(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();if(Xw(r,t.port)){process.stderr.write(`[mcp] ${r} is not an Open Knowledge project (no .ok/); exiting. Run \`ok init\` to scaffold one.\n`),process.exitCode=1;return}let i=Re({startupCwd:r,startupConfig:n}),a=Kw(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=Yw({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 Rw({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 Qw(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-DUYE2XxR.mjs`),r=e(),i=process.cwd(),a=ge(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function $w(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function eT(e,t,n=process.cwd()){let r=e.op??`sync`,i=_e(he(ge(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}`)}$w(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let a=ye({baseDir:n});if(r===`sync`||r===`pull`){$w(e.json,{type:`step`,step:`pull`});let t=await a.pull();$w(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&($w(e.json,{type:`step`,step:`push`}),await a.push(),$w(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1409
1409
  `)),$w(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function tT(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 eT({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 nT(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await eT({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 rT(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await eT({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 iT(e={}){let t=jn(e.cwd??process.cwd()),n;try{n=await ke({projectDir:t,rootDir:e.root})}catch(e){return e instanceof xe?{status:`prerequisite-missing`,message:`${Ue(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Ue(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${He(`Your knowledge base is already seeded.`)}\n${Ve(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${Ge(`Plan (dry-run — no changes made):`)}\n\n${aT(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await oT(`${Ge(`Plan:`)}\n\n${aT(n,t)}\n\n${Ge(`Apply?`)} ${Ve(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Ve(`Cancelled.`),plan:n,exitCode:0};let r=await be(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Ue(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${We(`Applied`)} ${r.applied} entries, ${We(String(r.errors.length))} error(s):`,...e].join(`
1410
1410
  `),plan:n,exitCode:1}}return{status:`applied`,message:`${He(`✓ Seeded knowledge base`)} ${Ve(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function aT(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(Ge(`Folders to create:`));for(let e of r)n.push(` ${He(`+`)} ${Be(An(t,jn(t,e.path))||e.path)}${Ve(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(Ge(`Files to create:`));for(let e of i)n.push(` ${He(`+`)} ${Be(An(t,jn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push(Ge(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${He(`+`)} ${Be(t.folderMatch)} ${Ve(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Ve(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Ve(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(We(`Warnings:`));for(let t of e.warnings)n.push(` ${We(`!`)} ${t}`)}return n.join(`
1411
- `)}async function oT(e,t){let n=or({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 sT(){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 iT({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 cT(e,t){return{server:lT(`server`,e),ui:lT(`ui`,t)}}function lT(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 uT(e){return`${dT(e.server)}\n${dT(e.ui)}`}function dT(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 fT(e){let t=e.inspect??(t=>Co(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=cT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(uT(r)),r}function pT(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=>{fT({lockDir:he(ge(e(),process.cwd())),json:t.json===!0})})}function mT(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 hT(e){let t=e.inspect??(t=>Co(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=mT(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 gT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{hT({lockDir:he(ge(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const _T=1e4,vT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function yT(e){let t=e.upstreamTimeoutMs??_T,n=rr((n,r)=>{xT(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 bT(e,t,n){xT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??_T)}function xT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of vT)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=ir({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of vT)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 ST(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function CT(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:a,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-B-uWyCj3.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-BQoQfIvS.mjs`),m=f(e.config,e.cwd),h=p(m);a(h,{port:0,worktreeRoot:e.cwd});let g=import.meta.dirname??new URL(`.`,import.meta.url).pathname,_=[r(g,`public`),r(g,`../../app/dist`),r(g,`../../../app/dist`)].find(e=>t(e)),v=_?d(_,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,y=t(m)?o({contentFilter:s({projectDir:e.cwd,contentDir:m}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:M,assetExtensions:ie,blocklistExtensions:A}):null,b=e.port,x=null,S=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){x?.();let n=c(h),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:b});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/`)){x?.();let r=c(h);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}bT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):wT(t)});return}if(v){v(e,t);return}wT(t)},C=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],w=[],ee=e.port;try{for(let e of C){let t=n(S);w.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ee,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ee=e.port),n()})})}}catch(e){await Promise.all(w.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let T=ee;b=T,u(h,T);let E=e.scheduler??i,te=e.safetyNetMs??432e5,ne=null,D=!1,re=!1,O=()=>{D||(D=!0,ne!==null&&(E.clearTimeout(ne),ne=null))},k=()=>{if(O(),!re){re=!0;try{l(h)}catch{}}},ae=()=>{D||te<=0||(ne!==null&&(E.clearTimeout(ne),ne=null),ne=E.setTimeout(()=>{ne=null,console.warn(`[ui] safety-net (${te}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of w)try{e.close()}catch{}k()},te))},oe=()=>{D||te<=0||ae()};return x=oe,ae(),{httpServers:w,port:T,release:k,detachSafetyNet:O,nudgeSafetyNet:oe}}function wT(e){e.writeHead(404),e.end(`Not found`)}function TT(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 ET(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-B-uWyCj3.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 yT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function DT(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-CswooXAS.mjs`),{UiLockCollisionError:r}=await import(`./dist-B-uWyCj3.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-BQoQfIvS.mjs`),o=e(),s=t.host,c;try{c=TT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await CT({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)}};ST(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 ET({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 OT=new r;let kT;OT.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(pe).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}=Ie(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.host!==void 0&&(r.server.host=i.host),process.env.HOST&&(r.server.host=process.env.HOST),kT=r});const AT=bn(()=>kT);OT.addCommand(AT,{isDefault:!0});const jT=Zw(()=>kT);OT.addCommand(jT),OT.addCommand(ze()),OT.addCommand(sT()),OT.addCommand(Xo());const MT=Qw(()=>kT);OT.addCommand(MT);const NT=DT(()=>kT);OT.addCommand(NT),OT.addCommand(gT(()=>kT)),OT.addCommand(Eo(()=>kT)),OT.addCommand(pT(()=>kT)),OT.addCommand(Uo()),OT.addCommand(So(()=>kT)),OT.addCommand(Io(()=>kT)),OT.addCommand(tT(()=>kT)),OT.addCommand(rT(()=>kT)),OT.addCommand(nT(()=>kT)),await OT.parseAsync();export{};
1411
+ `)}async function oT(e,t){let n=or({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 sT(){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 iT({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 cT(e,t){return{server:lT(`server`,e),ui:lT(`ui`,t)}}function lT(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 uT(e){return`${dT(e.server)}\n${dT(e.ui)}`}function dT(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 fT(e){let t=e.inspect??(t=>Co(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=cT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(uT(r)),r}function pT(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=>{fT({lockDir:he(ge(e(),process.cwd())),json:t.json===!0})})}function mT(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 hT(e){let t=e.inspect??(t=>Co(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=mT(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 gT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{hT({lockDir:he(ge(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const _T=1e4,vT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function yT(e){let t=e.upstreamTimeoutMs??_T,n=rr((n,r)=>{xT(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 bT(e,t,n){xT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??_T)}function xT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of vT)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=ir({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of vT)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 ST(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function CT(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:a,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BVnVlgjQ.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-BIsyTDX6.mjs`),m=f(e.config,e.cwd),h=p(m);a(h,{port:0,worktreeRoot:e.cwd});let g=import.meta.dirname??new URL(`.`,import.meta.url).pathname,_=[r(g,`public`),r(g,`../../app/dist`),r(g,`../../../app/dist`)].find(e=>t(e)),v=_?d(_,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,y=t(m)?o({contentFilter:s({projectDir:e.cwd,contentDir:m}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:M,assetExtensions:ie,blocklistExtensions:A}):null,b=e.port,x=null,S=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){x?.();let n=c(h),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:b});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/`)){x?.();let r=c(h);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}bT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):wT(t)});return}if(v){v(e,t);return}wT(t)},C=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],w=[],ee=e.port;try{for(let e of C){let t=n(S);w.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ee,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ee=e.port),n()})})}}catch(e){await Promise.all(w.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let T=ee;b=T,u(h,T);let E=e.scheduler??i,te=e.safetyNetMs??432e5,ne=null,D=!1,re=!1,O=()=>{D||(D=!0,ne!==null&&(E.clearTimeout(ne),ne=null))},k=()=>{if(O(),!re){re=!0;try{l(h)}catch{}}},ae=()=>{D||te<=0||(ne!==null&&(E.clearTimeout(ne),ne=null),ne=E.setTimeout(()=>{ne=null,console.warn(`[ui] safety-net (${te}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of w)try{e.close()}catch{}k()},te))},oe=()=>{D||te<=0||ae()};return x=oe,ae(),{httpServers:w,port:T,release:k,detachSafetyNet:O,nudgeSafetyNet:oe}}function wT(e){e.writeHead(404),e.end(`Not found`)}function TT(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 ET(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BVnVlgjQ.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 yT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function DT(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-CswooXAS.mjs`),{UiLockCollisionError:r}=await import(`./dist-BVnVlgjQ.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-BIsyTDX6.mjs`),o=e(),s=t.host,c;try{c=TT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await CT({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)}};ST(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 ET({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 OT=new r;let kT;OT.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(pe).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}=Ie(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.host!==void 0&&(r.server.host=i.host),process.env.HOST&&(r.server.host=process.env.HOST),kT=r});const AT=bn(()=>kT);OT.addCommand(AT,{isDefault:!0});const jT=Zw(()=>kT);OT.addCommand(jT),OT.addCommand(ze()),OT.addCommand(sT()),OT.addCommand(Xo());const MT=Qw(()=>kT);OT.addCommand(MT);const NT=DT(()=>kT);OT.addCommand(NT),OT.addCommand(gT(()=>kT)),OT.addCommand(Eo(()=>kT)),OT.addCommand(pT(()=>kT)),OT.addCommand(Uo()),OT.addCommand(So(()=>kT)),OT.addCommand(Io(()=>kT)),OT.addCommand(tT(()=>kT)),OT.addCommand(rT(()=>kT)),OT.addCommand(nT(()=>kT)),await OT.parseAsync();export{};
1412
1412
  //# sourceMappingURL=cli.mjs.map