@inkeep/open-knowledge 0.0.0-dev-20260430220436 → 0.0.0-dev-20260501033542

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 (59) hide show
  1. package/dist/THIRD_PARTY_NOTICES.md +44 -0
  2. package/dist/cli.mjs +10 -10
  3. package/dist/constants-C4c9G6bx.mjs +2 -0
  4. package/dist/{dist-7GgIDlwG.mjs → dist-BKxD-v-w.mjs} +12 -12
  5. package/dist/{dist-BEzp6mq0.mjs → dist-Bk22-nn7.mjs} +12 -12
  6. package/dist/{dist-BnZHVzE4.mjs → dist-BuWOuGGO.mjs} +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/dist/{init-CrWt5I5H.mjs → init-B110s1wM.mjs} +2 -2
  9. package/dist/{init-Dame1GG3.mjs → init-BgvX0Sq8.mjs} +3 -3
  10. package/dist/init-CCv_Zp9V.mjs +1 -0
  11. package/dist/init-DLXU6VrK.mjs +1 -0
  12. package/dist/loader-CXRhSZPN.mjs +1 -0
  13. package/dist/{loader-m7I7pd_0.mjs → loader-DmdfaHaq.mjs} +2 -2
  14. package/dist/paths-RkbKkMl_.mjs +2 -0
  15. package/dist/paths-r4eAorwU.mjs +1 -0
  16. package/dist/preview-CnsTM1D_.mjs +1 -0
  17. package/dist/{preview-Dd3l-KWB.mjs → preview-jvjjfAtM.mjs} +2 -2
  18. package/dist/public/assets/{ActivityModeContent-DWssAqaG.js → ActivityModeContent-Dh5iGi22.js} +1 -1
  19. package/dist/public/assets/DocumentContext-BtLDstmc.js +34 -0
  20. package/dist/public/assets/{GraphPanel-aktIAtaE.js → GraphPanel-jbwIk-JX.js} +2 -2
  21. package/dist/public/assets/{McpConsentDialogBody-BKRS2Qm0.js → McpConsentDialogBody-Dx67JoKA.js} +1 -1
  22. package/dist/public/assets/SettingsPane-C93_FdcE.js +5 -0
  23. package/dist/public/assets/SourceEditor-Bo2dIeu9.js +2 -0
  24. package/dist/public/assets/{agent-presence-XtMgnv3n.js → agent-presence-BxT9uQ-C.js} +1 -1
  25. package/dist/public/assets/{button-CXhPNzpp.js → button-Dyz7QGIk.js} +1 -1
  26. package/dist/public/assets/circle-check-C-DpX4dU.js +1 -0
  27. package/dist/public/assets/clipboard-B19FK6nN.js +5 -0
  28. package/dist/public/assets/{config-validation-events-5erczoJ8.js → config-validation-events-ClxIZ8iZ.js} +1 -1
  29. package/dist/public/assets/dialog-FUclf-NK.js +45 -0
  30. package/dist/public/assets/index-D3IFbquY.js +1848 -0
  31. package/dist/public/assets/index-sRsZ2bXw.css +1 -0
  32. package/dist/public/assets/{panel-DiSt1efw.js → panel-DT62BXGr.js} +1 -1
  33. package/dist/public/assets/{target-navigation-intent-rQkR_SWG.js → target-navigation-intent-CK4Ee17H.js} +1 -1
  34. package/dist/public/assets/{toggle-group-DUoJt_Lj.js → toggle-group-n36XMgMC.js} +137 -136
  35. package/dist/public/assets/tooltip-BM5o_T0o.js +1 -0
  36. package/dist/public/index.html +13 -13
  37. package/dist/{server-C3JdctFI.mjs → server-CYax-BjV.mjs} +2 -2
  38. package/dist/src-DKAFRzZc.mjs +1 -0
  39. package/dist/start-B8KGCnGd.mjs +1 -0
  40. package/dist/{start-Bz9pi8fW.mjs → start-M53xqMIa.mjs} +2 -2
  41. package/package.json +1 -1
  42. package/dist/constants-BcJMCJN9.mjs +0 -2
  43. package/dist/init-BANhgZmt.mjs +0 -1
  44. package/dist/init-CXCzna7i.mjs +0 -1
  45. package/dist/loader-CA834Giw.mjs +0 -1
  46. package/dist/paths-Bcq8_cdi.mjs +0 -1
  47. package/dist/paths-DOJDdHR7.mjs +0 -2
  48. package/dist/preview-CD7jAwMP.mjs +0 -1
  49. package/dist/public/assets/DocumentContext-GbmGcVzS.js +0 -34
  50. package/dist/public/assets/SettingsPane-HKf0Vtow.js +0 -5
  51. package/dist/public/assets/SourceEditor-D5eu9Dbl.js +0 -2
  52. package/dist/public/assets/circle-check-bKAq6pcI.js +0 -1
  53. package/dist/public/assets/clipboard-D2LwhWD3.js +0 -5
  54. package/dist/public/assets/dialog-CJazZw1E.js +0 -45
  55. package/dist/public/assets/index-C_wVGFTR.css +0 -1
  56. package/dist/public/assets/index-DWZjAcTk.js +0 -1844
  57. package/dist/public/assets/tooltip-CSwVg9kb.js +0 -1
  58. package/dist/src-C3CKMgF-.mjs +0 -1
  59. package/dist/start-B3XZX6TH.mjs +0 -1
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-wByiX8MO.mjs";import{$ as i,A as a,At as o,Ct as s,Ft as c,I as l,It as u,Lt as d,Mt as f,N as p,Nt as m,Ot as h,Pt as g,Q as _,Rt as v,St as y,Tt as b,_t as x,bt as S,ct as ee,dt as te,ft as ne,g as re,gt as C,ht as w,jt as ie,kt as ae,lt as T,mt as E,n as oe,ot as se,pt as ce,st as le,ut as ue,v as de,vt as fe,wt as pe,x as me,xt as D,y as he,yt as ge}from"./dist-BEzp6mq0.mjs";import{n as _e,r as ve,t as ye}from"./dist-bundle-BSdjl7Rj.mjs";import{i as be,r as xe}from"./constants-BcJMCJN9.mjs";import{n as Se,t as Ce}from"./paths-DOJDdHR7.mjs";import{l as we,o as Te,s as Ee}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as De}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as Oe,C as ke,Ct as Ae,Et as je,F as Me,an as Ne,in as Pe,nn as Fe,on as Ie,rn as Le}from"./dist-7GgIDlwG.mjs";import{a as Re,i as ze,n as Be,t as Ve}from"./server-C3JdctFI.mjs";import{t as He}from"./is-object-CEU0BgQ5.mjs";import{i as Ue,n as We,r as Ge,t as Ke}from"./loader-m7I7pd_0.mjs";import{r as qe}from"./init-Dame1GG3.mjs";import{i as Je,n as Ye,o as Xe,r as Ze,s as Qe,t as $e}from"./colors-BdAXRiXe.mjs";import{t as et}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as tt,c as nt,d as rt,f as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as gt,B as _t,C as vt,D as yt,E as bt,F as xt,H as St,I as Ct,L as wt,M as Tt,N as Et,O as Dt,P as Ot,S as kt,T as At,V as jt,_ as Mt,a as Nt,b as Pt,c as Ft,d as It,f as O,g as Lt,h as Rt,i as zt,j as Bt,k as Vt,l as Ht,m as Ut,n as Wt,o as Gt,p as Kt,r as qt,s as Jt,t as Yt,u as Xt,v as Zt,w as Qt,x as $t,y as en,z as tn}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as nn,c as rn,d as an,i as on,l as sn,n as cn,o as ln,r as un,s as k,t as dn,u as fn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as pn,r as mn,t as hn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as gn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as _n,t as vn}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as yn,t as bn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as xn,r as Sn,t as Cn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as wn,t as Tn}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as En}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as Dn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as On,s as kn}from"./start-Bz9pi8fW.mjs";import"./src-C3CKMgF-.mjs";import{execFileSync as An,spawn as jn}from"node:child_process";import*as Mn from"node:path";import Nn,{basename as Pn,dirname as Fn,isAbsolute as In,join as Ln,relative as Rn,resolve as zn}from"node:path";import*as A from"node:fs";import{appendFileSync as Bn,closeSync as Vn,existsSync as Hn,mkdirSync as Un,openSync as Wn,readFileSync as Gn,readdirSync as Kn,realpathSync as qn,statSync as Jn,unlinkSync as Yn,writeFileSync as Xn}from"node:fs";import Zn from"node:process";import{homedir as Qn,hostname as $n,platform as er}from"node:os";import{AsyncLocalStorage as tr,AsyncResource as nr}from"node:async_hooks";import{stripVTControlCharacters as rr,styleText as ir}from"node:util";import*as ar from"node:readline";import{fileURLToPath as or}from"node:url";import{randomUUID as sr}from"node:crypto";import{mkdir as cr,readFile as lr,readdir as ur,stat as dr}from"node:fs/promises";import{setTimeout as fr}from"node:timers/promises";import{createServer as pr,request as mr}from"node:http";import{lookup as hr}from"node:dns";import{createInterface as gr}from"node:readline/promises";var _r=v();const vr=`open-knowledge`;var yr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(vr,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(vr,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(vr,e).deletePassword()}catch{}}},br=class{backend=`file`;authFile;constructor(e){this.authFile=e??Ln(Qn(),`.open-knowledge`,`auth.yml`)}read(){if(!Hn(this.authFile))return{};try{return(0,_r.parse)(Gn(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=Fn(this.authFile);Hn(t)||Un(t,{recursive:!0,mode:448}),Xn(this.authFile,(0,_r.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 xr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(vr,`__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{$ as i,A as a,At as o,Ct 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 _,Rt as v,St as y,Tt as b,_t as x,bt as S,ct as ee,dt as te,ft as ne,g as re,gt as C,ht as w,jt as ie,kt as ae,lt as T,mt as E,n as oe,ot as se,pt as ce,st as le,ut as ue,v as de,vt as fe,wt as pe,x as me,xt as D,y as he,yt as ge}from"./dist-Bk22-nn7.mjs";import{n as _e,r as ve,t as ye}from"./dist-bundle-BSdjl7Rj.mjs";import{i as be,r as xe}from"./constants-C4c9G6bx.mjs";import{n as Se,t as Ce}from"./paths-RkbKkMl_.mjs";import{l as we,o as Te,s as Ee}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{i as De}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{A as Oe,C as ke,Ct as Ae,Et as je,F as Me,an as Ne,in as Pe,nn as Fe,on as Ie,rn as Le}from"./dist-BKxD-v-w.mjs";import{a as Re,i as ze,n as Be,t as Ve}from"./server-CYax-BjV.mjs";import{t as He}from"./is-object-CEU0BgQ5.mjs";import{i as Ue,n as We,r as Ge,t as Ke}from"./loader-DmdfaHaq.mjs";import{r as qe}from"./init-BgvX0Sq8.mjs";import{i as Je,n as Ye,o as Xe,r as Ze,s as Qe,t as $e}from"./colors-BdAXRiXe.mjs";import{t as et}from"./chunk-YNYSPYQ5-CzQORSqg.mjs";import{a as tt,c as nt,d as rt,f as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht}from"./chunk-GFQRA5P5-BHvTMkvm.mjs";import{A as gt,B as _t,C as vt,D as yt,E as bt,F as xt,H as St,I as Ct,L as wt,M as Tt,N as Et,O as Dt,P as Ot,S as kt,T as At,V as jt,_ as Mt,a as Nt,b as Pt,c as Ft,d as It,f as O,g as Lt,h as Rt,i as zt,j as Bt,k as Vt,l as Ht,m as Ut,n as Wt,o as Gt,p as Kt,r as qt,s as Jt,t as Yt,u as Xt,v as Zt,w as Qt,x as $t,y as en,z as tn}from"./chunk-FEIOJCZD-BWy7d-Eh.mjs";import{a as nn,c as rn,d as an,i as on,l as sn,n as cn,o as ln,r as un,s as k,t as dn,u as fn}from"./chunk-XHM67O4N-CAZ8iQv5.mjs";import{n as pn,r as mn,t as hn}from"./chunk-R6VWJ2ZL-Bz4BqhV-.mjs";import{r as gn}from"./chunk-CWQS3NFK-7eq8cfme.mjs";import"./chunk-DXB73IDG-B5N_TdmL.mjs";import{n as _n,t as vn}from"./chunk-5QMZ5MUS-O2hLndhl.mjs";import{n as yn,t as bn}from"./chunk-A5O5YHGN-Bb__rfH8.mjs";import{n as xn,r as Sn,t as Cn}from"./chunk-OJDRYQWQ-D39lhrQA.mjs";import{r as wn,t as Tn}from"./chunk-24IMIIXA-B3GEYoJz.mjs";import{n as En}from"./chunk-3THT3N7L-DTzOHNvT.mjs";import{t as Dn}from"./chunk-44UOCSGV-D5MNKiyC.mjs";import{o as On,s as kn}from"./start-M53xqMIa.mjs";import"./src-DKAFRzZc.mjs";import{execFileSync as An,spawn as jn}from"node:child_process";import*as Mn from"node:path";import Nn,{basename as Pn,dirname as Fn,isAbsolute as In,join as Ln,relative as Rn,resolve as zn}from"node:path";import*as A from"node:fs";import{appendFileSync as Bn,closeSync as Vn,existsSync as Hn,mkdirSync as Un,openSync as Wn,readFileSync as Gn,readdirSync as Kn,realpathSync as qn,statSync as Jn,unlinkSync as Yn,writeFileSync as Xn}from"node:fs";import Zn from"node:process";import{homedir as Qn,hostname as $n,platform as er}from"node:os";import{AsyncLocalStorage as tr,AsyncResource as nr}from"node:async_hooks";import{stripVTControlCharacters as rr,styleText as ir}from"node:util";import*as ar from"node:readline";import{fileURLToPath as or}from"node:url";import{randomUUID as sr}from"node:crypto";import{mkdir as cr,readFile as lr,readdir as ur,stat as dr}from"node:fs/promises";import{setTimeout as fr}from"node:timers/promises";import{createServer as pr,request as mr}from"node:http";import{lookup as hr}from"node:dns";import{createInterface as gr}from"node:readline/promises";var _r=v();const vr=`open-knowledge`;var yr=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(vr,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(vr,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(vr,e).deletePassword()}catch{}}},br=class{backend=`file`;authFile;constructor(e){this.authFile=e??Ln(Qn(),`.open-knowledge`,`auth.yml`)}read(){if(!Hn(this.authFile))return{};try{return(0,_r.parse)(Gn(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=Fn(this.authFile);Hn(t)||Un(t,{recursive:!0,mode:448}),Xn(this.authFile,(0,_r.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 xr(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(vr,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new yr}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new br(e)}}async function Sr(e,t,n){let r=Cr(await wr(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 Cr(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 wr(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 Tr(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 Sr(process.stdin,process.stdout,t);process.exit(n)}),t}function Er(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Dr(e,t,n){let r={baseUrl:Er(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new _e(`${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 Or(e){let t=e.request||ye,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Dr(t,`POST /login/device/code`,n)}async function kr(e){let t=await Dr(e.request||ye,`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=Ar(e,t.data.expires_in),n.refreshTokenExpiresAt=Ar(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ar(e,t){return new Date(e+t*1e3).toISOString()}async function jr(e,t){let n=Mr(e,t.auth);if(n)return n;let{data:r}=await Or({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Pr(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Mr(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 Nr(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Pr(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await kr({...i,clientType:`oauth-app`}):await kr({...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 Nr(r.interval),Pr(e,t,n,r);if(a===`slow_down`)return await Nr(r.interval+7),Pr(e,t,n,r);throw i}}async function Fr(e,t){return jr(e,{auth:t})}async function Ir(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 jr(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Lr=`0.0.0-development`;function Rr(e){let t=e.request||ye.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Lr} ${ve()}`}}),{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(Fr.bind(null,i),{hook:Ir.bind(null,i)})}async function zr(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=Rr({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 Br(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const Vr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Hr(e){let t=e.toLowerCase().replace(/:\d+$/,``);Vr.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 Ur(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Wr(e,t,n,r=zr){let i=Br(n),{host:a,json:o}=e;Hr(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?Ur(!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?Ur(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Gr(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 Wr(n,await t(),e())})}const Kr=e=>e.name===`enter`||e.name===`return`;var qr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Jr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Yr=class extends Error{name=`ExitPromptError`},Xr=class extends Error{name=`HookError`},Zr=class extends Error{name=`ValidationError`};const Qr=new tr;function $r(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ei(e,t){let n=$r(e);return Qr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function ti(){let e=Qr.getStore();if(!e)throw new Xr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function ni(){return ti().rl}function ri(e){return nr.bind((...t)=>{let n=ti(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function ii(e){let t=ti(),{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 ai(){ti().handleChange()}const oi={queue(e){let t=ti(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(ni());if(r!=null&&typeof r!=`function`)throw new Zr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=ti();ri(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=ti();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function si(e){return typeof e==`function`}function ci(e){return ii(t=>{let n=nr.bind(function(e){t.get()!==e&&(t.set(e),ai())});if(t.initialized)return[t.get(),n];let r=si(e)?e():e;return t.set(r),[r,n]})}function li(e,t){ii(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&oi.queue(e),n.set(t)})}function ui(){return Zn.platform.startsWith(`win`)?!!Zn.env.CI||!!Zn.env.WT_SESSION||!!Zn.env.TERMINUS_SUBLIME||Zn.env.ConEmuTask===`{cmd::Cmder}`||Zn.env.TERM_PROGRAM===`Terminus-Sublime`||Zn.env.TERM_PROGRAM===`vscode`||Zn.env.TERM===`xterm-256color`||Zn.env.TERM===`alacritty`||Zn.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:Zn.env.TERM!==`linux`}const di={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:`╱`},fi={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:`⅒`},pi={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`},mi={...di,...fi},hi={...di,...pi},gi=ui()?mi:hi;Object.entries(fi);const _i={prefix:{idle:ir(`blue`,`?`),done:ir(`green`,gi.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>ir(`yellow`,e))},style:{answer:e=>ir(`cyan`,e),message:e=>ir(`bold`,e),error:e=>ir(`red`,`> ${e}`),defaultAnswer:e=>ir(`dim`,`(${e})`),help:e=>ir(`dim`,e),highlight:e=>ir(`cyan`,e),key:e=>ir(`cyan`,ir(`bold`,`<${e}>`))}};function vi(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 yi(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=vi(n)&&vi(r)?yi(n,r):r}return t}function bi(...e){return yi(_i,...e.filter(e=>e!=null))}function xi({status:e=`idle`,theme:t}){let[n,r]=ci(!1),[i,a]=ci(0),{prefix:o,spinner:s}=bi(t);return li(()=>{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 Si(e){return ci({current:e})[0]}function Ci(e){let t=Si(e);t.current=e,li(e=>{let n=!1,r=ri((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var wi=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 Ti=(()=>{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}})(),Ei=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Di=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,Oi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ki=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ai=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ji=/\t{1,1000}/y,Mi=/[\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,Ni=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Pi=/\p{M}+/gu,Fi={limit:1/0,ellipsis:``},Ii=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ii(i,Fi,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ni,l],[Oi,0],[ki,o],[ji,s],[Mi,c],[Ai,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(Pi,``)){let t=e.codePointAt(0)||0;if(S=Ei(t)?2:Di(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===Ai?Ti(e.slice(p,n.lastIndex)):n===Mi?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}},Li={limit:1/0,ellipsis:``,ellipsisWidth:0},Ri=(e,t={})=>Ii(e,Li,t).width,zi=`]8;;`,Bi=RegExp(`(?:\\[(?<code>\\d+)m|\\${zi}(?<uri>.*))`,`y`),Vi=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},Hi=e=>`[${e}m`,Ui=e=>`${zi}${e}`,Wi=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:Ri(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=Ri(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(zi,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())},Gi=e=>{let t=e.split(` `),n=t.length;for(;n&&!Ri(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ki=(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=Ri(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=Ri(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(``),Wi(s,r,t),c=Ri(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Wi(s,r,t),c=Ri(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Wi(s,r,t),c=Ri(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Gi(e)));let l=s.join(`
@@ -21,13 +21,13 @@ 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 To(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 wo(t,await e())})}async function Eo(e,t){let{host:n,json:r}=e;Hr(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Co({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Do(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 Eo(t,await e())})}async function Oo(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function ko(e){return new r(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Oo(t,await e())})}async function Ao(e,t){let{host:n,json:r}=e;Hr(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Co({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
22
22
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function jo(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 Ao(t,await e())})}function Mo(e){let t=new r(`auth`);t.description(`GitHub authentication management`);let n=()=>xr(),i=e??(()=>({}));return t.addCommand(Gr(i,n)),t.addCommand(jo(n)),t.addCommand(Do(n)),t.addCommand(ko(n)),t.addCommand(To(n)),t.addCommand(Tr(n)),t}function No(e,t,n={}){let r=Ee(e,t);if(!Hn(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(Gn(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??$n();return a.hostname===o?(n.isAlive??Te)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Po(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 Fo(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.unlink??(e=>Yn(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Po(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 Io(e){return new r(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{Fo({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function Lo(){try{let e=An(`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 Ro(e,t,n={},r=Lo){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 zo(e){return e.replace(/:\d+$/,``)}function Bo(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:zo(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:zo(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:zo(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 Vo=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Ho(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 Vo)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function Uo(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Wo(e,t,n,r=process.cwd()){let i=Bo(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?zn(r,t.dir):zn(r,i.name);if(Hn(a)&&Kn(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await xr(),s=await Ro(i.hostname,o,{}),c=De({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=Ho(e);n&&n.pct!==l&&(l=n.pct,Uo(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-BANhgZmt.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?Uo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Go(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Go(e){let t=Ln(e,`.git`,`info`,`exclude`);if(!Hn(t))return`no-exclude`;let n=Gn(t,`utf-8`),r=new Set([i,`${i}/`,`/${i}`,`/${i}/`]);return n.split(`
24
+ `);try{let{runInit:e}=await import(`./init-CCv_Zp9V.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?Uo(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Go(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?Uo(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Go(e){let t=Ln(e,`.git`,`info`,`exclude`);if(!Hn(t))return`no-exclude`;let n=Gn(t,`utf-8`),r=new Set([i,`${i}/`,`/${i}`,`/${i}/`]);return n.split(`
25
25
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(Xn(t,`${n}${n.length===0||n.endsWith(`
26
26
  `)?``:`
27
- `}${i}/\n`,`utf-8`),`appended`)}function Ko(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 Wo(t,{json:r.json,dir:n},i);if(r.json)Uo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-B3XZX6TH.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?Uo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const qo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`]];function Jo(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Yo(e){let t=(0,_r.parseDocument)(Gn(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 qo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zo(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=Xo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Qo(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??Re,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:ze(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:ze(`user`,a,e.homedirOverride)});let c=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Hn(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Yo(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:Zo(qo.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:l(s.error)}),u=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=c.some(e=>e.error!==void 0),f=c.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 c)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:c,ok:u}}function $o(){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(()=>{Jo({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port) 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 Qo({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}function es(e=Qn()){return Ln(e,`Downloads`,`openknowledge.skill`)}function ts(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ns(e={}){let t=zn(e.out??es()),n=e.platformName??er(),r=e.spawnFn??jn;try{await cr(Fn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await Me({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
27
+ `}${i}/\n`,`utf-8`),`appended`)}function Ko(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 Wo(t,{json:r.json,dir:n},i);if(r.json)Uo(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-B8KGCnGd.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?Uo(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const qo=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`]];function Jo(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??We;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Yo(e){let t=(0,_r.parseDocument)(Gn(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 qo)t.hasIn(e)&&n.push(e.join(`.`));return n}function Xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zo(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=Xo(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Qo(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??Re,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:ze(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:ze(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of s){if(!Hn(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Yo(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:Zo(qo.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 $o(){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(()=>{Jo({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port) 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 Qo({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}function es(e=Qn()){return Ln(e,`Downloads`,`openknowledge.skill`)}function ts(e,t,n){try{return t===`darwin`?(n(`open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired. Use --no-open and open the file manually.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ns(e={}){let t=zn(e.out??es()),n=e.platformName??er(),r=e.spawnFn??jn;try{await cr(Fn(t),{recursive:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} could not create output directory: ${e instanceof Error?e.message:String(e)}`,exitCode:1}}let i;try{i=await Me({outputPath:t,skipVersionCheck:!0})}catch(e){return{status:`failed`,message:`${Ze(`Error:`)} build failed — ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(e.noOpen)return{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}…`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
28
28
  `),exitCode:0};let a=ts(i.outputPath,n,r);return a.ok?{status:`installed`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Ye(` ${i.size} bytes • sha256 ${i.sha256.slice(0,12)}… • CLI v${i.cliVersion}`),Je(` Claude Desktop App opened. Now upload the file manually:`),` 1. ${$e(`Customize`)} (sidebar) → ${$e(`Skills`)}`,` 2. Click the ${$e(`+`)} button`,` 3. Click ${$e(`Create skill`)}`,` 4. Click ${$e(`Upload skill`)}`,` 5. Pick ${$e(`openknowledge.skill`)} from Downloads`,Ye(` If Claude Desktop didn't open, open it and start at step 1. The file is at ${i.outputPath}`)].join(`
29
29
  `),exitCode:0}:{status:`built`,outputPath:i.outputPath,size:i.size,sha256:i.sha256,cliVersion:i.cliVersion,skillVersion:i.skillVersion,message:[Xe(`Built ${i.outputPath}`),Qe(` Handoff failed: ${a.message}`),Je(` Open the Claude Desktop App, then: ${$e(`Customize → Skills → + → Create skill → Upload skill`)} → pick the file.`)].join(`
30
- `),exitCode:0}}function rs(){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 ns({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var j;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(j||={});var is;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(is||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),as=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=j.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var os=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};os.create=e=>new os(e);const ss=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let cs=ss;function ls(){return cs}const us=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function P(e,t){let n=ls(),r=us({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ss?void 0:ss].filter(e=>!!e)});e.common.issues.push(r)}var ds=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return F;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return F;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const F=Object.freeze({status:`aborted`}),fs=e=>({status:`dirty`,value:e}),ps=e=>({status:`valid`,value:e}),ms=e=>e.status===`aborted`,hs=e=>e.status===`dirty`,gs=e=>e.status===`valid`,_s=e=>typeof Promise<`u`&&e instanceof Promise;var I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var vs=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 ys=(e,t)=>{if(gs(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 os(e.common.issues),this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var R=class{get description(){return this._def.description}_getType(e){return as(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ds,ctx:{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(_s(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:as(e)};return ys(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:as(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return gs(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=>gs(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:as(e)},r=this._parse({data:e,path:n.path,parent:n});return ys(n,await(_s(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new xc({schema:this,typeName:z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return Sc.create(this,this._def)}nullable(){return Cc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nc.create(this)}promise(){return bc.create(this,this._def)}or(e){return ac.create([this,e],this._def)}and(e){return lc.create(this,e,this._def)}transform(e){return new xc({...L(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new wc({...L(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new Dc({typeName:z.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Tc({...L(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Oc.create(this,e)}readonly(){return kc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bs=/^c[^\s-]{8,}$/i,xs=/^[0-9a-z]+$/,Ss=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cs=/^[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,ws=/^[a-z0-9_-]{21}$/i,Ts=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Es=/^[-+]?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)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Os;const ks=/^(?:(?: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])$/,As=/^(?:(?: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])$/,js=/^(([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]))$/,Ms=/^(([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])$/,Ns=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ps=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fs=`((\\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])))`,Is=RegExp(`^${Fs}$`);function Ls(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 Rs(e){return RegExp(`^${Ls(e)}$`)}function zs(e){let t=`${Fs}T${Ls(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Bs(e,t){return!!((t===`v4`||!t)&&ks.test(e)||(t===`v6`||!t)&&js.test(e))}function Vs(e,t){if(!Ts.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 Hs(e,t){return!!((t===`v4`||!t)&&As.test(e)||(t===`v6`||!t)&&Ms.test(e))}var Us=class e extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new ds,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Os||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Os.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Cs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ws.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)bs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)xs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ss.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?zs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Is.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Rs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Es.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Bs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Vs(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Hs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Ns.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ps.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Us.create=e=>new Us({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...L(e)});function Ws(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 Gs=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new ds;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ws(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&j.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Gs.create=e=>new Gs({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...L(e)});var Ks=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let t,n=new ds;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ks.create=e=>new Ks({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var qs=class extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return ps(e.data)}};qs.create=e=>new qs({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var Js=class e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new ds,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Js.create=e=>new Js({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...L(e)});var Ys=class extends R{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return ps(e.data)}};Ys.create=e=>new Ys({typeName:z.ZodSymbol,...L(e)});var Xs=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return ps(e.data)}};Xs.create=e=>new Xs({typeName:z.ZodUndefined,...L(e)});var Zs=class extends R{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return ps(e.data)}};Zs.create=e=>new Zs({typeName:z.ZodNull,...L(e)});var Qs=class extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return ps(e.data)}};Qs.create=e=>new Qs({typeName:z.ZodAny,...L(e)});var $s=class extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ps(e.data)}};$s.create=e=>new $s({typeName:z.ZodUnknown,...L(e)});var ec=class extends R{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};ec.create=e=>new ec({typeName:z.ZodNever,...L(e)});var tc=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return ps(e.data)}};tc.create=e=>new tc({typeName:z.ZodVoid,...L(e)});var nc=class e extends R{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new vs(t,e,t.path,n)))).then(e=>ds.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new vs(t,e,t.path,n)));return ds.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};nc.create=(e,t)=>new nc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...L(t)});function rc(e){if(e instanceof ic){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Sc.create(rc(r))}return new ic({...e._def,shape:()=>t})}else if(e instanceof nc)return new nc({...e._def,type:rc(e.element)});else if(e instanceof Sc)return Sc.create(rc(e.unwrap()));else if(e instanceof Cc)return Cc.create(rc(e.unwrap()));else if(e instanceof uc)return uc.create(e.items.map(e=>rc(e)));else return e}var ic=class e extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ec&&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 vs(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ec){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(P(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new vs(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=>ds.mergeObjectSync(t,e)):ds.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:I.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of j.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return rc(this)}partial(t){let n={};for(let e of j.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Sc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return _c(j.objectKeys(this.shape))}};ic.create=(e,t)=>new ic({shape:()=>e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.strictCreate=(e,t)=>new ic({shape:()=>e,unknownKeys:`strict`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.lazycreate=(e,t)=>new ic({shape:e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)});var ac=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new os(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new os(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};ac.create=(e,t)=>new ac({options:e,typeName:z.ZodUnion,...L(t)});const oc=e=>e instanceof hc?oc(e.schema):e instanceof xc?oc(e.innerType()):e instanceof gc?[e.value]:e instanceof vc?e.options:e instanceof yc?j.objectValues(e.enum):e instanceof wc?oc(e._def.innerType):e instanceof Xs?[void 0]:e instanceof Zs?[null]:e instanceof Sc?[void 0,...oc(e.unwrap())]:e instanceof Cc?[null,...oc(e.unwrap())]:e instanceof Dc||e instanceof kc?oc(e.unwrap()):e instanceof Tc?oc(e._def.innerType):[];var sc=class e extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=oc(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function cc(e,t){let n=as(e),r=as(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=cc(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=cc(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var lc=class extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ms(e)||ms(r))return F;let i=cc(e.value,r.value);return i.valid?((hs(e)||hs(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lc.create=(e,t,n)=>new lc({left:e,right:t,typeName:z.ZodIntersection,...L(n)});var uc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new vs(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ds.mergeArray(t,e)):ds.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};uc.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new uc({items:e,typeName:z.ZodTuple,rest:null,...L(t)})};var dc=class e extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new vs(n,e,n.path,e)),value:a._parse(new vs(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ds.mergeObjectAsync(t,r):ds.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof R?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...L(r)}):new e({keyType:Us.create(),valueType:t,typeName:z.ZodRecord,...L(n)})}},fc=class extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new vs(n,e,n.path,[a,`key`])),value:i._parse(new vs(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};fc.create=(e,t,n)=>new fc({valueType:t,keyType:e,typeName:z.ZodMap,...L(n)});var pc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(P(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return F;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new vs(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};pc.create=(e,t)=>new pc({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...L(t)});var mc=class e extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof bc){let e=this;return ps(async function(...t){let o=new os([]),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 ps(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new os([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new os([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:uc.create(t).rest($s.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||uc.create([]).rest($s.create()),returns:n||$s.create(),typeName:z.ZodFunction,...L(r)})}},hc=class extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};hc.create=(e,t)=>new hc({getter:e,typeName:z.ZodLazy,...L(t)});var gc=class extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};gc.create=(e,t)=>new gc({value:e,typeName:z.ZodLiteral,...L(t)});function _c(e,t){return new vc({values:e,typeName:z.ZodEnum,...L(t)})}var vc=class e extends R{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:j.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return ps(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})}};vc.create=_c;var yc=class extends R{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return P(n,{expected:j.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return ps(e.data)}get enum(){return this._def.values}};yc.create=(e,t)=>new yc({values:e,typeName:z.ZodNativeEnum,...L(t)});var bc=class extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):ps((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bc.create=(e,t)=>new bc({type:e,typeName:z.ZodPromise,...L(t)});var xc=class extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{P(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?F:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?F:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gs(e))return F;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>gs(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);j.assertNever(r)}};xc.create=(e,t,n)=>new xc({schema:e,typeName:z.ZodEffects,effect:t,...L(n)}),xc.createWithPreprocess=(e,t,n)=>new xc({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...L(n)});var Sc=class extends R{_parse(e){return this._getType(e)===M.undefined?ps(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:z.ZodOptional,...L(t)});var Cc=class extends R{_parse(e){return this._getType(e)===M.null?ps(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cc.create=(e,t)=>new Cc({innerType:e,typeName:z.ZodNullable,...L(t)});var wc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};wc.create=(e,t)=>new wc({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var Tc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _s(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tc.create=(e,t)=>new Tc({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var Ec=class extends R{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};Ec.create=e=>new Ec({typeName:z.ZodNaN,...L(e)});var Dc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Oc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),fs(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:z.ZodPipeline})}},kc=class extends R{_parse(e){let t=this._def.innerType._parse(e),n=e=>(gs(e)&&(e.value=Object.freeze(e.value)),e);return _s(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};kc.create=(e,t)=>new kc({innerType:e,typeName:z.ZodReadonly,...L(t)}),ic.lazycreate;var z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(z||={}),Us.create,Gs.create,Ec.create,Ks.create,qs.create,Js.create,Ys.create,Xs.create,Zs.create,Qs.create,$s.create,ec.create,tc.create,nc.create;const Ac=ic.create;ic.strictCreate,ac.create,sc.create,lc.create,uc.create,dc.create,fc.create,pc.create,mc.create,hc.create,gc.create,vc.create,yc.create,bc.create,xc.create,Sc.create,Cc.create,xc.createWithPreprocess,Oc.create;const jc=d(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ae.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>o(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>f(e,t,n),e.parseAsync=async(t,n)=>ie(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>m(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)=>g(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Mc=d(`ZodMiniObject`,(e,t)=>{h.init(e,t),jc.init(e,t),c(e,`shape`,()=>t.shape)});function Nc(e,t){return new Mc({type:`object`,shape:e??{},...u(t)})}function Pc(e){return!!e._zod}function Fc(e){let t=Object.values(e);if(t.length===0)return Nc({});let n=t.every(Pc),r=t.every(e=>!Pc(e));if(n)return Nc(e);if(r)return Ac(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Ic(e,t){return Pc(e)?f(e,t):e.safeParse(t)}async function Lc(e,t){return Pc(e)?await m(e,t):await e.safeParseAsync(t)}function Rc(e){if(!e)return;let t;if(t=Pc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function zc(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 Fc(e)}}if(Pc(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 Bc(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 Vc(e){return e.description}function Hc(e){if(Pc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Uc(e){if(Pc(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 Wc=`2025-11-25`,Gc=[Wc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Kc=`io.modelcontextprotocol/related-task`,qc=te(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Jc=y([D(),C().int()]),Yc=D();w({ttl:C().optional(),pollInterval:C().optional()});const Xc=x({ttl:C().optional()}),Zc=x({taskId:D()}),Qc=w({progressToken:Jc.optional(),[Kc]:Zc.optional()}),$c=x({_meta:Qc.optional()}),el=$c.extend({task:Xc.optional()}),tl=e=>el.safeParse(e).success,nl=x({method:D(),params:$c.loose().optional()}),rl=x({_meta:Qc.optional()}),il=x({method:D(),params:rl.loose().optional()}),al=w({_meta:Qc.optional()}),ol=y([D(),C().int()]),sl=x({jsonrpc:E(`2.0`),id:ol,...nl.shape}).strict(),cl=e=>sl.safeParse(e).success,ll=x({jsonrpc:E(`2.0`),...il.shape}).strict(),ul=e=>ll.safeParse(e).success,dl=x({jsonrpc:E(`2.0`),id:ol,result:al}).strict(),fl=e=>dl.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(B||={});const pl=x({jsonrpc:E(`2.0`),id:ol.optional(),error:x({code:C().int(),message:D(),data:s().optional()})}).strict(),ml=e=>pl.safeParse(e).success,hl=y([sl,ll,dl,pl]);y([dl,pl]);const gl=al.strict(),_l=rl.extend({requestId:ol.optional(),reason:D().optional()}),vl=il.extend({method:E(`notifications/cancelled`),params:_l}),yl=x({icons:T(x({src:D(),mimeType:D().optional(),sizes:T(D()).optional(),theme:le([`light`,`dark`]).optional()})).optional()}),bl=x({name:D(),title:D().optional()}),xl=bl.extend({...bl.shape,...yl.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),Sl=ge(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ce(x({form:ce(x({applyDefaults:ue().optional()}),S(D(),s())).optional(),url:qc.optional()}),S(D(),s()).optional())),Cl=w({list:qc.optional(),cancel:qc.optional(),requests:w({sampling:w({createMessage:qc.optional()}).optional(),elicitation:w({create:qc.optional()}).optional()}).optional()}),wl=w({list:qc.optional(),cancel:qc.optional(),requests:w({tools:w({call:qc.optional()}).optional()}).optional()}),Tl=x({experimental:S(D(),qc).optional(),sampling:x({context:qc.optional(),tools:qc.optional()}).optional(),elicitation:Sl.optional(),roots:x({listChanged:ue().optional()}).optional(),tasks:Cl.optional(),extensions:S(D(),qc).optional()}),El=$c.extend({protocolVersion:D(),capabilities:Tl,clientInfo:xl}),Dl=nl.extend({method:E(`initialize`),params:El}),Ol=x({experimental:S(D(),qc).optional(),logging:qc.optional(),completions:qc.optional(),prompts:x({listChanged:ue().optional()}).optional(),resources:x({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:x({listChanged:ue().optional()}).optional(),tasks:wl.optional(),extensions:S(D(),qc).optional()}),kl=al.extend({protocolVersion:D(),capabilities:Ol,serverInfo:xl,instructions:D().optional()}),Al=il.extend({method:E(`notifications/initialized`),params:rl.optional()}),jl=nl.extend({method:E(`ping`),params:$c.optional()}),Ml=x({progress:C(),total:fe(C()),message:fe(D())}),Nl=x({...rl.shape,...Ml.shape,progressToken:Jc}),Pl=il.extend({method:E(`notifications/progress`),params:Nl}),Fl=$c.extend({cursor:Yc.optional()}),Il=nl.extend({params:Fl.optional()}),Ll=al.extend({nextCursor:Yc.optional()}),Rl=le([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zl=x({taskId:D(),status:Rl,ttl:y([C(),ee()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:fe(C()),statusMessage:fe(D())}),Bl=al.extend({task:zl}),Vl=rl.merge(zl),Hl=il.extend({method:E(`notifications/tasks/status`),params:Vl}),Ul=nl.extend({method:E(`tasks/get`),params:$c.extend({taskId:D()})}),Wl=al.merge(zl),Gl=nl.extend({method:E(`tasks/result`),params:$c.extend({taskId:D()})});al.loose();const Kl=Il.extend({method:E(`tasks/list`)}),ql=Ll.extend({tasks:T(zl)}),Jl=nl.extend({method:E(`tasks/cancel`),params:$c.extend({taskId:D()})}),Yl=al.merge(zl),Xl=x({uri:D(),mimeType:fe(D()),_meta:S(D(),s()).optional()}),Zl=Xl.extend({text:D()}),Ql=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$l=Xl.extend({blob:Ql}),eu=le([`user`,`assistant`]),tu=x({audience:T(eu).optional(),priority:C().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),nu=x({...bl.shape,...yl.shape,uri:D(),description:fe(D()),mimeType:fe(D()),size:fe(C()),annotations:tu.optional(),_meta:fe(w({}))}),ru=x({...bl.shape,...yl.shape,uriTemplate:D(),description:fe(D()),mimeType:fe(D()),annotations:tu.optional(),_meta:fe(w({}))}),iu=Il.extend({method:E(`resources/list`)}),au=Ll.extend({resources:T(nu)}),ou=Il.extend({method:E(`resources/templates/list`)}),su=Ll.extend({resourceTemplates:T(ru)}),cu=$c.extend({uri:D()}),lu=cu,uu=nl.extend({method:E(`resources/read`),params:lu}),du=al.extend({contents:T(y([Zl,$l]))}),fu=il.extend({method:E(`notifications/resources/list_changed`),params:rl.optional()}),pu=cu,mu=nl.extend({method:E(`resources/subscribe`),params:pu}),hu=cu,gu=nl.extend({method:E(`resources/unsubscribe`),params:hu}),_u=rl.extend({uri:D()}),vu=il.extend({method:E(`notifications/resources/updated`),params:_u}),yu=x({name:D(),description:fe(D()),required:fe(ue())}),bu=x({...bl.shape,...yl.shape,description:fe(D()),arguments:fe(T(yu)),_meta:fe(w({}))}),xu=Il.extend({method:E(`prompts/list`)}),Su=Ll.extend({prompts:T(bu)}),Cu=$c.extend({name:D(),arguments:S(D(),D()).optional()}),wu=nl.extend({method:E(`prompts/get`),params:Cu}),Tu=x({type:E(`text`),text:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Eu=x({type:E(`image`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Du=x({type:E(`audio`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Ou=x({type:E(`tool_use`),name:D(),id:D(),input:S(D(),s()),_meta:S(D(),s()).optional()}),ku=x({type:E(`resource`),resource:y([Zl,$l]),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Au=y([Tu,Eu,Du,nu.extend({type:E(`resource_link`)}),ku]),ju=x({role:eu,content:Au}),Mu=al.extend({description:D().optional(),messages:T(ju)}),Nu=il.extend({method:E(`notifications/prompts/list_changed`),params:rl.optional()}),Pu=x({title:D().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),Fu=x({taskSupport:le([`required`,`optional`,`forbidden`]).optional()}),Iu=x({...bl.shape,...yl.shape,description:D().optional(),inputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()),outputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()).optional(),annotations:Pu.optional(),execution:Fu.optional(),_meta:S(D(),s()).optional()}),Lu=Il.extend({method:E(`tools/list`)}),Ru=Ll.extend({tools:T(Iu)}),zu=al.extend({content:T(Au).default([]),structuredContent:S(D(),s()).optional(),isError:ue().optional()});zu.or(al.extend({toolResult:s()}));const Bu=el.extend({name:D(),arguments:S(D(),s()).optional()}),Vu=nl.extend({method:E(`tools/call`),params:Bu}),Hu=il.extend({method:E(`notifications/tools/list_changed`),params:rl.optional()});x({autoRefresh:ue().default(!0),debounceMs:C().int().nonnegative().default(300)});const Uu=le([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wu=$c.extend({level:Uu}),Gu=nl.extend({method:E(`logging/setLevel`),params:Wu}),Ku=rl.extend({level:Uu,logger:D().optional(),data:s()}),qu=il.extend({method:E(`notifications/message`),params:Ku}),Ju=x({hints:T(x({name:D().optional()})).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Yu=x({mode:le([`auto`,`required`,`none`]).optional()}),Xu=x({type:E(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:T(Au).default([]),structuredContent:x({}).loose().optional(),isError:ue().optional(),_meta:S(D(),s()).optional()}),Zu=ne(`type`,[Tu,Eu,Du]),Qu=ne(`type`,[Tu,Eu,Du,Ou,Xu]),$u=x({role:eu,content:y([Qu,T(Qu)]),_meta:S(D(),s()).optional()}),ed=el.extend({messages:T($u),modelPreferences:Ju.optional(),systemPrompt:D().optional(),includeContext:le([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:T(D()).optional(),metadata:qc.optional(),tools:T(Iu).optional(),toolChoice:Yu.optional()}),td=nl.extend({method:E(`sampling/createMessage`),params:ed}),nd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:eu,content:Zu}),rd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:eu,content:y([Qu,T(Qu)])}),id=x({type:E(`boolean`),title:D().optional(),description:D().optional(),default:ue().optional()}),ad=x({type:E(`string`),title:D().optional(),description:D().optional(),minLength:C().optional(),maxLength:C().optional(),format:le([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),od=x({type:le([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),sd=x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),default:D().optional()}),cd=x({type:E(`string`),title:D().optional(),description:D().optional(),oneOf:T(x({const:D(),title:D()})),default:D().optional()}),ld=y([y([x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),enumNames:T(D()).optional(),default:D().optional()}),y([sd,cd]),y([x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({type:E(`string`),enum:T(D())}),default:T(D()).optional()}),x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({anyOf:T(x({const:D(),title:D()}))}),default:T(D()).optional()})])]),id,ad,od]),ud=y([el.extend({mode:E(`form`).optional(),message:D(),requestedSchema:x({type:E(`object`),properties:S(D(),ld),required:T(D()).optional()})}),el.extend({mode:E(`url`),message:D(),elicitationId:D(),url:D().url()})]),dd=nl.extend({method:E(`elicitation/create`),params:ud}),fd=rl.extend({elicitationId:D()}),pd=il.extend({method:E(`notifications/elicitation/complete`),params:fd}),md=al.extend({action:le([`accept`,`decline`,`cancel`]),content:ge(e=>e===null?void 0:e,S(D(),y([D(),C(),ue(),T(D())])).optional())}),hd=x({type:E(`ref/resource`),uri:D()}),gd=x({type:E(`ref/prompt`),name:D()}),_d=$c.extend({ref:y([gd,hd]),argument:x({name:D(),value:D()}),context:x({arguments:S(D(),D()).optional()}).optional()}),vd=nl.extend({method:E(`completion/complete`),params:_d});function yd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xd=al.extend({completion:w({values:T(D()).max(100),total:fe(C().int()),hasMore:fe(ue())})}),Sd=x({uri:D().startsWith(`file://`),name:D().optional(),_meta:S(D(),s()).optional()}),Cd=nl.extend({method:E(`roots/list`),params:$c.optional()}),wd=al.extend({roots:T(Sd)}),Td=il.extend({method:E(`notifications/roots/list_changed`),params:rl.optional()});y([jl,Dl,vd,Gu,wu,xu,iu,ou,uu,mu,gu,Vu,Lu,Ul,Gl,Kl,Jl]),y([vl,Pl,Al,Td,Hl]),y([gl,nd,rd,md,wd,Wl,ql,Bl]),y([jl,td,dd,Cd,Ul,Gl,Kl,Jl]),y([vl,Pl,qu,vu,fu,Hu,Nu,Hl,pd]),y([gl,kl,xd,Mu,Su,au,su,du,zu,Ru,Wl,ql,Bl]);var V=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===B.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ed(e.elicitations,n)}return new e(t,n,r)}},Ed=class extends V{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dd(e){return e===`completed`||e===`failed`||e===`cancelled`}const Od=Symbol(`Let zodToJsonSchema decide on which parser to use`),kd={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`},Ad=e=>typeof e==`string`?{...kd,name:e}:{...kd,...e},jd=e=>{let t=Ad(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 Md(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,Md(e,t,r,i)}const Nd=(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 Pd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Nd(t,e.currentPath):t.join(`/`)}}function Fd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=U(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Id(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function Ld(){return{type:`boolean`}}function Rd(e,t){return U(e.type._def,t)}const zd=(e,t)=>U(e.innerType._def,t);function Bd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Bd(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 Vd(e,t)}}const Vd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Hd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function Ud(e,t){return t.effectStrategy===`input`?U(e.schema._def,t):Pd(t)}function Wd(e){return{type:`string`,enum:Array.from(e.values)}}const Gd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Kd(e,t){let n=[U(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),U(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Gd(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 qd(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 Jd;const Yd={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:()=>(Jd===void 0&&(Jd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Jd),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 Xd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:ef(n,`email`,r.message,t);break;case`format:idn-email`:ef(n,`idn-email`,r.message,t);break;case`pattern:zod`:tf(n,Yd.email,r.message,t);break}break;case`url`:ef(n,`uri`,r.message,t);break;case`uuid`:ef(n,`uuid`,r.message,t);break;case`regex`:tf(n,r.regex,r.message,t);break;case`cuid`:tf(n,Yd.cuid,r.message,t);break;case`cuid2`:tf(n,Yd.cuid2,r.message,t);break;case`startsWith`:tf(n,RegExp(`^${Zd(r.value,t)}`),r.message,t);break;case`endsWith`:tf(n,RegExp(`${Zd(r.value,t)}$`),r.message,t);break;case`datetime`:ef(n,`date-time`,r.message,t);break;case`date`:ef(n,`date`,r.message,t);break;case`time`:ef(n,`time`,r.message,t);break;case`duration`:ef(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:tf(n,RegExp(Zd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&ef(n,`ipv4`,r.message,t),r.version!==`v4`&&ef(n,`ipv6`,r.message,t);break;case`base64url`:tf(n,Yd.base64url,r.message,t);break;case`jwt`:tf(n,Yd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&tf(n,Yd.ipv4Cidr,r.message,t),r.version!==`v4`&&tf(n,Yd.ipv6Cidr,r.message,t);break;case`emoji`:tf(n,Yd.emoji(),r.message,t);break;case`ulid`:tf(n,Yd.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:ef(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:tf(n,Yd.base64,r.message,t);break}break;case`nanoid`:tf(n,Yd.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Zd(e,t){return t.patternStrategy===`escape`?$d(e):e}const Qd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function $d(e){let t=``;for(let n=0;n<e.length;n++)Qd.has(e[n])||(t+=`\\`),t+=e[n];return t}function ef(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):H(e,`format`,t,n,r)}function tf(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:nf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,nf(t,r),n,r)}function nf(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
+ `),exitCode:0}}function rs(){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 ns({out:e.out,noOpen:!e.open});process.stdout.write(`${t.message}\n`),t.exitCode!==0&&process.exit(t.exitCode)})}var j;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(j||={});var is;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(is||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),as=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},N=j.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var os=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};os.create=e=>new os(e);const ss=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case N.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let cs=ss;function ls(){return cs}const us=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function P(e,t){let n=ls(),r=us({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ss?void 0:ss].filter(e=>!!e)});e.common.issues.push(r)}var ds=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return F;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return F;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const F=Object.freeze({status:`aborted`}),fs=e=>({status:`dirty`,value:e}),ps=e=>({status:`valid`,value:e}),ms=e=>e.status===`aborted`,hs=e=>e.status===`dirty`,gs=e=>e.status===`valid`,_s=e=>typeof Promise<`u`&&e instanceof Promise;var I;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(I||={});var vs=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 ys=(e,t)=>{if(gs(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 os(e.common.issues),this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var R=class{get description(){return this._def.description}_getType(e){return as(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ds,ctx:{common:e.parent.common,data:e.data,parsedType:as(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(_s(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:as(e)};return ys(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:as(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return gs(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=>gs(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:as(e)},r=this._parse({data:e,path:n.path,parent:n});return ys(n,await(_s(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:N.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new xc({schema:this,typeName:z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return Sc.create(this,this._def)}nullable(){return Cc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nc.create(this)}promise(){return bc.create(this,this._def)}or(e){return ac.create([this,e],this._def)}and(e){return lc.create(this,e,this._def)}transform(e){return new xc({...L(this._def),schema:this,typeName:z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new wc({...L(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new Dc({typeName:z.ZodBranded,type:this,...L(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Tc({...L(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Oc.create(this,e)}readonly(){return kc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bs=/^c[^\s-]{8,}$/i,xs=/^[0-9a-z]+$/,Ss=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cs=/^[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,ws=/^[a-z0-9_-]{21}$/i,Ts=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Es=/^[-+]?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)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Os;const ks=/^(?:(?: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])$/,As=/^(?:(?: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])$/,js=/^(([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]))$/,Ms=/^(([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])$/,Ns=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ps=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fs=`((\\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])))`,Is=RegExp(`^${Fs}$`);function Ls(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 Rs(e){return RegExp(`^${Ls(e)}$`)}function zs(e){let t=`${Fs}T${Ls(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Bs(e,t){return!!((t===`v4`||!t)&&ks.test(e)||(t===`v6`||!t)&&js.test(e))}function Vs(e,t){if(!Ts.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 Hs(e,t){return!!((t===`v4`||!t)&&As.test(e)||(t===`v6`||!t)&&Ms.test(e))}var Us=class e extends R{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.string,received:t.parsedType}),F}let t=new ds,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?P(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&P(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Os||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Os.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Cs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ws.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)bs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)xs.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ss.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),P(n,{validation:`url`,code:N.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`regex`,code:N.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?zs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Is.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Rs(r).test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Es.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Bs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Vs(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Hs(e.data,r.version)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Ns.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ps.test(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...I.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...I.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...I.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...I.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...I.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...I.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...I.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...I.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...I.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...I.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...I.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...I.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...I.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...I.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...I.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...I.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...I.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...I.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Us.create=e=>new Us({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...L(e)});function Ws(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 Gs=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.number,received:t.parsedType}),F}let t,n=new ds;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ws(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:I.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:I.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:I.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:I.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&j.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Gs.create=e=>new Gs({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...L(e)});var Ks=class e extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let t,n=new ds;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),P(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit(`min`,e,!0,I.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,I.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,I.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,I.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:I.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ks.create=e=>new Ks({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var qs=class extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.boolean,received:t.parsedType}),F}return ps(e.data)}};qs.create=e=>new qs({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var Js=class e extends R{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.date,received:t.parsedType}),F}if(Number.isNaN(e.data.getTime()))return P(this._getOrReturnCtx(e),{code:N.invalid_date}),F;let t=new ds,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),P(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:I.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:I.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Js.create=e=>new Js({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...L(e)});var Ys=class extends R{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.symbol,received:t.parsedType}),F}return ps(e.data)}};Ys.create=e=>new Ys({typeName:z.ZodSymbol,...L(e)});var Xs=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.undefined,received:t.parsedType}),F}return ps(e.data)}};Xs.create=e=>new Xs({typeName:z.ZodUndefined,...L(e)});var Zs=class extends R{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.null,received:t.parsedType}),F}return ps(e.data)}};Zs.create=e=>new Zs({typeName:z.ZodNull,...L(e)});var Qs=class extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return ps(e.data)}};Qs.create=e=>new Qs({typeName:z.ZodAny,...L(e)});var $s=class extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ps(e.data)}};$s.create=e=>new $s({typeName:z.ZodUnknown,...L(e)});var ec=class extends R{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.never,received:t.parsedType}),F}};ec.create=e=>new ec({typeName:z.ZodNever,...L(e)});var tc=class extends R{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.void,received:t.parsedType}),F}return ps(e.data)}};tc.create=e=>new tc({typeName:z.ZodVoid,...L(e)});var nc=class e extends R{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return P(t,{code:N.invalid_type,expected:M.array,received:t.parsedType}),F;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(P(t,{code:e?N.too_big:N.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:N.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:N.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new vs(t,e,t.path,n)))).then(e=>ds.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new vs(t,e,t.path,n)));return ds.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};nc.create=(e,t)=>new nc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...L(t)});function rc(e){if(e instanceof ic){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Sc.create(rc(r))}return new ic({...e._def,shape:()=>t})}else if(e instanceof nc)return new nc({...e._def,type:rc(e.element)});else if(e instanceof Sc)return Sc.create(rc(e.unwrap()));else if(e instanceof Cc)return Cc.create(rc(e.unwrap()));else if(e instanceof uc)return uc.create(e.items.map(e=>rc(e)));else return e}var ic=class e extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ec&&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 vs(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ec){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(P(n,{code:N.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new vs(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=>ds.mergeObjectSync(t,e)):ds.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:I.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of j.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return rc(this)}partial(t){let n={};for(let e of j.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Sc;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return _c(j.objectKeys(this.shape))}};ic.create=(e,t)=>new ic({shape:()=>e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.strictCreate=(e,t)=>new ic({shape:()=>e,unknownKeys:`strict`,catchall:ec.create(),typeName:z.ZodObject,...L(t)}),ic.lazycreate=(e,t)=>new ic({shape:e,unknownKeys:`strip`,catchall:ec.create(),typeName:z.ZodObject,...L(t)});var ac=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new os(e.ctx.common.issues));return P(t,{code:N.invalid_union,unionErrors:n}),F}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new os(e));return P(t,{code:N.invalid_union,unionErrors:i}),F}}get options(){return this._def.options}};ac.create=(e,t)=>new ac({options:e,typeName:z.ZodUnion,...L(t)});const oc=e=>e instanceof hc?oc(e.schema):e instanceof xc?oc(e.innerType()):e instanceof gc?[e.value]:e instanceof vc?e.options:e instanceof yc?j.objectValues(e.enum):e instanceof wc?oc(e._def.innerType):e instanceof Xs?[void 0]:e instanceof Zs?[null]:e instanceof Sc?[void 0,...oc(e.unwrap())]:e instanceof Cc?[null,...oc(e.unwrap())]:e instanceof Dc||e instanceof kc?oc(e.unwrap()):e instanceof Tc?oc(e._def.innerType):[];var sc=class e extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return P(t,{code:N.invalid_type,expected:M.object,received:t.parsedType}),F;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=oc(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...L(r)})}};function cc(e,t){let n=as(e),r=as(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=cc(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=cc(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var lc=class extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ms(e)||ms(r))return F;let i=cc(e.value,r.value);return i.valid?((hs(e)||hs(r))&&t.dirty(),{status:t.value,value:i.data}):(P(n,{code:N.invalid_intersection_types}),F)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lc.create=(e,t,n)=>new lc({left:e,right:t,typeName:z.ZodIntersection,...L(n)});var uc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:N.invalid_type,expected:M.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return P(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),F;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new vs(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ds.mergeArray(t,e)):ds.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};uc.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new uc({items:e,typeName:z.ZodTuple,rest:null,...L(t)})};var dc=class e extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:N.invalid_type,expected:M.object,received:n.parsedType}),F;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new vs(n,e,n.path,e)),value:a._parse(new vs(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ds.mergeObjectAsync(t,r):ds.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof R?new e({keyType:t,valueType:n,typeName:z.ZodRecord,...L(r)}):new e({keyType:Us.create(),valueType:t,typeName:z.ZodRecord,...L(n)})}},fc=class extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:N.invalid_type,expected:M.map,received:n.parsedType}),F;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new vs(n,e,n.path,[a,`key`])),value:i._parse(new vs(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return F;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};fc.create=(e,t,n)=>new fc({valueType:t,keyType:e,typeName:z.ZodMap,...L(n)});var pc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:N.invalid_type,expected:M.set,received:n.parsedType}),F;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(P(n,{code:N.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(P(n,{code:N.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return F;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new vs(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};pc.create=(e,t)=>new pc({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...L(t)});var mc=class e extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return P(t,{code:N.invalid_type,expected:M.function,received:t.parsedType}),F;function n(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return us({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ls(),ss].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof bc){let e=this;return ps(async function(...t){let o=new os([]),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 ps(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new os([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new os([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:uc.create(t).rest($s.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||uc.create([]).rest($s.create()),returns:n||$s.create(),typeName:z.ZodFunction,...L(r)})}},hc=class extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};hc.create=(e,t)=>new hc({getter:e,typeName:z.ZodLazy,...L(t)});var gc=class extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),F}return{status:`valid`,value:e.data}}get value(){return this._def.value}};gc.create=(e,t)=>new gc({value:e,typeName:z.ZodLiteral,...L(t)});function _c(e,t){return new vc({values:e,typeName:z.ZodEnum,...L(t)})}var vc=class e extends R{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{expected:j.joinValues(n),received:t.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return P(t,{received:t.data,code:N.invalid_enum_value,options:n}),F}return ps(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})}};vc.create=_c;var yc=class extends R{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return P(n,{expected:j.joinValues(e),received:n.parsedType,code:N.invalid_type}),F}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return P(n,{received:n.data,code:N.invalid_enum_value,options:e}),F}return ps(e.data)}get enum(){return this._def.values}};yc.create=(e,t)=>new yc({values:e,typeName:z.ZodNativeEnum,...L(t)});var bc=class extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(P(t,{code:N.invalid_type,expected:M.promise,received:t.parsedType}),F):ps((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bc.create=(e,t)=>new bc({type:e,typeName:z.ZodPromise,...L(t)});var xc=class extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{P(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return F;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r});{if(t.value===`aborted`)return F;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?F:r.status===`dirty`||t.value===`dirty`?fs(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?F:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?F:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gs(e))return F;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>gs(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):F);j.assertNever(r)}};xc.create=(e,t,n)=>new xc({schema:e,typeName:z.ZodEffects,effect:t,...L(n)}),xc.createWithPreprocess=(e,t,n)=>new xc({schema:t,effect:{type:`preprocess`,transform:e},typeName:z.ZodEffects,...L(n)});var Sc=class extends R{_parse(e){return this._getType(e)===M.undefined?ps(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:z.ZodOptional,...L(t)});var Cc=class extends R{_parse(e){return this._getType(e)===M.null?ps(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cc.create=(e,t)=>new Cc({innerType:e,typeName:z.ZodNullable,...L(t)});var wc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};wc.create=(e,t)=>new wc({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...L(t)});var Tc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _s(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new os(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tc.create=(e,t)=>new Tc({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...L(t)});var Ec=class extends R{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return P(t,{code:N.invalid_type,expected:M.nan,received:t.parsedType}),F}return{status:`valid`,value:e.data}}};Ec.create=e=>new Ec({typeName:z.ZodNaN,...L(e)});var Dc=class extends R{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Oc=class e extends R{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),fs(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?F:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:z.ZodPipeline})}},kc=class extends R{_parse(e){let t=this._def.innerType._parse(e),n=e=>(gs(e)&&(e.value=Object.freeze(e.value)),e);return _s(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};kc.create=(e,t)=>new kc({innerType:e,typeName:z.ZodReadonly,...L(t)}),ic.lazycreate;var z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(z||={}),Us.create,Gs.create,Ec.create,Ks.create,qs.create,Js.create,Ys.create,Xs.create,Zs.create,Qs.create,$s.create,ec.create,tc.create,nc.create;const Ac=ic.create;ic.strictCreate,ac.create,sc.create,lc.create,uc.create,dc.create,fc.create,pc.create,mc.create,hc.create,gc.create,vc.create,yc.create,bc.create,xc.create,Sc.create,Cc.create,xc.createWithPreprocess,Oc.create;const jc=d(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ae.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>o(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>p(e,t,n),e.parseAsync=async(t,n)=>ie(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>m(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)=>g(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Mc=d(`ZodMiniObject`,(e,t)=>{h.init(e,t),jc.init(e,t),l(e,`shape`,()=>t.shape)});function Nc(e,t){return new Mc({type:`object`,shape:e??{},...u(t)})}function Pc(e){return!!e._zod}function Fc(e){let t=Object.values(e);if(t.length===0)return Nc({});let n=t.every(Pc),r=t.every(e=>!Pc(e));if(n)return Nc(e);if(r)return Ac(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Ic(e,t){return Pc(e)?p(e,t):e.safeParse(t)}async function Lc(e,t){return Pc(e)?await m(e,t):await e.safeParseAsync(t)}function Rc(e){if(!e)return;let t;if(t=Pc(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function zc(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 Fc(e)}}if(Pc(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 Bc(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 Vc(e){return e.description}function Hc(e){if(Pc(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Uc(e){if(Pc(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 Wc=`2025-11-25`,Gc=[Wc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Kc=`io.modelcontextprotocol/related-task`,qc=te(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Jc=y([D(),C().int()]),Yc=D();w({ttl:C().optional(),pollInterval:C().optional()});const Xc=x({ttl:C().optional()}),Zc=x({taskId:D()}),Qc=w({progressToken:Jc.optional(),[Kc]:Zc.optional()}),$c=x({_meta:Qc.optional()}),el=$c.extend({task:Xc.optional()}),tl=e=>el.safeParse(e).success,nl=x({method:D(),params:$c.loose().optional()}),rl=x({_meta:Qc.optional()}),il=x({method:D(),params:rl.loose().optional()}),al=w({_meta:Qc.optional()}),ol=y([D(),C().int()]),sl=x({jsonrpc:E(`2.0`),id:ol,...nl.shape}).strict(),cl=e=>sl.safeParse(e).success,ll=x({jsonrpc:E(`2.0`),...il.shape}).strict(),ul=e=>ll.safeParse(e).success,dl=x({jsonrpc:E(`2.0`),id:ol,result:al}).strict(),fl=e=>dl.safeParse(e).success;var B;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(B||={});const pl=x({jsonrpc:E(`2.0`),id:ol.optional(),error:x({code:C().int(),message:D(),data:s().optional()})}).strict(),ml=e=>pl.safeParse(e).success,hl=y([sl,ll,dl,pl]);y([dl,pl]);const gl=al.strict(),_l=rl.extend({requestId:ol.optional(),reason:D().optional()}),vl=il.extend({method:E(`notifications/cancelled`),params:_l}),yl=x({icons:T(x({src:D(),mimeType:D().optional(),sizes:T(D()).optional(),theme:le([`light`,`dark`]).optional()})).optional()}),bl=x({name:D(),title:D().optional()}),xl=bl.extend({...bl.shape,...yl.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),Sl=ge(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ce(x({form:ce(x({applyDefaults:ue().optional()}),S(D(),s())).optional(),url:qc.optional()}),S(D(),s()).optional())),Cl=w({list:qc.optional(),cancel:qc.optional(),requests:w({sampling:w({createMessage:qc.optional()}).optional(),elicitation:w({create:qc.optional()}).optional()}).optional()}),wl=w({list:qc.optional(),cancel:qc.optional(),requests:w({tools:w({call:qc.optional()}).optional()}).optional()}),Tl=x({experimental:S(D(),qc).optional(),sampling:x({context:qc.optional(),tools:qc.optional()}).optional(),elicitation:Sl.optional(),roots:x({listChanged:ue().optional()}).optional(),tasks:Cl.optional(),extensions:S(D(),qc).optional()}),El=$c.extend({protocolVersion:D(),capabilities:Tl,clientInfo:xl}),Dl=nl.extend({method:E(`initialize`),params:El}),Ol=x({experimental:S(D(),qc).optional(),logging:qc.optional(),completions:qc.optional(),prompts:x({listChanged:ue().optional()}).optional(),resources:x({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:x({listChanged:ue().optional()}).optional(),tasks:wl.optional(),extensions:S(D(),qc).optional()}),kl=al.extend({protocolVersion:D(),capabilities:Ol,serverInfo:xl,instructions:D().optional()}),Al=il.extend({method:E(`notifications/initialized`),params:rl.optional()}),jl=nl.extend({method:E(`ping`),params:$c.optional()}),Ml=x({progress:C(),total:fe(C()),message:fe(D())}),Nl=x({...rl.shape,...Ml.shape,progressToken:Jc}),Pl=il.extend({method:E(`notifications/progress`),params:Nl}),Fl=$c.extend({cursor:Yc.optional()}),Il=nl.extend({params:Fl.optional()}),Ll=al.extend({nextCursor:Yc.optional()}),Rl=le([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zl=x({taskId:D(),status:Rl,ttl:y([C(),ee()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:fe(C()),statusMessage:fe(D())}),Bl=al.extend({task:zl}),Vl=rl.merge(zl),Hl=il.extend({method:E(`notifications/tasks/status`),params:Vl}),Ul=nl.extend({method:E(`tasks/get`),params:$c.extend({taskId:D()})}),Wl=al.merge(zl),Gl=nl.extend({method:E(`tasks/result`),params:$c.extend({taskId:D()})});al.loose();const Kl=Il.extend({method:E(`tasks/list`)}),ql=Ll.extend({tasks:T(zl)}),Jl=nl.extend({method:E(`tasks/cancel`),params:$c.extend({taskId:D()})}),Yl=al.merge(zl),Xl=x({uri:D(),mimeType:fe(D()),_meta:S(D(),s()).optional()}),Zl=Xl.extend({text:D()}),Ql=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$l=Xl.extend({blob:Ql}),eu=le([`user`,`assistant`]),tu=x({audience:T(eu).optional(),priority:C().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),nu=x({...bl.shape,...yl.shape,uri:D(),description:fe(D()),mimeType:fe(D()),size:fe(C()),annotations:tu.optional(),_meta:fe(w({}))}),ru=x({...bl.shape,...yl.shape,uriTemplate:D(),description:fe(D()),mimeType:fe(D()),annotations:tu.optional(),_meta:fe(w({}))}),iu=Il.extend({method:E(`resources/list`)}),au=Ll.extend({resources:T(nu)}),ou=Il.extend({method:E(`resources/templates/list`)}),su=Ll.extend({resourceTemplates:T(ru)}),cu=$c.extend({uri:D()}),lu=cu,uu=nl.extend({method:E(`resources/read`),params:lu}),du=al.extend({contents:T(y([Zl,$l]))}),fu=il.extend({method:E(`notifications/resources/list_changed`),params:rl.optional()}),pu=cu,mu=nl.extend({method:E(`resources/subscribe`),params:pu}),hu=cu,gu=nl.extend({method:E(`resources/unsubscribe`),params:hu}),_u=rl.extend({uri:D()}),vu=il.extend({method:E(`notifications/resources/updated`),params:_u}),yu=x({name:D(),description:fe(D()),required:fe(ue())}),bu=x({...bl.shape,...yl.shape,description:fe(D()),arguments:fe(T(yu)),_meta:fe(w({}))}),xu=Il.extend({method:E(`prompts/list`)}),Su=Ll.extend({prompts:T(bu)}),Cu=$c.extend({name:D(),arguments:S(D(),D()).optional()}),wu=nl.extend({method:E(`prompts/get`),params:Cu}),Tu=x({type:E(`text`),text:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Eu=x({type:E(`image`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Du=x({type:E(`audio`),data:Ql,mimeType:D(),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Ou=x({type:E(`tool_use`),name:D(),id:D(),input:S(D(),s()),_meta:S(D(),s()).optional()}),ku=x({type:E(`resource`),resource:y([Zl,$l]),annotations:tu.optional(),_meta:S(D(),s()).optional()}),Au=y([Tu,Eu,Du,nu.extend({type:E(`resource_link`)}),ku]),ju=x({role:eu,content:Au}),Mu=al.extend({description:D().optional(),messages:T(ju)}),Nu=il.extend({method:E(`notifications/prompts/list_changed`),params:rl.optional()}),Pu=x({title:D().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),Fu=x({taskSupport:le([`required`,`optional`,`forbidden`]).optional()}),Iu=x({...bl.shape,...yl.shape,description:D().optional(),inputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()),outputSchema:x({type:E(`object`),properties:S(D(),qc).optional(),required:T(D()).optional()}).catchall(s()).optional(),annotations:Pu.optional(),execution:Fu.optional(),_meta:S(D(),s()).optional()}),Lu=Il.extend({method:E(`tools/list`)}),Ru=Ll.extend({tools:T(Iu)}),zu=al.extend({content:T(Au).default([]),structuredContent:S(D(),s()).optional(),isError:ue().optional()});zu.or(al.extend({toolResult:s()}));const Bu=el.extend({name:D(),arguments:S(D(),s()).optional()}),Vu=nl.extend({method:E(`tools/call`),params:Bu}),Hu=il.extend({method:E(`notifications/tools/list_changed`),params:rl.optional()});x({autoRefresh:ue().default(!0),debounceMs:C().int().nonnegative().default(300)});const Uu=le([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wu=$c.extend({level:Uu}),Gu=nl.extend({method:E(`logging/setLevel`),params:Wu}),Ku=rl.extend({level:Uu,logger:D().optional(),data:s()}),qu=il.extend({method:E(`notifications/message`),params:Ku}),Ju=x({hints:T(x({name:D().optional()})).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Yu=x({mode:le([`auto`,`required`,`none`]).optional()}),Xu=x({type:E(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:T(Au).default([]),structuredContent:x({}).loose().optional(),isError:ue().optional(),_meta:S(D(),s()).optional()}),Zu=ne(`type`,[Tu,Eu,Du]),Qu=ne(`type`,[Tu,Eu,Du,Ou,Xu]),$u=x({role:eu,content:y([Qu,T(Qu)]),_meta:S(D(),s()).optional()}),ed=el.extend({messages:T($u),modelPreferences:Ju.optional(),systemPrompt:D().optional(),includeContext:le([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:T(D()).optional(),metadata:qc.optional(),tools:T(Iu).optional(),toolChoice:Yu.optional()}),td=nl.extend({method:E(`sampling/createMessage`),params:ed}),nd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:eu,content:Zu}),rd=al.extend({model:D(),stopReason:fe(le([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:eu,content:y([Qu,T(Qu)])}),id=x({type:E(`boolean`),title:D().optional(),description:D().optional(),default:ue().optional()}),ad=x({type:E(`string`),title:D().optional(),description:D().optional(),minLength:C().optional(),maxLength:C().optional(),format:le([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),od=x({type:le([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),sd=x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),default:D().optional()}),cd=x({type:E(`string`),title:D().optional(),description:D().optional(),oneOf:T(x({const:D(),title:D()})),default:D().optional()}),ld=y([y([x({type:E(`string`),title:D().optional(),description:D().optional(),enum:T(D()),enumNames:T(D()).optional(),default:D().optional()}),y([sd,cd]),y([x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({type:E(`string`),enum:T(D())}),default:T(D()).optional()}),x({type:E(`array`),title:D().optional(),description:D().optional(),minItems:C().optional(),maxItems:C().optional(),items:x({anyOf:T(x({const:D(),title:D()}))}),default:T(D()).optional()})])]),id,ad,od]),ud=y([el.extend({mode:E(`form`).optional(),message:D(),requestedSchema:x({type:E(`object`),properties:S(D(),ld),required:T(D()).optional()})}),el.extend({mode:E(`url`),message:D(),elicitationId:D(),url:D().url()})]),dd=nl.extend({method:E(`elicitation/create`),params:ud}),fd=rl.extend({elicitationId:D()}),pd=il.extend({method:E(`notifications/elicitation/complete`),params:fd}),md=al.extend({action:le([`accept`,`decline`,`cancel`]),content:ge(e=>e===null?void 0:e,S(D(),y([D(),C(),ue(),T(D())])).optional())}),hd=x({type:E(`ref/resource`),uri:D()}),gd=x({type:E(`ref/prompt`),name:D()}),_d=$c.extend({ref:y([gd,hd]),argument:x({name:D(),value:D()}),context:x({arguments:S(D(),D()).optional()}).optional()}),vd=nl.extend({method:E(`completion/complete`),params:_d});function yd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xd=al.extend({completion:w({values:T(D()).max(100),total:fe(C().int()),hasMore:fe(ue())})}),Sd=x({uri:D().startsWith(`file://`),name:D().optional(),_meta:S(D(),s()).optional()}),Cd=nl.extend({method:E(`roots/list`),params:$c.optional()}),wd=al.extend({roots:T(Sd)}),Td=il.extend({method:E(`notifications/roots/list_changed`),params:rl.optional()});y([jl,Dl,vd,Gu,wu,xu,iu,ou,uu,mu,gu,Vu,Lu,Ul,Gl,Kl,Jl]),y([vl,Pl,Al,Td,Hl]),y([gl,nd,rd,md,wd,Wl,ql,Bl]),y([jl,td,dd,Cd,Ul,Gl,Kl,Jl]),y([vl,Pl,qu,vu,fu,Hu,Nu,Hl,pd]),y([gl,kl,xd,Mu,Su,au,su,du,zu,Ru,Wl,ql,Bl]);var V=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===B.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ed(e.elicitations,n)}return new e(t,n,r)}},Ed=class extends V{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dd(e){return e===`completed`||e===`failed`||e===`cancelled`}const Od=Symbol(`Let zodToJsonSchema decide on which parser to use`),kd={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`},Ad=e=>typeof e==`string`?{...kd,name:e}:{...kd,...e},jd=e=>{let t=Ad(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 Md(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,Md(e,t,r,i)}const Nd=(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 Pd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Nd(t,e.currentPath):t.join(`/`)}}function Fd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==z.ZodAny&&(n.items=U(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Id(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function Ld(){return{type:`boolean`}}function Rd(e,t){return U(e.type._def,t)}const zd=(e,t)=>U(e.innerType._def,t);function Bd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Bd(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 Vd(e,t)}}const Vd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Hd(e,t){return{...U(e.innerType._def,t),default:e.defaultValue()}}function Ud(e,t){return t.effectStrategy===`input`?U(e.schema._def,t):Pd(t)}function Wd(e){return{type:`string`,enum:Array.from(e.values)}}const Gd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Kd(e,t){let n=[U(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),U(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Gd(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 qd(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 Jd;const Yd={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:()=>(Jd===void 0&&(Jd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Jd),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 Xd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:ef(n,`email`,r.message,t);break;case`format:idn-email`:ef(n,`idn-email`,r.message,t);break;case`pattern:zod`:tf(n,Yd.email,r.message,t);break}break;case`url`:ef(n,`uri`,r.message,t);break;case`uuid`:ef(n,`uuid`,r.message,t);break;case`regex`:tf(n,r.regex,r.message,t);break;case`cuid`:tf(n,Yd.cuid,r.message,t);break;case`cuid2`:tf(n,Yd.cuid2,r.message,t);break;case`startsWith`:tf(n,RegExp(`^${Zd(r.value,t)}`),r.message,t);break;case`endsWith`:tf(n,RegExp(`${Zd(r.value,t)}$`),r.message,t);break;case`datetime`:ef(n,`date-time`,r.message,t);break;case`date`:ef(n,`date`,r.message,t);break;case`time`:ef(n,`time`,r.message,t);break;case`duration`:ef(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:tf(n,RegExp(Zd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&ef(n,`ipv4`,r.message,t),r.version!==`v4`&&ef(n,`ipv6`,r.message,t);break;case`base64url`:tf(n,Yd.base64url,r.message,t);break;case`jwt`:tf(n,Yd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&tf(n,Yd.ipv4Cidr,r.message,t),r.version!==`v4`&&tf(n,Yd.ipv6Cidr,r.message,t);break;case`emoji`:tf(n,Yd.emoji(),r.message,t);break;case`ulid`:tf(n,Yd.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:ef(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:tf(n,Yd.base64,r.message,t);break}break;case`nanoid`:tf(n,Yd.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Zd(e,t){return t.patternStrategy===`escape`?$d(e):e}const Qd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function $d(e){let t=``;for(let n=0;n<e.length;n++)Qd.has(e[n])||(t+=`\\`),t+=e[n];return t}function ef(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):H(e,`format`,t,n,r)}function tf(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:nf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,nf(t,r),n,r)}function nf(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
31
31
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
32
32
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function rf(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Pd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Xd(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===z.ZodBranded&&e.keyType._def.type._def.typeName===z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Rd(e.keyType._def,t);return{...n,propertyNames:i}}return n}function af(e,t){return t.mapStrategy===`record`?rf(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[U(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Pd(t),U(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Pd(t)],minItems:2,maxItems:2}}}function of(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function sf(e){return e.target===`openAi`?void 0:{not:Pd({...e,currentPath:[...e.currentPath,`not`]})}}function cf(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const lf={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function uf(e,t){if(t.target===`openApi3`)return df(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in lf&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=lf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return df(e,t)}const df=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ff(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:lf[e.innerType._def.typeName],nullable:!0}:{type:[lf[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function pf(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,Md(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function mf(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=gf(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=U(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=hf(e,t);return o!==void 0&&(r.additionalProperties=o),r}function hf(e,t){if(e.catchall._def.typeName!==`ZodNever`)return U(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function gf(e){try{return e.isOptional()}catch{return!0}}const _f=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return U(e.innerType._def,t);let n=U(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Pd(t)},n]}:Pd(t)},vf=(e,t)=>{if(t.pipeStrategy===`input`)return U(e.in._def,t);if(t.pipeStrategy===`output`)return U(e.out._def,t);let n=U(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,U(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function yf(e,t){return U(e.type._def,t)}function bf(e,t){let n={type:`array`,uniqueItems:!0,items:U(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&H(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&H(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function xf(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:U(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>U(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Sf(e){return{not:Pd(e)}}function Cf(e){return Pd(e)}const wf=(e,t)=>U(e.innerType._def,t),Tf=(e,t,n)=>{switch(t){case z.ZodString:return Xd(e,n);case z.ZodNumber:return pf(e,n);case z.ZodObject:return mf(e,n);case z.ZodBigInt:return Id(e,n);case z.ZodBoolean:return Ld();case z.ZodDate:return Bd(e,n);case z.ZodUndefined:return Sf(n);case z.ZodNull:return cf(n);case z.ZodArray:return Fd(e,n);case z.ZodUnion:case z.ZodDiscriminatedUnion:return uf(e,n);case z.ZodIntersection:return Kd(e,n);case z.ZodTuple:return xf(e,n);case z.ZodRecord:return rf(e,n);case z.ZodLiteral:return qd(e,n);case z.ZodEnum:return Wd(e);case z.ZodNativeEnum:return of(e);case z.ZodNullable:return ff(e,n);case z.ZodOptional:return _f(e,n);case z.ZodMap:return af(e,n);case z.ZodSet:return bf(e,n);case z.ZodLazy:return()=>e.getter()._def;case z.ZodPromise:return yf(e,n);case z.ZodNaN:case z.ZodNever:return sf(n);case z.ZodEffects:return Ud(e,n);case z.ZodAny:return Pd(n);case z.ZodUnknown:return Cf(n);case z.ZodDefault:return Hd(e,n);case z.ZodBranded:return Rd(e,n);case z.ZodReadonly:return wf(e,n);case z.ZodCatch:return zd(e,n);case z.ZodPipeline:return vf(e,n);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(e=>void 0)(t)}};function U(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Od)return i}if(r&&!n){let e=Ef(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Tf(e,e.typeName,t),o=typeof a==`function`?U(a(),t):a;if(o&&Df(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Ef=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Nd(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Pd(t)):t.$refStrategy===`seen`?Pd(t):void 0}},Df=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Of=(e,t)=>{let n=jd(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:U(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Pd(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=U(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Pd(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function kf(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Af(e,t){return Pc(e)?b(e,{target:kf(t?.target),io:t?.pipeStrategy??`input`}):Of(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function jf(e){let t=Rc(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Uc(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Mf(e,t){let n=Ic(e,t);if(!n.success)throw n.error;return n.data}var Nf=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(vl,e=>{this._oncancel(e)}),this.setNotificationHandler(Pl,e=>{this._onprogress(e)}),this.setRequestHandler(jl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ul,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V(B.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Gl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new V(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new V(B.InvalidParams,`Task not found: ${r}`);if(!Dd(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Dd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Kc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Kl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new V(B.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Jl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V(B.InvalidParams,`Task not found: ${e.params.taskId}`);if(Dd(n.status))throw new V(B.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new V(B.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof V?e:new V(B.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),V.fromError(B.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),fl(e)||ml(e)?this._onresponse(e):cl(e)?this._onrequest(e,t):ul(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=V.fromError(B.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Kc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:B.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=tl(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new V(B.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:B.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),fl(e)?n(e):n(new V(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(fl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),fl(e)?r(e):r(V.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof V?e:new V(B.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Bl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new V(B.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Dd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new V(B.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new V(B.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof V?e:new V(B.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Kc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof V?e:new V(B.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Ic(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(V.fromError(B.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Wl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ql,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Yl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Kc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Kc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Kc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=jf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Mf(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=jf(e);this._notificationHandlers.set(n,n=>{let r=Mf(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&cl(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new V(B.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new V(B.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new V(B.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new V(B.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Hl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Dd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new V(B.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Dd(a.status))throw new V(B.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Hl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Dd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ff(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];Pf(a)&&Pf(i)?n[r]={...a,...i}:n[r]=i}return n}var If=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Lf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=If();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),W=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=If(),n=Lf();var r=If();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=Lf();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ie(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ie(this.rhs,e,n),this}get names(){return w(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ie(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(ae(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>C(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(T(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ie(this.condition,e,t),this}get names(){let e=super.names;return w(e,this.condition),this.else&&C(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ie(this.iteration,e,t),this}get names(){return C(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return w(w(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ie(this.iterable,e,t),this}get names(){return C(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var ee=class extends p{render(e){return`return `+super.render(e)}};ee.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&C(e,this.catch.names),this.finally&&C(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
33
33
  `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new ee;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(ee)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function C(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function w(e,n){return n instanceof t._CodeOrName?C(e,n.names):e}function ie(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function ae(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function T(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=T;let E=le(e.operators.AND);function oe(...e){return e.reduce(E)}e.and=oe;let se=le(e.operators.OR);function ce(...e){return e.reduce(se)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=W(),n=If();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Rf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),zf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=Rf();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Bf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=zf(),n=W(),r=Rf(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Vf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Hf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Uf=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Vf(),n=Hf(),r=zf(),i=W(),a=G();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
@@ -204,7 +204,7 @@ superseded_by: <path-to-new-canonical-article>.md
204
204
  - **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
205
205
  - **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
206
206
  `}const lh=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
207
- `);function uh(e,t){e.tool(`consolidate`,lh,{topic:D().describe(`The topic to consolidate into a canonical article`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(ch(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}function dh(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function fh(e){return e.endsWith(`/`)?e.slice(0,-1):e}function ph(e){try{return new URL(e),!0}catch{return!1}}async function mh(e,t,n){let r=n??await t.resolveCwd(),i=await th(t.config,r),a=Ce(i,r);return vh(e,{config:i,lockDir:Se(a),contentDir:a})}function hh(e){try{let t=je(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function gh(e,t){let n=t??await e.resolveCwd(),r=await th(e.config,n),i=Ce(r,n),a={config:r,lockDir:Se(i),contentDir:i};return{resolve:e=>vh(e,a),ui:hh(a)}}function _h(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function vh(e,t){let n=`/#/${dh(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=qn(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&ph(r))return{url:`${fh(r)}${n}`,source:`env`};try{let e=je(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&ph(i)?{url:`${fh(i)}${n}`,source:`config`}:null}const yh=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
207
+ `);function uh(e,t){e.tool(`consolidate`,lh,{topic:D().describe(`The topic to consolidate into a canonical article`),cwd:D().optional().describe(qm)},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);return n.ok?q(ch(e.topic,n.config.content.dir),{previewUrl:null}):K(`Error: ${n.error}`,!0)})}function dh(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function fh(e){return e.endsWith(`/`)?e.slice(0,-1):e}function ph(e){try{return new URL(e),!0}catch{return!1}}async function mh(e,t,n){let r=n??await t.resolveCwd(),i=await th(t.config,r),a=Ce(i,r);return vh(e,{config:i,lockDir:Se(a),contentDir:a})}function hh(e){try{let t=je(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function gh(e,t){let n=t??await e.resolveCwd(),r=await th(e.config,n),i=Ce(r,n),a={config:r,lockDir:Se(i),contentDir:i};return{resolve:e=>vh(e,a),ui:hh(a)}}function _h(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function vh(e,t){let n=`/#/${dh(e)}`;if(process.env.OK_ELECTRON_PROTOCOL_HOST===`1`&&t.contentDir)try{let n=qn(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(n)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}let r=process.env.OPEN_KNOWLEDGE_PREVIEW_BASE_URL;if(r&&ph(r))return{url:`${fh(r)}${n}`,source:`env`};try{let e=je(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${n}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}, falling through to config: ${e instanceof Error?e.message:String(e)}\n`)}let i=t.config.preview?.baseUrl;return i&&ph(i)?{url:`${fh(i)}${n}`,source:`config`}:null}const yh=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,'**Body-only.** Frontmatter-intersecting find/replace calls are rejected with HTTP 400. Frontmatter editing via MCP is currently unavailable — to change frontmatter, use `write_document` with `position: "replace"` and a payload that includes the new YAML block.',``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
208
208
  `);function bh(e,t){e.tool(`edit_document`,yh,{docName:D().describe(`Document name to edit`),find:D().describe(`Text to find (exact match)`),replace:D().describe(`Replacement text`),offset:C().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-patch`,{docName:o.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=vh(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=c.summary&&typeof c.summary==`object`?c.summary:void 0,h=typeof m?.hint==`string`?m.hint:void 0,g=[`Edit applied successfully.`];u&&g.push(`Preview: ${u.url}`),f&&g.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),h&&g.push(h);let _=g.join(`
209
209
  `);if(!u&&!f&&!p&&!m)return K(_);let v={};return u&&(v.previewUrl=u.url,v.previewUrlSource=u.source),f&&(v.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(v.summary=m),q(_,v)})}const xh=new Set([`cat`,`ls`,`grep`,`find`]),Sh=/\b[\w./-]+\.(md|mdx)\b/g;function Ch(e){return/\.(md|mdx)$/.test(e)}function wh(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function Th(e){return e.args.slice(1)}function Eh(e){return e.filter(e=>!e.startsWith(`-`))}function Dh(e){return Eh(Th(e)).filter(Ch)}function Oh(e,t){let n=Eh(Th(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?wh(r):``,a=[];i&&a.push(i);for(let t of e.split(`
210
210
  `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!Ch(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function kh(e){let t=[];for(let n of e.split(`
@@ -1381,9 +1381,9 @@ In headless mode, write the recap into the research article's "Further reading"
1381
1381
  `);function rw(e,t,n,r,i){e.tool(`save_version`,nw,{cwd:D().optional().describe(qm)},async(e={})=>{let a=await rh(r,t,n,e.cwd);if(!a.ok)return K(`Error: ${a.error}`,!0);if(!a.url)return K(Ym,!0);let{url:o}=a,s=i?.current,c=await oh(o,`/api/save-version`,{...s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{}});return c.ok?q(`Checkpoint saved. Checkpoint ref: ${c.checkpointRef}`,{checkpointRef:c.checkpointRef,previewUrl:null}):K(`Error: ${c.error}`,!0)})}const iw=[`Search wiki content with metadata-enriched results. Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding all articles mentioning a topic`,`- Locating a specific term across the wiki before deciding which file to read`,``,"**When the project has `.open-knowledge/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.open-knowledge/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match"].join(`
1382
1382
  `);function aw(e){let t=new Map;for(let n of e){let e=t.get(n.path);e?e.push(n):t.set(n.path,[n])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function ow(e,t){let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)throw Error(n.error);let{cwd:r,config:a,url:o}=n,s=a.mcp.tools.search.maxResults,c=a.content.include,l=a.content.exclude,u=await Yx(e.query,r,{caseInsensitive:!(e.case_sensitive??!1),include:c,exclude:[...l,`node_modules`,`.git`,`.claude`,`.changeset`,i],maxResults:s+1}),d=u.length>s,f=d?u.slice(0,s):u,{resolve:p,ui:m}=await gh({config:a,resolveCwd:async()=>r},r);if(f.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:m,cwd:r}};let h=aw(f),g=new Map,_=a.folders;await Promise.all(h.map(async e=>{try{let t=await WS(e.path,{projectDir:r,serverUrl:o,folderRules:_});g.set(e.path,t)}catch{}}));let v=[];v.push(`## Search results for "${e.query}" (${f.length} match${f.length===1?``:`es`} in ${h.length} file${h.length===1?``:`s`})`,``);let y=[];for(let e of h){let t=g.get(e.path),n=t?.title??e.path;v.push(`### ${n} (${e.path})`),t?.tags?.length&&v.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&v.push(`${t.description}`);for(let t of e.matches)v.push(`- Line ${t.line}: ${t.text}`);v.push(``);let r=_h(e.path),i=p(r);y.push({path:e.path,docName:r,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:i?.url??null,...i?{previewUrlSource:i.source}:{}})}return d&&v.push(`_${f.length} of ${u.length}+ matches shown. Raise \`mcp.tools.search.maxResults\` in config.yml to see more._`),{text:v.join(`
1383
1383
  `),structured:{query:e.query,matchCount:f.length,fileCount:h.length,truncated:d,results:y,ui:m,cwd:r}}}function sw(e,t){e.tool(`search`,iw,{query:D().describe(`Literal text to search for`),case_sensitive:ue().optional().describe(`Case-sensitive search (default false)`),cwd:D().optional().describe("Absolute host path to search in. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},async e=>{try{let{text:n,structured:r}=await ow(e,t);return r?q(n,r):K(n)}catch(e){return K(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const cw=[`[Operates on disk; no running OK server required] Set fields in the Open Knowledge config (project + user-global YAML).`,``,`Pass a deep-partial patch over the agent-settable allowlist. The server picks the write target (project vs user) automatically based on where the path is already set + per-field default scope.`,``,`**Allowlist** (only these paths are agent-settable):`,"- `content.include` — globs of files to include in the wiki","- `content.exclude` — globs to exclude","- `folders[]` — folder-rule defaults (whole-array replace; for per-rule upsert use `set_folder_rule`)","- `mcp.tools.search.maxResults` — search result cap","- `mcp.tools.read_document.historyDepth` — number of history entries returned",``,"Other paths are rejected with `NOT_AGENT_SETTABLE`. To inspect what is currently set, call `get_config`.",``,"**Patch semantics:** RFC 7396 spirit (TypeScript-only — no wire format). Top-level keys present are written; absent keys are unchanged; `null` clears a field; nested objects merge recursively; arrays replace wholesale.",``,"**Mixed scope:** if leaves in a single patch resolve to different scopes (e.g., one project-only field + one user-only field), the call fails with `MIXED_SCOPE` — retry per-scope.",``,`**Parameters:**`,"- `patch` — Deep-partial config patch over the allowlist (see above).","- `cwd` (optional) — Project root."].join(`
1384
- `),lw={patch:w({}).describe(`Deep-partial config patch over the agent-settable allowlist. See description for the 5 allowed paths. Null at any path clears the field; arrays replace wholesale.`),cwd:D().optional().describe(qm)},uw={result:y([x({ok:E(!0),applied:T(D()),scope:le([`user`,`project`]),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function dw(e){let t=[];function n(e,r){if(e!==void 0){if(e===null||Array.isArray(e)||typeof e!=`object`){t.push(r);return}for(let[t,i]of Object.entries(e))n(i,[...r,t])}}for(let[t,r]of Object.entries(e))n(r,[t]);return t}function fw(e){return e.map(e=>({path:[...e],meta:p(Ge,e)}))}function pw(e,t,n){return t?.project?`project`:t?.user?`user`:n??`user`}function mw(e,t,n){let r=Be(e.map(e=>e.path),{cwd:t,...n===void 0?{}:{homedirOverride:n}}),i=e.map(e=>{let t=r.get(e.path.join(`.`));return{path:e.path,scope:pw(e.path,t,e.meta?.defaultScope)}}),a=new Set(i.map(e=>e.scope));if(a.size>1)return{mixed:{code:`MIXED_SCOPE`,paths:i.map(({path:e,scope:t})=>({path:e.map(String),scope:t}))}};let[o]=a;return{scope:o??`user`,perLeaf:i}}function hw(e){return{isError:!0,structuredContent:{result:{ok:!1,error:e}},content:[{type:`text`,text:`${l(e)}\n\nPlease fix and try again.`}]}}function gw(e,t){e.registerTool(`set_config`,{description:cw,inputSchema:lw,outputSchema:uw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=e.patch,a=dw(i);if(a.length===0)return hw({code:`SCHEMA_INVALID`,issues:[{path:[],message:`Patch is empty — pass at least one leaf value.`,issueCode:`empty_patch`}]});let o=fw(a),s=o.find(e=>e.meta?.agentSettable!==!0);if(s)return hw({code:`NOT_AGENT_SETTABLE`,path:s.path.map(String)});let c=mw(o,r,t.homedirOverride);if(`mixed`in c)return hw(c.mixed);let l=await Re({cwd:r,scope:c.scope,patch:i,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!l.ok)return hw(l.error);let u={result:{ok:!0,applied:l.appliedPaths,scope:c.scope,path:l.path,current:l.effective}};return q(JSON.stringify(u.result,null,2),u)})}const _w=["[Operates on disk; no running OK server required] Upsert one or more folder rules in the project `folders[]` array.",``,"Folder rules apply default frontmatter (title / description / tags) to every doc whose path matches `match` (a glob like `specs/**` or `reports/*/**`). Use this tool to add a new rule, replace an existing one keyed by `match`, or rename via `new_match`.",``,`Always pass an array — even for a single rule. The tool runs all rules transactionally: if any rule produces an invalid merged config, NO rules are applied to disk.`,``,'**To remove a rule**, use `set_config({patch: {folders: [<filtered-array>]}})` — read folders via `get_config({path: ["folders"]})`, drop the entry, then write back.',``,`**Parameters:**`,"- `rules` — Array of `{match, frontmatter, new_match?}`.",' - `match` — Glob pattern that identifies the rule (e.g. `"specs/**"`). Required.',' - `frontmatter` — `{title?, description?, tags?: string[]}` to apply. Required (use `{}` for "match the rule but apply no frontmatter").'," - `new_match` — If set, rename the rule keyed by `match` to this glob. If both already exist, the rename target is overwritten.","- `cwd` (optional) — Project root."].join(`
1385
- `),vw={rules:T(x({match:D().min(1).describe(`Glob pattern (e.g. "specs/**", "reports/*/**") that identifies the rule.`),frontmatter:_.describe("Default frontmatter to apply to matched docs: `{title?, description?, tags?: string[]}`."),new_match:D().min(1).optional().describe("If set, rename the existing rule keyed by `match` to this new glob.")})).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:D().optional().describe(qm)},yw={result:y([x({ok:E(!0),applied:T(D()),scope:E(`project`),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function bw(e,t){e.registerTool(`set_folder_rule`,{description:_w,inputSchema:vw,outputSchema:yw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=await Ve({cwd:r,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter,...e.new_match===void 0?{}:{new_match:e.new_match}})),scope:`project`,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!i.ok)return{isError:!0,structuredContent:{result:{ok:!1,error:i.error}},content:[{type:`text`,text:`${l(i.error)}\n\nPlease fix and try again.`}]};let a={result:{ok:!0,applied:i.appliedPaths,scope:`project`,path:i.path,current:i.effective}};return q(JSON.stringify(a.result,null,2),a)})}const xw=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
1386
- `);function Sw(e,t){e.tool(`suggest_links`,xw,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await mh(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const Cw=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1384
+ `),lw={patch:w({}).describe(`Deep-partial config patch over the agent-settable allowlist. See description for the 5 allowed paths. Null at any path clears the field; arrays replace wholesale.`),cwd:D().optional().describe(qm)},uw={result:y([x({ok:E(!0),applied:T(D()),scope:le([`user`,`project`]),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function dw(e){let t=[];function n(e,r){if(e!==void 0){if(e===null||Array.isArray(e)||typeof e!=`object`){t.push(r);return}for(let[t,i]of Object.entries(e))n(i,[...r,t])}}for(let[t,r]of Object.entries(e))n(r,[t]);return t}function fw(e){return e.map(e=>({path:[...e],meta:f(Ge,e)}))}function pw(e,t,n){return t?.project?`project`:t?.user?`user`:n??`user`}function mw(e,t,n){let r=Be(e.map(e=>e.path),{cwd:t,...n===void 0?{}:{homedirOverride:n}}),i=e.map(e=>{let t=r.get(e.path.join(`.`));return{path:e.path,scope:pw(e.path,t,e.meta?.defaultScope)}}),a=new Set(i.map(e=>e.scope));if(a.size>1)return{mixed:{code:`MIXED_SCOPE`,paths:i.map(({path:e,scope:t})=>({path:e.map(String),scope:t}))}};let[o]=a;return{scope:o??`user`,perLeaf:i}}function hw(e){return{isError:!0,structuredContent:{result:{ok:!1,error:e}},content:[{type:`text`,text:`${c(e)}\n\nPlease fix and try again.`}]}}function gw(e,t){e.registerTool(`set_config`,{description:cw,inputSchema:lw,outputSchema:uw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=e.patch,a=dw(i);if(a.length===0)return hw({code:`SCHEMA_INVALID`,issues:[{path:[],message:`Patch is empty — pass at least one leaf value.`,issueCode:`empty_patch`}]});let o=fw(a),s=o.find(e=>e.meta?.agentSettable!==!0);if(s)return hw({code:`NOT_AGENT_SETTABLE`,path:s.path.map(String)});let c=mw(o,r,t.homedirOverride);if(`mixed`in c)return hw(c.mixed);let l=await Re({cwd:r,scope:c.scope,patch:i,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!l.ok)return hw(l.error);let u={result:{ok:!0,applied:l.appliedPaths,scope:c.scope,path:l.path,current:l.effective}};return q(JSON.stringify(u.result,null,2),u)})}const _w=["[Operates on disk; no running OK server required] Upsert one or more folder rules in the project `folders[]` array.",``,"Folder rules apply default frontmatter (title / description / tags) to every doc whose path matches `match` (a glob like `specs/**` or `reports/*/**`). Use this tool to add a new rule, replace an existing one keyed by `match`, or rename via `new_match`.",``,`Always pass an array — even for a single rule. The tool runs all rules transactionally: if any rule produces an invalid merged config, NO rules are applied to disk.`,``,'**To remove a rule**, use `set_config({patch: {folders: [<filtered-array>]}})` — read folders via `get_config({path: ["folders"]})`, drop the entry, then write back.',``,`**Parameters:**`,"- `rules` — Array of `{match, frontmatter, new_match?}`.",' - `match` — Glob pattern that identifies the rule (e.g. `"specs/**"`). Required.',' - `frontmatter` — `{title?, description?, tags?: string[]}` to apply. Required (use `{}` for "match the rule but apply no frontmatter").'," - `new_match` — If set, rename the rule keyed by `match` to this glob. If both already exist, the rename target is overwritten.","- `cwd` (optional) — Project root."].join(`
1385
+ `),vw={rules:T(x({match:D().min(1).describe(`Glob pattern (e.g. "specs/**", "reports/*/**") that identifies the rule.`),frontmatter:_.describe("Default frontmatter to apply to matched docs: `{title?, description?, tags?: string[]}`."),new_match:D().min(1).optional().describe("If set, rename the existing rule keyed by `match` to this new glob.")})).min(1).describe("One or more folder rules to upsert. Always an array — pass `[{...}]` for a single rule."),cwd:D().optional().describe(qm)},yw={result:y([x({ok:E(!0),applied:T(D()),scope:E(`project`),path:D(),current:S(D(),s())}),x({ok:E(!1),error:re})])};function bw(e,t){e.registerTool(`set_folder_rule`,{description:_w,inputSchema:vw,outputSchema:yw,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let n=await nh(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let{cwd:r}=n,i=await Ve({cwd:r,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter,...e.new_match===void 0?{}:{new_match:e.new_match}})),scope:`project`,...t.homedirOverride===void 0?{}:{homedirOverride:t.homedirOverride}});if(!i.ok)return{isError:!0,structuredContent:{result:{ok:!1,error:i.error}},content:[{type:`text`,text:`${c(i.error)}\n\nPlease fix and try again.`}]};let a={result:{ok:!0,applied:i.appliedPaths,scope:`project`,path:i.path,current:i.effective}};return q(JSON.stringify(a.result,null,2),a)})}const xw=[`[Requires: Hocuspocus server] Find missing link candidates for a target page.`,"Returns JSON with structure: `{ target: { docName, title, aliases }, mentions: [{ source, excerpt, offset }], truncated }`.","Each mention includes an `offset` you can pass to `edit_document` for precision patching.","When `truncated` is true, the scan hit its time budget before reading every admitted document.",``,`**Parameters:**`,'- `docName` — Target page docName, typically without extension (for example, "articles/project-alpha"). A trailing `.md` or `.mdx` is stripped automatically.'].join(`
1386
+ `);function Sw(e,t){e.tool(`suggest_links`,xw,{docName:D().describe(`Target page docName`),cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return K(Ym,!0);let a=ih(e.docName);if(!a.ok)return K(a.error,!0);let o=await ah(i,`/api/suggest-links?docName=${encodeURIComponent(a.docName)}`);if(!o.ok)return K(`Error: ${o.error}`,!0);let{ok:s,...c}=o,l=await mh(a.docName,{config:t.config,resolveCwd:t.resolveCwd},r);return q(JSON.stringify(c,null,2),{...c,previewUrl:l?.url??null,...l?{previewUrlSource:l.source}:{}})})}const Cw=[`[Requires: Hocuspocus server] Write markdown content to a document via the CRDT layer.`,`Content is applied through Hocuspocus and propagated to all connected editors in real-time.`,``,'**Frontmatter.** The markdown payload may include a YAML frontmatter block (`---`-fenced). To change frontmatter, call this tool with `position: "replace"` and a payload that includes the new YAML block — per-property MCP editing is currently unavailable. `edit_document` rejects frontmatter-intersecting find/replace calls.',``,'**Link liberally.** Every noun-phrase that names another document in this knowledge base should be a `[[wiki-link]]`, not plain prose. Backlinks are the primary navigation surface — underlinked documents become islands. Redlinks (links to pages that don\'t exist yet) are fine; they signal "this should exist." Prefer `[[Page Name]]` over Markdown `[text](./page.md)` — only wiki-links participate in the backlinks index.',``,`**Parameters:**`,'- `docName` — Document name, typically without extension (e.g., "my-doc" or "notes/meeting"). A trailing `.md` or `.mdx` is stripped automatically. New documents are created as `.md` by default; to create a `.mdx` file, first place it on disk, then use this tool for edits.',"- `markdown` — Markdown content to write",'- `position` — Where to insert: "append", "prepend", or "replace"','- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Added 3 lines"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
1387
1387
  `);function ww(e,t){e.tool(`write_document`,Cw,{docName:D().describe(`Document name to write to`),markdown:D().describe(`Markdown content to write`),position:le([`append`,`prepend`,`replace`]).describe(`Where to insert the content`),summary:Jm,cwd:D().optional().describe(qm)},async e=>{let n=await rh(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(Ym,!0);let o=ih(e.docName);if(!o.ok)return K(o.error,!0);let s=t.identityRef?.current,c=await oh(a,`/api/agent-write-md`,{docName:o.docName,markdown:e.markdown,position:e.position,...e.summary===void 0?{}:{summary:e.summary},...s?{agentId:s.connectionId,agentName:s.displayName,clientName:s.clientInfo?.name,colorSeed:s.colorSeed}:{}});if(!c.ok)return K(`Error: ${c.error}`,!0);let l=Se(Ce(i,r)),u=vh(o.docName,{config:i,lockDir:l}),d=typeof c.subscriberCount==`number`?c.subscriberCount:void 0,f=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,p=d===0,m=Array.isArray(c.hints)?c.hints:void 0,h=c.summary&&typeof c.summary==`object`?c.summary:void 0,g=typeof h?.hint==`string`?h.hint:void 0,_=[`Written successfully (${e.position}).`];if(u&&_.push(`Preview: ${u.url}`),f&&_.push(u?`Open ${u.url} in your preview browser.`:`No preview attached. Start the UI.`),g&&_.push(g),m)for(let e of m)e.message&&_.push(e.message);let v=_.join(`
1388
1388
  `);if(!u&&!f&&!p&&!m&&!h)return K(v);let y={};return u&&(y.previewUrl=u.url,y.previewUrlSource=u.source),f&&(y.warning={message:`Open the previewUrl in your preview browser.`,action:`attach-preview-once`,previewUrl:u?.url??null}),m&&(y.hints=m),h&&(y.summary=h),q(v,y)})}function Tw(e,t){let n=t.logger,r=Km(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(Mm()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(Mm()??n)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...r?{explicit:r}:{}}),t}};lC(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),kC(r,{config:t.config,resolveCwd:i(`ingest`)}),$C(r,{config:t.config,resolveCwd:i(`research`)}),uh(r,{config:t.config,resolveCwd:i(`consolidate`)}),BC(r,{resolveCwd:i(`read_document`),config:t.config,serverUrl:t.serverUrl}),sw(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl}),Sw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`suggest_links`)}),ww(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write_document`),identityRef:t.identityRef}),bh(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit_document`),identityRef:t.identityRef}),GC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_document`),identityRef:t.identityRef}),XC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rename_folder`),identityRef:t.identityRef}),SC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_history`)}),rw(r,t.config,t.serverUrl,i(`save_version`),t.identityRef),tw(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`rollback_to_version`),identityRef:t.identityRef}),jC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`list_documents`)}),dC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_backlinks`)}),bC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_forward_links`)}),EC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_orphans`)}),wC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_hubs`)}),vC(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`get_dead_links`)}),gC(r,{config:t.config,resolveCwd:i(`get_config`)}),gw(r,{config:t.config,resolveCwd:i(`set_config`)}),bw(r,{config:t.config,resolveCwd:i(`set_folder_rule`)})}function Ew(e){return e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`?e.code:e instanceof Error&&e.name?e.name:typeof e}var Dw=class extends Error{};function Ow(e){let t=Ue(e.startupCwd),n=null,r=null,i=async()=>n===null?(r||=(async()=>{let t=await e.listRoots(),r=await Promise.all(t.roots.map(async e=>e.uri.startsWith(`file://`)?await Ue(or(e.uri)):null)),i=[...new Set(r.filter(e=>e!==null))];return n=i,e.logger?.info(`roots resolved`,{roots:i,count:i.length}),i})().finally(()=>{r=null}),await r):n;return{async resolveCwd(n){if(n){let t=await Ue(n);return e.logger?.debug(`cwd resolved`,{cwd:t,routing:`explicit`}),t}if(e.bypassProjectSelection){let n=await t;return e.logger?.debug(`cwd resolved`,{cwd:n,routing:`bypass`}),n}let r;try{r=await i()}catch(t){throw e.logger?.warn(`roots/list unavailable`,{error:t instanceof Error?t.message:String(t),errorType:Ew(t)}),new Dw(`Client roots unavailable; pass cwd explicitly.`)}if(r.length===0)throw new Dw(`No client roots available; pass cwd explicitly.`);if(r.length>1)throw new Dw(`Multiple roots available; pass cwd explicitly.`);return e.logger?.debug(`cwd resolved`,{cwd:r[0],routing:`single-root`}),r[0]},invalidateRoots(){n=null,r=null,e.logger?.info(`roots cache invalidated`)}}}function kw(e){let t=Ue(e.startupCwd),n;return{async resolveCwdForTools(t){let r=await e.resolveCwd(t);return n=r,r},async getKeepaliveCwd(){return e.bypassProjectSelection?await t:n}}}let Aw;function jw(e,t){let{dir:n,include:r,exclude:i}=e.content,a=i.length>0?i.map(e=>`\`${e}\``).join(`, `):`(none)`;return`# Open Knowledge (OK) — collaborative markdown via MCP
1389
1389
 
@@ -1406,8 +1406,8 @@ Claude Code Desktop: \`preview_start("open-knowledge-ui")\`. Other hosts: open-U
1406
1406
  Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in the installed \`open-knowledge\` Agent Skill. If missing, run \`npx @inkeep/open-knowledge init\`.
1407
1407
 
1408
1408
  **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.open-knowledge/\`, when no OK MCP is registered, or right after a failed OK MCP call (then prefix with \`Open Knowledge MCP unavailable:\`). Non-markdown: native tools always.
1409
- `}async function Mw(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 Nw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(Aw=Am(),Aw.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Mw(n,Aw);Aw.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else Aw.info(`server discovery is lazy per effective cwd`);let o=new mm({name:xe,version:be},{instructions:jw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Ow({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:Aw}),c=kw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(Td,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=sr(),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},Aw?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},Tw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:Aw});let m=new Dm;await o.connect(m),Aw.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:Aw.child(`keepalive`)}),_=e=>{Aw?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const Pw=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],Fw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Iw(e){if(!e||e.length===0)return`unknown`;for(let t of Pw)if(e.includes(t))return`npx-cache`;return Fw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function Lw(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 Rw(e){return e?/\bENOENT\b/i.test(e):!1}function zw(e){switch(Iw(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 Bw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Rw(e)&&(r+=`\n\n${zw(n)}`),r}function Vw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Hw(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=Iw(o),c=Lw(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 Uw(e){let t=e.readLock??(()=>we(e.lockDir)),n=e.isAlive??Te,r=e.sleep??(e=>fr(e)),i=e.spawn??jn,a=e.readErrorLog??(e=>Hn(e)?Gn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Wn(e,`w`)),s=e.closeFd??Vn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=Hw({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);Hn(e.lockDir)||Un(e.lockDir,{recursive:!0});let f=Ln(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=kn();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:Rw(h)}),Error(Bw(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:Rw(h)}),Error(Bw(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 Ww(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??Uw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ue(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=Ce(i,o),s=Se(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 Gw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Ke({startupCwd:r,startupConfig:n}),a=Vw(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=Ww({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 Nw({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 Kw(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-CD7jAwMP.mjs`),r=e(),i=process.cwd(),a=Ce(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function qw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Jw(e,t,n=process.cwd()){let r=e.op??`sync`,i=we(Se(Ce(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}`)}qw(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=De({baseDir:n});if(r===`sync`||r===`pull`){qw(e.json,{type:`step`,step:`pull`});let t=await a.pull();qw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(qw(e.json,{type:`step`,step:`push`}),await a.push(),qw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1409
+ `}async function Mw(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 Nw(e){let{projectDir:t,serverUrl:n,config:r,startupConfig:i,bypassProjectSelection:a=!1}=e;if(Aw=Am(),Aw.info(`MCP server starting`,{startupCwd:t,bypassProjectSelection:a,serverUrlType:typeof n==`string`?`explicit`:`lazy`}),typeof n==`string`){let e=await Mw(n,Aw);Aw.info(`Hocuspocus detection complete`,{serverUrl:n,available:e})}else Aw.info(`server discovery is lazy per effective cwd`);let o=new mm({name:xe,version:be},{instructions:jw(i,{dynamicConfig:typeof r==`function`&&!a})}),s=Ow({startupCwd:t,bypassProjectSelection:a,listRoots:()=>o.server.listRoots(),logger:Aw}),c=kw({startupCwd:t,resolveCwd:s.resolveCwd,bypassProjectSelection:a}),l=c.resolveCwdForTools;o.server.setNotificationHandler(Td,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=sr(),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},Aw?.info(`agent identity established`,{displayName:p.current.displayName,connectionId:d.slice(0,8),clientName:e?.name})},Tw(o,{serverUrl:u,resolveCwd:l,config:r,identityRef:p,logger:Aw});let m=new Dm;await o.connect(m),Aw.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:Aw.child(`keepalive`)}),_=e=>{Aw?.info(`MCP server shutting down`,{signal:e});try{g.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>_(`SIGINT`)),process.on(`SIGTERM`,()=>_(`SIGTERM`))}const Pw=[`/_npx/`,`/.npm/_npx/`,`/_bunx/`,`/.bun/install/cache/`,`/pnpm/dlx/`],Fw=new Set([`/usr/local/bin/ok`,`/usr/local/bin/open-knowledge`,`/opt/homebrew/bin/ok`,`/opt/homebrew/bin/open-knowledge`]);function Iw(e){if(!e||e.length===0)return`unknown`;for(let t of Pw)if(e.includes(t))return`npx-cache`;return Fw.has(e)||e.startsWith(`/Applications/`)||e.includes(`.app/Contents/`)?`stable-shim`:e.startsWith(`/`)?`absolute-pin`:`unknown`}function Lw(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 Rw(e){return e?/\bENOENT\b/i.test(e):!1}function zw(e){switch(Iw(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 Bw(e,t,n){let r=`spawn failed: ${e}${t?` stderr:\n${t}`:``}`;return Rw(e)&&(r+=`\n\n${zw(n)}`),r}function Vw(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function Hw(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=Iw(o),c=Lw(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 Uw(e){let t=e.readLock??(()=>we(e.lockDir)),n=e.isAlive??Te,r=e.sleep??(e=>fr(e)),i=e.spawn??jn,a=e.readErrorLog??(e=>Hn(e)?Gn(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>Wn(e,`w`)),s=e.closeFd??Vn,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=e.launchPath??process.argv[1],d=Hw({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);Hn(e.lockDir)||Un(e.lockDir,{recursive:!0});let f=Ln(e.lockDir,`last-spawn-error.log`),p=o(f),m,h,g=kn();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:Rw(h)}),Error(Bw(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:Rw(h)}),Error(Bw(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 Ww(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??Uw,n=e.cacheMs??1e3,r=new Map,i=new Map;return async a=>{let o=await Ue(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=Ce(i,o),s=Se(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 Gw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=Ke({startupCwd:r,startupConfig:n}),a=Vw(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=Ww({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 Nw({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 Kw(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-CnsTM1D_.mjs`),r=e(),i=process.cwd(),a=Ce(r,i),o;try{o=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function qw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Jw(e,t,n=process.cwd()){let r=e.op??`sync`,i=we(Se(Ce(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}`)}qw(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=De({baseDir:n});if(r===`sync`||r===`pull`){qw(e.json,{type:`step`,step:`pull`});let t=await a.pull();qw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(qw(e.json,{type:`step`,step:`push`}),await a.push(),qw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
1410
1410
  `)),qw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Yw(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 Jw({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 Xw(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Jw({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 Zw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Jw({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 Qw(e={}){let t=zn(e.cwd??process.cwd()),n;try{n=await Ae({projectDir:t,rootDir:e.root})}catch(e){return e instanceof ke?{status:`prerequisite-missing`,message:`${Ze(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${Ze(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(n.created.length===0&&n.configEdits.length===0)return{status:`no-op`,message:`${Xe(`Your knowledge base is already seeded.`)}\n${Ye(`Nothing to do.`)}`,plan:n,exitCode:0};if(e.dryRun)return{status:`dry-run`,message:`${$e(`Plan (dry-run — no changes made):`)}\n\n${$w(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await eT(`${$e(`Plan:`)}\n\n${$w(n,t)}\n\n${$e(`Apply?`)} ${Ye(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:Ye(`Cancelled.`),plan:n,exitCode:0};let r=await Oe(n,{projectDir:t});if(r.errors.length>0){let e=r.errors.map(e=>` ${Ze(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${Qe(`Applied`)} ${r.applied} entries, ${Qe(String(r.errors.length))} error(s):`,...e].join(`
1411
1411
  `),plan:n,exitCode:1}}return{status:`applied`,message:`${Xe(`✓ Seeded knowledge base`)} ${Ye(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function $w(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($e(`Folders to create:`));for(let e of r)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}${Ye(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push($e(`Files to create:`));for(let e of i)n.push(` ${Xe(`+`)} ${Je(Rn(t,zn(t,e.path))||e.path)}`)}if(e.configEdits.length>0){n.length>0&&n.push(``),n.push($e(`config.yml folders: entries to add:`));for(let t of e.configEdits)n.push(` ${Xe(`+`)} ${Je(t.folderMatch)} ${Ye(`—`)} ${t.entry.frontmatter.title??``}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(Ye(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${Ye(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(Qe(`Warnings:`));for(let t of e.warnings)n.push(` ${Qe(`!`)} ${t}`)}return n.join(`
1412
- `)}async function eT(e,t){let n=gr({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 tT(){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 Qw({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 nT(e,t){return{server:rT(`server`,e),ui:rT(`ui`,t)}}function rT(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 iT(e){return`${aT(e.server)}\n${aT(e.ui)}`}function aT(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 oT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=nT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(iT(r)),r}function sT(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=>{oT({lockDir:Se(Ce(e(),process.cwd())),json:t.json===!0})})}function cT(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 lT(e){let t=e.inspect??(t=>No(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=cT(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 uT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{lT({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const dT=1e4,fT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function pT(e){let t=e.upstreamTimeoutMs??dT,n=pr((n,r)=>{hT(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 mT(e,t,n){hT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??dT)}function hT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of fT)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=mr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of fT)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 gT(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function _T(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BnZHVzE4.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-Bcq8_cdi.mjs`),m=f(e.config,e.cwd),h=p(m);i(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,includePatterns:e.config.content.include,excludePatterns:e.config.content.exclude}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:he,assetExtensions:oe,blocklistExtensions:de}):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}mT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):vT(t)});return}if(v){v(e,t);return}vT(t)},ee=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],te=[],ne=e.port;try{for(let e of ee){let t=n(S);te.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ne,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ne=e.port),n()})})}}catch(e){await Promise.all(te.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let re=ne;b=re,u(h,re);let C=e.scheduler??a,w=e.safetyNetMs??432e5,ie=null,ae=!1,T=!1,E=()=>{ae||(ae=!0,ie!==null&&(C.clearTimeout(ie),ie=null))},se=()=>{if(E(),!T){T=!0;try{l(h)}catch{}}},ce=()=>{ae||w<=0||(ie!==null&&(C.clearTimeout(ie),ie=null),ie=C.setTimeout(()=>{ie=null,console.warn(`[ui] safety-net (${w}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of te)try{e.close()}catch{}se()},w))},le=()=>{ae||w<=0||ce()};return x=le,ce(),{httpServers:te,port:re,release:se,detachSafetyNet:E,nudgeSafetyNet:le}}function vT(e){e.writeHead(404),e.end(`Not found`)}function yT(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 bT(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BnZHVzE4.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 pT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function xT(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-BnZHVzE4.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-Bcq8_cdi.mjs`),o=e(),s=t.host,c;try{c=yT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await _T({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)}};gT(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 bT({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 ST=new r;let CT;ST.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(be).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}=We(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),CT=r});const wT=On(()=>CT);ST.addCommand(wT,{isDefault:!0});const TT=Gw(()=>CT);ST.addCommand(TT),ST.addCommand(qe()),ST.addCommand(tT()),ST.addCommand(rs());const ET=Kw(()=>CT);ST.addCommand(ET);const DT=xT(()=>CT);ST.addCommand(DT),ST.addCommand(uT(()=>CT)),ST.addCommand(Io(()=>CT)),ST.addCommand(sT(()=>CT)),ST.addCommand($o()),ST.addCommand(Mo(()=>CT)),ST.addCommand(Ko(()=>CT)),ST.addCommand(Yw(()=>CT)),ST.addCommand(Zw(()=>CT)),ST.addCommand(Xw(()=>CT)),await ST.parseAsync();export{};
1412
+ `)}async function eT(e,t){let n=gr({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 tT(){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 Qw({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 nT(e,t){return{server:rT(`server`,e),ui:rT(`ui`,t)}}function rT(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 iT(e){return`${aT(e.server)}\n${aT(e.ui)}`}function aT(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 oT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=nT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(iT(r)),r}function sT(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=>{oT({lockDir:Se(Ce(e(),process.cwd())),json:t.json===!0})})}function cT(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 lT(e){let t=e.inspect??(t=>No(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=cT(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 uT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{lT({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const dT=1e4,fT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function pT(e){let t=e.upstreamTimeoutMs??dT,n=pr((n,r)=>{hT(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 mT(e,t,n){hT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??dT)}function hT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of fT)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=mr({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of fT)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 gT(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function _T(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-BuWOuGGO.mjs`),{default:d}=await import(`./build-DPvitIN3.mjs`),{resolveContentDir:f,resolveLockDir:p}=await import(`./paths-r4eAorwU.mjs`),m=f(e.config,e.cwd),h=p(m);i(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,includePatterns:e.config.content.include,excludePatterns:e.config.content.exclude}),contentSirv:d(m,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:he,assetExtensions:oe,blocklistExtensions:de}):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}mT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):vT(t)});return}if(v){v(e,t);return}vT(t)},ee=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],te=[],ne=e.port;try{for(let e of ee){let t=n(S);te.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(ne,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(ne=e.port),n()})})}}catch(e){await Promise.all(te.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{l(h)}catch{}throw e}let re=ne;b=re,u(h,re);let C=e.scheduler??a,w=e.safetyNetMs??432e5,ie=null,ae=!1,T=!1,E=()=>{ae||(ae=!0,ie!==null&&(C.clearTimeout(ie),ie=null))},se=()=>{if(E(),!T){T=!0;try{l(h)}catch{}}},ce=()=>{ae||w<=0||(ie!==null&&(C.clearTimeout(ie),ie=null),ie=C.setTimeout(()=>{ie=null,console.warn(`[ui] safety-net (${w}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of te)try{e.close()}catch{}se()},w))},le=()=>{ae||w<=0||ce()};return x=le,ce(),{httpServers:te,port:re,release:se,detachSafetyNet:E,nudgeSafetyNet:le}}function vT(e){e.writeHead(404),e.end(`Not found`)}function yT(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 bT(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-BuWOuGGO.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 pT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function xT(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-BuWOuGGO.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-r4eAorwU.mjs`),o=e(),s=t.host,c;try{c=yT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await _T({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)}};gT(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 bT({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 ST=new r;let CT;ST.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(be).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}=We(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),CT=r});const wT=On(()=>CT);ST.addCommand(wT,{isDefault:!0});const TT=Gw(()=>CT);ST.addCommand(TT),ST.addCommand(qe()),ST.addCommand(tT()),ST.addCommand(rs());const ET=Kw(()=>CT);ST.addCommand(ET);const DT=xT(()=>CT);ST.addCommand(DT),ST.addCommand(uT(()=>CT)),ST.addCommand(Io(()=>CT)),ST.addCommand(sT(()=>CT)),ST.addCommand($o()),ST.addCommand(Mo(()=>CT)),ST.addCommand(Ko(()=>CT)),ST.addCommand(Yw(()=>CT)),ST.addCommand(Zw(()=>CT)),ST.addCommand(Xw(()=>CT)),await ST.parseAsync();export{};
1413
1413
  //# sourceMappingURL=cli.mjs.map