@inkeep/open-knowledge 0.0.0-dev-20260501034226 → 0.0.0-dev-20260501045551
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +15 -0
- package/dist/cli.mjs +7 -7
- package/dist/constants-CYAWu1t_.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/init-3aNImgts.mjs +1 -0
- package/dist/{init-298Ayrtx.mjs → init-C4wke4uB.mjs} +2 -2
- package/dist/{init-CXD7S1br.mjs → init-CD1Q6xzB.mjs} +3 -3
- package/dist/init-DcSlN0vZ.mjs +1 -0
- package/dist/loader-C-9Jcwv3.mjs +1 -0
- package/dist/{loader-CBGPucqb.mjs → loader-LlG0LgdL.mjs} +2 -2
- package/dist/paths-CinA1Uub.mjs +2 -0
- package/dist/paths-D8xkWudL.mjs +1 -0
- package/dist/{preview-YdZO7Xe-.mjs → preview-BaEgnUY0.mjs} +2 -2
- package/dist/preview-j16n7DSe.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-Dh5iGi22.js → ActivityModeContent-BLbgxGR9.js} +1 -1
- package/dist/public/assets/{DocumentContext-BtLDstmc.js → DocumentContext-CjSzCZL0.js} +1 -1
- package/dist/public/assets/SettingsPane-ztNlE-yh.js +6 -0
- package/dist/public/assets/{SourceEditor-C0WLCZqD.js → SourceEditor-D-FWP4Ng.js} +1 -1
- package/dist/public/assets/{clipboard-CIRkQ4_J.js → clipboard-DiHLkR-W.js} +1 -1
- package/dist/public/assets/config-validation-events-GcLpFEMN.js +1 -0
- package/dist/public/assets/{index-BbGfAZdV.css → index-Du0-WJgD.css} +1 -1
- package/dist/public/assets/{index-CrNx3AgB.js → index-kpNzOlZa.js} +72 -72
- package/dist/public/index.html +6 -6
- package/dist/src-aFcF98AM.mjs +1 -0
- package/dist/start-DW0GxweG.mjs +1 -0
- package/dist/{start-S8FFCxLU.mjs → start-cf2OdewF.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BVSgu1p0.mjs +0 -2
- package/dist/init-BRaqMC9N.mjs +0 -1
- package/dist/init-CFRhnDnB.mjs +0 -1
- package/dist/loader-Cl1JDwMN.mjs +0 -1
- package/dist/paths-B42XU6NV.mjs +0 -1
- package/dist/paths-C7JyDBWk.mjs +0 -2
- package/dist/preview-DMu5oITV.mjs +0 -1
- package/dist/public/assets/SettingsPane-C93_FdcE.js +0 -5
- package/dist/public/assets/config-validation-events-ClxIZ8iZ.js +0 -1
- package/dist/src-r-4kerBt.mjs +0 -1
- package/dist/start-DUwONCW8.mjs +0 -1
|
@@ -1185,6 +1185,11 @@ Homepage: https://github.com/honojs/node-server
|
|
|
1185
1185
|
|
|
1186
1186
|
Copyright (c) 2022 - present, Yusuke Wada and Hono contributors
|
|
1187
1187
|
|
|
1188
|
+
### `@hookform/resolvers@5.2.2`
|
|
1189
|
+
Homepage: https://react-hook-form.com
|
|
1190
|
+
|
|
1191
|
+
Copyright (c) 2019-present Beier(Bill) Luo
|
|
1192
|
+
|
|
1188
1193
|
### `@inquirer/ansi@2.0.5`
|
|
1189
1194
|
Homepage: https://github.com/SBoudrias/Inquirer.js/blob/main/packages/ansi/README.md
|
|
1190
1195
|
|
|
@@ -1845,6 +1850,11 @@ Homepage: https://github.com/sindresorhus/merge-streams
|
|
|
1845
1850
|
|
|
1846
1851
|
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
|
1847
1852
|
|
|
1853
|
+
### `@standard-schema/utils@0.3.0`
|
|
1854
|
+
Homepage: https://github.com/standard-schema/standard-schema
|
|
1855
|
+
|
|
1856
|
+
Copyright (c) 2024 Fabian Hiller
|
|
1857
|
+
|
|
1848
1858
|
### `@tabby_ai/hijri-converter@1.0.5`
|
|
1849
1859
|
|
|
1850
1860
|
Copyright (c) 2023 Tabby FZ-LLC
|
|
@@ -4202,6 +4212,11 @@ Homepage: https://github.com/vasturiano/react-force-graph
|
|
|
4202
4212
|
|
|
4203
4213
|
_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_
|
|
4204
4214
|
|
|
4215
|
+
### `react-hook-form@7.74.0`
|
|
4216
|
+
Homepage: https://react-hook-form.com
|
|
4217
|
+
|
|
4218
|
+
Copyright (c) 2019-present Beier(Bill) Luo
|
|
4219
|
+
|
|
4205
4220
|
### `react-is@16.13.1`
|
|
4206
4221
|
Homepage: https://reactjs.org/
|
|
4207
4222
|
|
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,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-
|
|
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-CYAWu1t_.mjs";import{n as Se,t as Ce}from"./paths-CinA1Uub.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-LlG0LgdL.mjs";import{r as qe}from"./init-CD1Q6xzB.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-cf2OdewF.mjs";import"./src-aFcF98AM.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,10 +21,10 @@ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{t as r}from"./esm-
|
|
|
21
21
|
`),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function 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-
|
|
24
|
+
`);try{let{runInit:e}=await import(`./init-DcSlN0vZ.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-
|
|
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-DW0GxweG.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
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
|
|
@@ -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-DMu5oITV.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
|
-
`)),
|
|
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
|
|
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-B42XU6NV.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-B42XU6NV.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{};
|
|
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,t){return t===void 0?!Hn(zn(e,i)):!1}function Kw(e){return new r(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(Gw(r,t.port)){process.stderr.write(`[mcp] ${r} is not an Open Knowledge project (no ${i}/); exiting. Run \`ok init\` to scaffold one.\n`),process.exitCode=1;return}let a=Ke({startupCwd:r,startupConfig:n}),o=Vw(process.env.OK_MCP_SPAWN_TIMEOUT_MS),s,c;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(s=void 0,c=`invalid --port value '${t.port}' — disk-only mode`):e>0?(s=`ws://${n.server.host}:${e}`,c=`using --port override, connecting to ${s}`):(s=void 0,c=`--port=0 — disk-only mode`)}else s=Ww({startupCwd:r,resolveConfig:a,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:o}),c=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${c}\n`),await Nw({projectDir:r,serverUrl:s,config:a,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function qw(e){return new r(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-j16n7DSe.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 Jw(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Yw(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}`)}Jw(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`){Jw(e.json,{type:`step`,step:`pull`});let t=await a.pull();Jw(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Jw(e.json,{type:`step`,step:`push`}),await a.push(),Jw(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
|
|
1410
|
+
`)),Jw(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Xw(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 Yw({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 Zw(e){return new r(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yw({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 Qw(e){return new r(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Yw({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 $w(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${eT(n,t)}`,plan:n,exitCode:0};if(!e.yes&&!await tT(`${$e(`Plan:`)}\n\n${eT(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
|
+
`),plan:n,exitCode:1}}return{status:`applied`,message:`${Xe(`✓ Seeded knowledge base`)} ${Ye(`(${r.applied} entries, ${r.durationMs}ms)`)}`,plan:n,exitCode:0}}function eT(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 tT(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 nT(){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 $w({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 rT(e,t){return{server:iT(`server`,e),ui:iT(`ui`,t)}}function iT(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 aT(e){return`${oT(e.server)}\n${oT(e.ui)}`}function oT(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 sT(e){let t=e.inspect??(t=>No(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=rT(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(aT(r)),r}function cT(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=>{sT({lockDir:Se(Ce(e(),process.cwd())),json:t.json===!0})})}function lT(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 uT(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=lT(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 dT(e){return new r(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{uT({lockDir:Se(Ce(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const fT=1e4,pT=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function mT(e){let t=e.upstreamTimeoutMs??fT,n=pr((n,r)=>{gT(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 hT(e,t,n){gT(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??fT)}function gT(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of pT)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 pT)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 _T(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function vT(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-D8xkWudL.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}hT(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(y){y(e,t,()=>{v?v(e,t):yT(t)});return}if(v){v(e,t);return}yT(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 yT(e){e.writeHead(404),e.end(`Not found`)}function bT(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 xT(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 mT({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function ST(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-D8xkWudL.mjs`),o=e(),s=t.host,c;try{c=bT(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await vT({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)}};_T(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 xT({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 CT=new r;let wT;CT.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),wT=r});const TT=On(()=>wT);CT.addCommand(TT,{isDefault:!0});const ET=Kw(()=>wT);CT.addCommand(ET),CT.addCommand(qe()),CT.addCommand(nT()),CT.addCommand(rs());const DT=qw(()=>wT);CT.addCommand(DT);const OT=ST(()=>wT);CT.addCommand(OT),CT.addCommand(dT(()=>wT)),CT.addCommand(Io(()=>wT)),CT.addCommand(cT(()=>wT)),CT.addCommand($o()),CT.addCommand(Mo(()=>wT)),CT.addCommand(Ko(()=>wT)),CT.addCommand(Xw(()=>wT)),CT.addCommand(Qw(()=>wT)),CT.addCommand(Zw(()=>wT)),await CT.parseAsync();export{};
|
|
1413
1413
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t}from"./loader-
|
|
1
|
+
import{n as e,r as t}from"./loader-LlG0LgdL.mjs";import{c as n,i as r,l as i,s as a,t as o,u as s}from"./init-CD1Q6xzB.mjs";import"./src-aFcF98AM.mjs";export{i as ALL_EDITOR_IDS,t as ConfigSchema,s as EDITOR_TARGETS,o as detectInstalledEditors,e as loadConfig,r as readExistingMcpEntry,a as writeEditorMcpConfig,n as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./init-C4wke4uB.mjs";export{e as initContent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as e,X as t}from"./dist-Bk22-nn7.mjs";import{i as n,n as r,t as i}from"./constants-
|
|
1
|
+
import{$ as e,X as t}from"./dist-Bk22-nn7.mjs";import{i as n,n as r,t as i}from"./constants-CYAWu1t_.mjs";import{join as a,resolve as o}from"node:path";import{existsSync as s,mkdirSync as c,readFileSync as l,writeFileSync as u}from"node:fs";function d(n){return`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${t}/config.project.schema.json
|
|
2
2
|
# Open Knowledge — project configuration
|
|
3
3
|
#
|
|
4
4
|
# This file overrides built-in defaults for this project. Every key below
|
|
@@ -141,4 +141,4 @@ state.json
|
|
|
141
141
|
# MCP spawn diagnostics
|
|
142
142
|
last-spawn-error.log
|
|
143
143
|
`;function h(t){let s=o(t,e),l=[],u=[],h=[];c(s,{recursive:!0}),c(a(s,i),{recursive:!0});let g=p(a(s,`.gitignore`),m);return g===`created`?l.push(`.gitignore`):g===`updated`?u.push(`.gitignore`):h.push(`.gitignore`),f(a(s,`config.yml`),d(n))?l.push(r):h.push(r),{created:l,updated:u,skipped:h}}export{h as n,d as t};
|
|
144
|
-
//# sourceMappingURL=init-
|
|
144
|
+
//# sourceMappingURL=init-C4wke4uB.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./esm-wByiX8MO.mjs";import{$ as n}from"./dist-Bk22-nn7.mjs";import{r}from"./constants-
|
|
1
|
+
import{n as e,t}from"./esm-wByiX8MO.mjs";import{$ as n}from"./dist-Bk22-nn7.mjs";import{r}from"./constants-CYAWu1t_.mjs";import{$ as i,Z as a,_ as o,dt as s}from"./dist-BKxD-v-w.mjs";import{t as c}from"./is-object-CEU0BgQ5.mjs";import{n as l}from"./init-C4wke4uB.mjs";import{t as u}from"./preview-BaEgnUY0.mjs";import{i as d,o as f,r as p,s as m,t as h}from"./colors-BdAXRiXe.mjs";import{basename as g,dirname as _,join as v,posix as y,relative as b,resolve as x,sep as S,win32 as C}from"node:path";import{existsSync as w,mkdirSync as T,readFileSync as E,writeFileSync as D}from"node:fs";import{homedir as O}from"node:os";import ee from"@inquirer/checkbox";
|
|
2
2
|
/*!
|
|
3
3
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
4
4
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -251,5 +251,5 @@ let L=/^[a-z0-9-_]+$/i;function R(e){let t=typeof e;if(t===`object`){if(Array.is
|
|
|
251
251
|
`)?n:`${n}\n`,`utf-8`)}const Be=e=>e!==`project`,Ve=e=>e!==`user`;async function He(){let e=await ee({message:`Where should the MCP server be configured?
|
|
252
252
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Ue(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??He)():`both`}const We=`0.0.1`,X=`open-knowledge-ui`;function Ge(e,t={}){let n=v(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:X,runtimeExecutable:`node`,runtimeArgs:[U(t.cliEntryPath),`ui`],port:3e3}:{name:X,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!w(n))return T(_(n),{recursive:!0}),D(n,`${JSON.stringify({version:We,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let e=E(n,`utf-8`).trim(),t=e?JSON.parse(e):{};if(!c(t))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let i=Array.isArray(t.configurations)?t.configurations:[],a=i.findIndex(e=>c(e)&&e.name===X);a>=0?i[a]=r:i.push(r);let o={...t,version:t.version??We,configurations:i};return D(n,`${JSON.stringify(o,null,2)}\n`,`utf-8`),{action:a>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Z(e,t,n){try{return w(e.detectPath?.(t,n)??_(e.configPath(t,n)))}catch{return!1}}function Q(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!Z(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};let s;try{s=e.format===`toml`?Le(o):Ie(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?ze(o,d):Re(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function Ke(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!w(n)))return{editorId:e.id,label:e.label,path:n}}async function qe(e){let t=Y(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>Q(t,``,n,e.home))}function Je(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?Le(r):Ie(r)}catch{return null}let a=i[e.topLevelKey];if(!c(a))return null;let o=a[e.serverName(t)];return c(o)?o:null}async function Ye(e={}){let t=x(e.cwd??process.cwd()),n={mode:e.pin?`pinned`:e.devMcp?`dev`:`published`,cliEntryPath:e.cliEntryPath},r=await i(t),o;try{o=l(t)}catch(n){let i=J.claude.configPath(t,e.home);return{contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],legacyProjectConfigs:[],didGitInit:r.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let c=await Ue({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),u=e.editors??$(t,e.home),d=e.editors??H.filter(e=>J[e].projectConfigPath!==void 0),f=Y(u),p=Y(d),m=e.mcp===!1||c===null,h=Array.from(new Map([...f,...m?[]:p].map(e=>[e.id,e])).values()),g=f.filter(n=>Z(n,t,e.home)),_=[],v=new Set;for(let r of h){if(m){let n=``;try{n=r.configPath(t,e.home)}catch{}_.push({editorId:r.id,label:r.label,action:`skipped-flag`,configPath:n,serverName:r.serverName(t)});continue}if(Be(c)&&f.includes(r)&&_.push(Q(r,t,n,e.home)),Ve(c)&&p.includes(r)&&r.projectConfigPath){let i=r.projectConfigPath(t),a=Q(r,t,n,e.home,i);_.push(a),(a.action===`written`||a.action===`overwritten`)&&v.add(i)}}let y=!m&&c!==null&&Ve(c)?p.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,b=m?[]:g.map(e=>Ke(e,t)).filter(e=>e!==void 0).filter(e=>!v.has(e.path)),S=g.some(e=>e.id===`claude`)&&!m?Ge(t,n):void 0,C=await(e.installUserSkill??s)({home:e.home}),w=a({home:e.home}),T=m?`skipped-flag`:`skipped-missing`,E=_.find(e=>e.editorId===`claude`)??_[0]??{action:T,configPath:J.claude.configPath(t,e.home)};return{contentCreated:o.created,contentUpdated:o.updated,contentSkipped:o.skipped,editors:_,legacyProjectConfigs:b,launchJson:S,skillInstall:C,didGitInit:r.didInit,claudeDesktopDetected:w,mcpAction:E.action,mcpPath:E.configPath,mcpError:`error`in E?E.error:void 0,projectScopeUnsupportedLabels:y}}function Xe(e,t){let r=[],i=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),a=e.editors.some(e=>e.action===`failed`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),s=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),c=e=>{let n=e.configPath.startsWith(t)?b(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&r.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let l=v(t,n);if(e.contentCreated.length>0||e.contentUpdated.length>0?(r.push(h(`Content scaffolded at ${l}/`)),e.contentCreated.length>0&&r.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&r.push(` Updated: ${e.contentUpdated.join(`, `)}`)):r.push(h(`Content already present at ${l}/`)),e.contentSkipped.length>0&&r.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),r.push(``),e.mcpError&&e.editors.length===0)r.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(r.push(h(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)r.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),n=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;r.push(` ${t} ${n} not support project-level config; skipped`)}else r.push(` No supported editor config directories detected; skipped MCP registration`);else if(o)r.push(`MCP config not written — use without --no-mcp to configure editors`);else if(s)r.push(h(`MCP server configuration:`)),r.push(` No supported editor config directories detected; skipped MCP registration`);else{r.push(h(`MCP server configuration:`));for(let n of e.editors){let i=n.configPath.startsWith(t)?b(t,n.configPath):n.configPath.replace(/^\/Users\/[^/]+/,`~`),a=n.serverName===`open-knowledge`?``:` (${n.serverName})`,o=n.configScope===`project`?` (project)`:``,s=`${n.label}${o}`,l=` `.repeat(Math.max(1,20-s.length)),u=n.editorId===`claude-desktop`&&(n.action===`written`||n.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(n.action){case`written`:r.push(` ${s}${l}${i} ${f(`registered`)}${a}${u}`);break;case`overwritten`:r.push(` ${s}${l}${i} ${f(`updated`)}${a}${u}`);break;case`skipped-missing`:r.push(` ${s}${l}${i} config root missing; skipped`);break;case`failed`:r.push(` ${s}${l}${i} ${p(`FAILED`)}: ${n.error}`);break;case`skipped-flag`:break}n.editorId===`claude`&&e.launchJson&&r.push(c(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),n=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;r.push(` ${t} ${n} not support project-level config; skipped`)}}if(a&&(r.push(``),r.push(`For failed editors, add the MCP server entry manually. See:`),r.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){r.push(``),r.push(`Project MCP configs found:`);for(let n of e.legacyProjectConfigs)r.push(` ${n.label} ${b(t,n.path)}`);r.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(r.push(``),r.push(h(`User-global skill:`)),e.skillInstall){case`installed`:r.push(` open-knowledge ${f(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:r.push(` open-knowledge ${f(`already installed at current version`)}`);break;case`failed`:r.push(` ${m(`open-knowledge install failed — MCP still configured; run manually:`)}`),r.push(` ${m(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(r.push(``),r.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${h(`ok install-skill`)}`)),e.preview?(r.push(``),r.push(u(e.preview,t))):e.previewWarning&&(r.push(``),r.push(`Content preview unavailable: ${e.previewWarning}`)),i){let t=new Set,n=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);r.push(``),r.push(`${f(`✓`)} ${h(`Next steps:`)}`),r.push(` 1. Open your editor (${d(n.join(` / `))})`),r.push(` 2. Approve the MCP server when prompted`),r.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),r.push(` - ${d(`ok seed`)}`),r.push(` 4. Use the three MCP workflow tools as you build the wiki:`),r.push(` - ${d(`mcp__open-knowledge__ingest`)} — capture an external source`),r.push(` - ${d(`mcp__open-knowledge__research`)} — gather sources and write findings`),r.push(` - ${d(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return r.join(`
|
|
253
253
|
`)}function $(e,t){let n=[];for(let r of H)Z(J[r],e,t)&&n.push(r);return n}function Ze(){return new t(`init`).description(`Scaffold ${n}/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the ${n}/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new e(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).option(`--pin`,"Pin the MCP entry to the absolute path of the current CLI binary instead of `npx`. Use a stable shim like /usr/local/bin/ok for upgrade-safe pinning; npx-cache or worktree paths will go stale on reinstall.").option(`--no-pin`,"Use the default unpinned `npx @inkeep/open-knowledge mcp` MCP entry").action(async e=>{let t=process.cwd(),n;try{n=await Ye({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,pin:e.pin})}catch(e){if(e instanceof o){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
254
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
255
|
-
//# sourceMappingURL=init-
|
|
254
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-j16n7DSe.mjs`),{loadConfig:r}=await import(`./loader-C-9Jcwv3.mjs`),{resolveContentDir:i}=await import(`./paths-D8xkWudL.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o,include:a.content.include,exclude:a.content.exclude})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Xe(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Ue as a,qe as c,Je as i,H as l,Xe as n,Ye as o,Ze as r,Q as s,$ as t,J as u};
|
|
255
|
+
//# sourceMappingURL=init-CD1Q6xzB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./init-CD1Q6xzB.mjs";export{e as runInit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-LlG0LgdL.mjs";export{e as loadConfig};
|