@ours.network/mcp 0.1.0
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/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @ours.network/mcp
|
|
2
|
+
|
|
3
|
+
Agent-agnostic MCP server for **ours** — a native ADAPT node exposing secure
|
|
4
|
+
agent-to-agent messaging tools. It is platform-neutral (no Claude Code / Codex /
|
|
5
|
+
Cursor specifics); per-platform plugins depend on this package and run its
|
|
6
|
+
`proxy` to reach the daemon.
|
|
7
|
+
|
|
8
|
+
The server **is** the node: on startup it boots a single ADAPT packet (a MUFL
|
|
9
|
+
messenger), restores prior state from the state dir, connects to the broker, and
|
|
10
|
+
exposes the messaging tools — each a thin wrapper over one MUFL user transaction:
|
|
11
|
+
|
|
12
|
+
- `generate_invite` — invite to share out-of-band (optionally named)
|
|
13
|
+
- `add_contact` — add a contact from an invite blob (TOFU)
|
|
14
|
+
- `list_contacts`
|
|
15
|
+
- `send_message` — end-to-end encrypted; optional `reply_to_wire_id` (+ `reply_to_sentence`) to reply to a specific message
|
|
16
|
+
- `get_messages` — return unread messages (bodies, each with its `wire_id` + any `reply_to`) + mark read; delivered exactly once
|
|
17
|
+
- `mark_processed` / `defer_messages` — remove handled messages, or re-queue read ones for another session
|
|
18
|
+
- `list_incoming_messages` — full inbox with ids + status (read-only)
|
|
19
|
+
|
|
20
|
+
## Configuration
|
|
21
|
+
|
|
22
|
+
| Env var | Default | Meaning |
|
|
23
|
+
|---------|---------|---------|
|
|
24
|
+
| `OURS_STATE_DIR` | `~/.ours` | Node identity + serialized state. Distinct per node. |
|
|
25
|
+
| `OURS_BROKER_URL` | `ws://ours.network/broker` | The ADAPT broker to connect through. Set to `ws://localhost:9000` for a local broker. |
|
|
26
|
+
|
|
27
|
+
## Daemon lifecycle
|
|
28
|
+
|
|
29
|
+
This package is the **single owner of the daemon lifecycle**. `ours-mcp start`
|
|
30
|
+
runs one long-lived HTTP daemon per host (default port 3030) that hosts every
|
|
31
|
+
identity's packet, the broker socket, and file locks — a shared singleton that
|
|
32
|
+
cannot be run per session. Each session instead runs a thin `ours-mcp proxy`
|
|
33
|
+
(stdio ⇄ the daemon's HTTP endpoint), which auto-starts the daemon if it is down.
|
|
34
|
+
Platform plugins ship only the proxy invocation; they never own or restart the
|
|
35
|
+
daemon.
|
|
36
|
+
|
|
37
|
+
On connect, the proxy runs a compatibility handshake against the daemon's
|
|
38
|
+
`/state-dir` report (`{ version, compat }`). `compat` is the wire-contract
|
|
39
|
+
version (`src/protocol.ts`) — distinct from the package version, bumped only on
|
|
40
|
+
breaking proxy↔daemon changes. Matching `compat` proceeds; a differing package
|
|
41
|
+
version warns (stderr); an incompatible `compat` refuses with guidance to run
|
|
42
|
+
`ours-mcp stop`. The proxy never kills the shared daemon itself, since it may
|
|
43
|
+
be hosting other sessions' identities.
|
|
44
|
+
|
|
45
|
+
## Build
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
npm run build # esbuild → minified dist/{index,cli}.js + dist/mufl_code/*.muflo
|
|
49
|
+
npm run build:dev # readable build (unminified, intact stack traces)
|
|
50
|
+
npm run typecheck
|
|
51
|
+
npm run dev # run the daemon under tsx
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
See the [repo README](https://github.com/adapt-toolkit/ours-mcp#readme) for install
|
|
55
|
+
and quickstart.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
3
|
+
var Ac=Object.defineProperty;var hr=(e,t)=>{for(var r in t)Ac(e,r,{get:t[r],enumerable:!0})};import{spawn as bc,spawnSync as pr}from"node:child_process";import{connect as jd}from"node:net";import{homedir as $c,userInfo as xc}from"node:os";import{resolve as Sc,join as je,dirname as Ao}from"node:path";import{fileURLToPath as Ld,pathToFileURL as Dd}from"node:url";import{createInterface as ur}from"node:readline/promises";import*as Z from"node:fs";import*as de from"node:fs";import{homedir as qo}from"node:os";import{resolve as At,join as Bo,dirname as Vo,basename as Uc}from"node:path";var Ct={brokerUrl:"wss://ours.network/broker",port:3050,stateDir:At(qo(),".ours"),gcIntervalMs:36e5};function Ut(){return process.env.OURS_CONFIG??Bo(qo(),".ours","config.json")}function Nc(){let e;try{e=de.readFileSync(Ut(),"utf8")}catch{return{}}let t;try{t=JSON.parse(e)}catch{return{}}let r={};return typeof t.brokerUrl=="string"&&(r.brokerUrl=t.brokerUrl),typeof t.port=="number"&&Number.isFinite(t.port)&&(r.port=t.port),typeof t.stateDir=="string"&&(r.stateDir=At(t.stateDir)),typeof t.gcIntervalMs=="number"&&Number.isFinite(t.gcIntervalMs)&&(r.gcIntervalMs=t.gcIntervalMs),r}function Fo(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function gr(){let e=Nc();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??Ct.brokerUrl,port:Fo("OURS_PORT")??e.port??Ct.port,stateDir:At(process.env.OURS_STATE_DIR??e.stateDir??Ct.stateDir),gcIntervalMs:Fo("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??Ct.gcIntervalMs}}function Wo(e){let t=Ut();de.mkdirSync(Vo(t),{recursive:!0}),de.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
4
|
+
`,{mode:384});try{de.chmodSync(t,384)}catch{}return t}var Et=".ours-identity";function Nt(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function _r(e){let t=At(e);return Uc(t)===Et?t:Bo(t,Et)}function Jo(e,t,r=!1){let o=Nt(t),n=_r(e);if(!r&&de.existsSync(n))throw new Error(`${n} already exists \u2014 pass overwrite to replace it`);return de.mkdirSync(Vo(n),{recursive:!0}),de.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
5
|
+
`),n}import Ba from"node:process";var zr=Object.freeze({status:"aborted"});function u(e,t,r){function o(c,l){var p;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(p=c._zod).traits??(p.traits=new Set),c._zod.traits.add(e),t(c,l);for(let f in s.prototype)f in c||Object.defineProperty(c,f,{value:s.prototype[f].bind(c)});c._zod.constr=s,c._zod.def=l}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(c){var l;let p=r?.Parent?new i:this;o(p,c),(l=p._zod).deferred??(l.deferred=[]);for(let f of p._zod.deferred)f();return p}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var jc=Symbol("zod_brand"),ye=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},jt={};function ce(e){return e&&Object.assign(jt,e),jt}var T={};hr(T,{BIGINT_FORMAT_RANGES:()=>Ho,Class:()=>vr,NUMBER_FORMAT_RANGES:()=>Pr,aborted:()=>Ze,allowsEval:()=>Sr,assert:()=>qc,assertEqual:()=>Lc,assertIs:()=>Mc,assertNever:()=>Fc,assertNotEqual:()=>Dc,assignProp:()=>$r,cached:()=>ot,captureStackTrace:()=>Dt,cleanEnum:()=>ru,cleanRegex:()=>it,clone:()=>ge,createTransparentProxy:()=>Hc,defineLazy:()=>N,esc:()=>Pe,escapeRegex:()=>Se,extend:()=>Xc,finalizeIssue:()=>_e,floatSafeRemainder:()=>br,getElementAtPath:()=>Bc,getEnumValues:()=>yr,getLengthableOrigin:()=>st,getParsedType:()=>Gc,getSizableOrigin:()=>Ko,isObject:()=>Me,isPlainObject:()=>Fe,issue:()=>Zr,joinValues:()=>Lt,jsonStringifyReplacer:()=>wr,merge:()=>Qc,normalizeParams:()=>b,nullish:()=>nt,numKeys:()=>Jc,omit:()=>Yc,optionalKeys:()=>Rr,partial:()=>eu,pick:()=>Kc,prefixIssues:()=>xe,primitiveTypes:()=>Go,promiseAllObject:()=>Vc,propertyKeyTypes:()=>kr,randomString:()=>Wc,required:()=>tu,stringifyPrimitive:()=>Mt,unwrapMessage:()=>rt});function Lc(e){return e}function Dc(e){return e}function Mc(e){}function Fc(e){throw new Error}function qc(e){}function yr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Lt(e,t="|"){return e.map(r=>Mt(r)).join(t)}function wr(e,t){return typeof t=="bigint"?t.toString():t}function ot(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function nt(e){return e==null}function it(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function br(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}function N(e,t,r){Object.defineProperty(e,t,{get(){{let n=r();return e[t]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function $r(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bc(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function Vc(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function Wc(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Pe(e){return JSON.stringify(e)}var Dt=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Sr=ot(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Fe(e){if(Me(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Me(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Jc(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Gc=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},kr=new Set(["string","number","symbol"]),Go=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Se(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function b(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Hc(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Mt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Rr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Pr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ho={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Kc(e,t){let r={},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(r[n]=o.shape[n])}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Yc(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete r[n]}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Xc(e,t){if(!Fe(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let o={...e._zod.def.shape,...t};return $r(this,"shape",o),o},checks:[]};return ge(e,r)}function Qc(e,t){return ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return $r(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function eu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=e?new e({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=e?new e({type:"optional",innerType:o[i]}):o[i];return ge(t,{...t._zod.def,shape:n,checks:[]})}function tu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new e({type:"nonoptional",innerType:o[i]});return ge(t,{...t._zod.def,shape:n,checks:[]})}function Ze(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function xe(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function rt(e){return typeof e=="string"?e:e?.message}function _e(e,t,r){let o={...e,path:e.path??[]};if(!e.message){let n=rt(e.inst?._zod.def?.error?.(e))??rt(t?.error?.(e))??rt(r.customError?.(e))??rt(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Ko(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function st(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Zr(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function ru(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var vr=class{constructor(...t){}};var Yo=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,wr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ft=u("$ZodError",Yo),Ir=u("$ZodError",Yo,{Parent:Error});function Tr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Or(e,t){let r=t||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>n({issues:c}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(r(s));else{let c=o,l=0;for(;l<s.path.length;){let p=s.path[l];l===s.path.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(r(s))):c[p]=c[p]||{_errors:[]},c=c[p],l++}}};return n(e),o}var Xo=e=>(t,r,o,n)=>{let i=o?Object.assign(o,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ye;if(s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Dt(c,n?.callee),c}return s.value};var Qo=e=>async(t,r,o,n)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Dt(c,n?.callee),c}return s.value};var Cr=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ye;return i.issues.length?{success:!1,error:new(e??Ft)(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},en=Cr(Ir),Er=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},tn=Er(Ir);var rn=/^[cC][^\s-]{8,}$/,on=/^[0-9a-z]+$/,nn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,sn=/^[0-9a-vA-V]{20}$/,an=/^[A-Za-z0-9]{27}$/,cn=/^[a-zA-Z0-9_-]{21}$/,un=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ln=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ar=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var pn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var nu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function dn(){return new RegExp(nu,"u")}var mn=/^(?:(?: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])$/,fn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,hn=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,gn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_n=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ur=/^[A-Za-z0-9_-]*$/,zn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var xn=/^\+(?:[0-9]){6,14}[0-9]$/,vn="(?:(?:\\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])))",yn=new RegExp(`^${vn}$`);function wn(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function bn(e){return new RegExp(`^${wn(e)}$`)}function $n(e){let t=wn({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${vn}T(?:${o})$`)}var Sn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kn=/^\d+n?$/,Rn=/^\d+$/,Pn=/^-?\d+(?:\.\d+)?/i,Zn=/true|false/i,In=/null/i;var Tn=/^[^A-Z]*$/,On=/^[^a-z]*$/;var ie=u("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Cn={number:"number",bigint:"bigint",object:"date"},Nr=u("$ZodCheckLessThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jr=u("$ZodCheckGreaterThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),En=u("$ZodCheckMultipleOf",(e,t)=>{ie.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):br(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),An=u("$ZodCheckNumberFormat",(e,t)=>{ie.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Pr[t.format];e._zod.onattach.push(s=>{let c=s._zod.bag;c.format=t.format,c.minimum=n,c.maximum=i,r&&(c.pattern=Rn)}),e._zod.check=s=>{let c=s.value;if(r){if(!Number.isInteger(c)){s.issues.push({expected:o,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort});return}}c<n&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}});var Un=u("$ZodCheckMaxLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!nt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=st(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Nn=u("$ZodCheckMinLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!nt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=st(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),jn=u("$ZodCheckLengthEquals",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!nt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let s=st(n),c=i>t.length;o.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),at=u("$ZodCheckStringFormat",(e,t)=>{var r,o;ie.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Ln=u("$ZodCheckRegex",(e,t)=>{at.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dn=u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tn),at.init(e,t)}),Mn=u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=On),at.init(e,t)}),Fn=u("$ZodCheckIncludes",(e,t)=>{ie.init(e,t);let r=Se(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qn=u("$ZodCheckStartsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`^${Se(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Bn=u("$ZodCheckEndsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`.*${Se(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Vn=u("$ZodCheckOverwrite",(e,t)=>{ie.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Bt=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
6
|
+
`).filter(s=>s),n=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,n.join(`
|
|
7
|
+
`))}};var Jn={major:4,minor:0,patch:0};var E=u("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jn;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,s,c)=>{let l=Ze(i),p;for(let f of s){if(f._zod.def.when){if(!f._zod.def.when(i))continue}else if(l)continue;let g=i.issues.length,x=f._zod.check(i);if(x instanceof Promise&&c?.async===!1)throw new ye;if(p||x instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await x,i.issues.length!==g&&(l||(l=Ze(i,g)))});else{if(i.issues.length===g)continue;l||(l=Ze(i,g))}}return p?p.then(()=>i):i};e._zod.run=(i,s)=>{let c=e._zod.parse(i,s);if(c instanceof Promise){if(s.async===!1)throw new ye;return c.then(l=>n(l,o,s))}return n(c,o,s)}}e["~standard"]={validate:n=>{try{let i=en(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return tn(e,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Wt=u("$ZodString",(e,t)=>{E.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Sn(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),M=u("$ZodStringFormat",(e,t)=>{at.init(e,t),Wt.init(e,t)}),oi=u("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ln),M.init(e,t)}),ni=u("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ar(o))}else t.pattern??(t.pattern=Ar());M.init(e,t)}),ii=u("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=pn),M.init(e,t)}),si=u("$ZodURL",(e,t)=>{M.init(e,t),e._zod.check=r=>{try{let o=r.value,n=new URL(o),i=n.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:zn.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!o.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ai=u("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=dn()),M.init(e,t)}),ci=u("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=cn),M.init(e,t)}),ui=u("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=rn),M.init(e,t)}),li=u("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=on),M.init(e,t)}),pi=u("$ZodULID",(e,t)=>{t.pattern??(t.pattern=nn),M.init(e,t)}),di=u("$ZodXID",(e,t)=>{t.pattern??(t.pattern=sn),M.init(e,t)}),mi=u("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=an),M.init(e,t)}),fi=u("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=$n(t)),M.init(e,t)}),hi=u("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=yn),M.init(e,t)}),gi=u("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=bn(t)),M.init(e,t)}),_i=u("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=un),M.init(e,t)}),zi=u("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=mn),M.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv4"})}),xi=u("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=fn),M.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),vi=u("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=hn),M.init(e,t)}),yi=u("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=gn),M.init(e,t),e._zod.check=r=>{let[o,n]=r.value.split("/");try{if(!n)throw new Error;let i=Number(n);if(`${i}`!==n)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function wi(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var bi=u("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_n),M.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{wi(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function iu(e){if(!Ur.test(e))return!1;let t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return wi(r)}var $i=u("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ur),M.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{iu(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Si=u("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xn),M.init(e,t)});function su(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}var ki=u("$ZodJWT",(e,t)=>{M.init(e,t),e._zod.check=r=>{su(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Dr=u("$ZodNumber",(e,t)=>{E.init(e,t),e._zod.pattern=e._zod.bag.pattern??Pn,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Ri=u("$ZodNumber",(e,t)=>{An.init(e,t),Dr.init(e,t)}),Pi=u("$ZodBoolean",(e,t)=>{E.init(e,t),e._zod.pattern=Zn,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Zi=u("$ZodBigInt",(e,t)=>{E.init(e,t),e._zod.pattern=kn,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var Ii=u("$ZodNull",(e,t)=>{E.init(e,t),e._zod.pattern=In,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),Ti=u("$ZodAny",(e,t)=>{E.init(e,t),e._zod.parse=r=>r}),Oi=u("$ZodUnknown",(e,t)=>{E.init(e,t),e._zod.parse=r=>r}),Ci=u("$ZodNever",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var Ei=u("$ZodDate",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function Gn(e,t,r){e.issues.length&&t.issues.push(...xe(r,e.issues)),t.value[r]=e.value}var Ai=u("$ZodArray",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let c=n[s],l=t.element._zod.run({value:c,issues:[]},o);l instanceof Promise?i.push(l.then(p=>Gn(p,r,s))):Gn(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Vt(e,t,r){e.issues.length&&t.issues.push(...xe(r,e.issues)),t.value[r]=e.value}function Hn(e,t,r,o){e.issues.length?o[r]===void 0?r in o?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...xe(r,e.issues)):e.value===void 0?r in o&&(t.value[r]=void 0):t.value[r]=e.value}var Ui=u("$ZodObject",(e,t)=>{E.init(e,t);let r=ot(()=>{let g=Object.keys(t.shape);for(let _ of g)if(!(t.shape[_]instanceof E))throw new Error(`Invalid element at key "${_}": expected a Zod schema`);let x=Rr(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(x)}});N(e._zod,"propValues",()=>{let g=t.shape,x={};for(let _ in g){let $=g[_]._zod;if($.values){x[_]??(x[_]=new Set);for(let R of $.values)x[_].add(R)}}return x});let o=g=>{let x=new Bt(["shape","payload","ctx"]),_=r.value,$=A=>{let k=Pe(A);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};x.write("const input = payload.value;");let R=Object.create(null),ne=0;for(let A of _.keys)R[A]=`key_${ne++}`;x.write("const newResult = {}");for(let A of _.keys)if(_.optionalKeys.has(A)){let k=R[A];x.write(`const ${k} = ${$(A)};`);let C=Pe(A);x.write(`
|
|
8
|
+
if (${k}.issues.length) {
|
|
9
|
+
if (input[${C}] === undefined) {
|
|
10
|
+
if (${C} in input) {
|
|
11
|
+
newResult[${C}] = undefined;
|
|
12
|
+
}
|
|
13
|
+
} else {
|
|
14
|
+
payload.issues = payload.issues.concat(
|
|
15
|
+
${k}.issues.map((iss) => ({
|
|
16
|
+
...iss,
|
|
17
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}],
|
|
18
|
+
}))
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
} else if (${k}.value === undefined) {
|
|
22
|
+
if (${C} in input) newResult[${C}] = undefined;
|
|
23
|
+
} else {
|
|
24
|
+
newResult[${C}] = ${k}.value;
|
|
25
|
+
}
|
|
26
|
+
`)}else{let k=R[A];x.write(`const ${k} = ${$(A)};`),x.write(`
|
|
27
|
+
if (${k}.issues.length) payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
28
|
+
...iss,
|
|
29
|
+
path: iss.path ? [${Pe(A)}, ...iss.path] : [${Pe(A)}]
|
|
30
|
+
})));`),x.write(`newResult[${Pe(A)}] = ${k}.value`)}x.write("payload.value = newResult;"),x.write("return payload;");let J=x.compile();return(A,k)=>J(g,A,k)},n,i=Me,s=!jt.jitless,l=s&&Sr.value,p=t.catchall,f;e._zod.parse=(g,x)=>{f??(f=r.value);let _=g.value;if(!i(_))return g.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),g;let $=[];if(s&&l&&x?.async===!1&&x.jitless!==!0)n||(n=o(t.shape)),g=n(g,x);else{g.value={};let k=f.shape;for(let C of f.keys){let v=k[C],z=v._zod.run({value:_[C],issues:[]},x),S=v._zod.optin==="optional"&&v._zod.optout==="optional";z instanceof Promise?$.push(z.then(D=>S?Hn(D,g,C,_):Vt(D,g,C))):S?Hn(z,g,C,_):Vt(z,g,C)}}if(!p)return $.length?Promise.all($).then(()=>g):g;let R=[],ne=f.keySet,J=p._zod,A=J.def.type;for(let k of Object.keys(_)){if(ne.has(k))continue;if(A==="never"){R.push(k);continue}let C=J.run({value:_[k],issues:[]},x);C instanceof Promise?$.push(C.then(v=>Vt(v,g,k))):Vt(C,g,k)}return R.length&&g.issues.push({code:"unrecognized_keys",keys:R,input:_,inst:e}),$.length?Promise.all($).then(()=>g):g}});function Kn(e,t,r,o){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(n=>n.issues.map(i=>_e(i,o,ce())))}),t}var Mr=u("$ZodUnion",(e,t)=>{E.init(e,t),N(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),N(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),N(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),N(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>it(o.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1,i=[];for(let s of t.options){let c=s._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),n=!0;else{if(c.issues.length===0)return c;i.push(c)}}return n?Promise.all(i).then(s=>Kn(s,r,e,o)):Kn(i,r,e,o)}}),Ni=u("$ZodDiscriminatedUnion",(e,t)=>{Mr.init(e,t);let r=e._zod.parse;N(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,l]of Object.entries(s)){n[c]||(n[c]=new Set);for(let p of l)n[c].add(p)}}return n});let o=ot(()=>{let n=t.options,i=new Map;for(let s of n){let c=s._zod.propValues[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of c){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!Me(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let c=o.value.get(s?.[t.discriminator]);return c?c._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),n)}}),ji=u("$ZodIntersection",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,p])=>Yn(r,l,p)):Yn(r,i,s)}});function Lr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Fe(e)&&Fe(t)){let r=Object.keys(t),o=Object.keys(e).filter(i=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=Lr(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=Lr(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Yn(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ze(e))return e;let o=Lr(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Li=u("$ZodRecord",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Fe(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let p=t.valueType._zod.run({value:n[l],issues:[]},o);p instanceof Promise?i.push(p.then(f=>{f.issues.length&&r.issues.push(...xe(l,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...xe(l,p.issues)),r.value[l]=p.value)}let c;for(let l in n)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:c})}else{r.value={};for(let s of Reflect.ownKeys(n)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(p=>_e(p,o,ce())),input:s,path:[s],inst:e}),r.value[c.value]=c.value;continue}let l=t.valueType._zod.run({value:n[s],issues:[]},o);l instanceof Promise?i.push(l.then(p=>{p.issues.length&&r.issues.push(...xe(s,p.issues)),r.value[c.value]=p.value})):(l.issues.length&&r.issues.push(...xe(s,l.issues)),r.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Di=u("$ZodEnum",(e,t)=>{E.init(e,t);let r=yr(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(o=>kr.has(typeof o)).map(o=>typeof o=="string"?Se(o):o.toString()).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;return e._zod.values.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Mi=u("$ZodLiteral",(e,t)=>{E.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Se(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}});var Fi=u("$ZodTransform",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(s=>(r.value=s,r));if(n instanceof Promise)throw new ye;return r.value=n,r}}),qi=u("$ZodOptional",(e,t)=>{E.init(e,t),e._zod.optin="optional",e._zod.optout="optional",N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${it(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,o):r.value===void 0?r:t.innerType._zod.run(r,o)}),Bi=u("$ZodNullable",(e,t)=>{E.init(e,t),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${it(r.source)}|null)$`):void 0}),N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),Vi=u("$ZodDefault",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Xn(i,t)):Xn(n,t)}});function Xn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Wi=u("$ZodPrefault",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),Ji=u("$ZodNonOptional",(e,t)=>{E.init(e,t),N(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Qn(i,e)):Qn(n,e)}});function Qn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Gi=u("$ZodCatch",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>_e(s,o,ce()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(i=>_e(i,o,ce()))},input:r.value}),r.issues=[]),r)}});var Hi=u("$ZodPipe",(e,t)=>{E.init(e,t),N(e._zod,"values",()=>t.in._zod.values),N(e._zod,"optin",()=>t.in._zod.optin),N(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,o)=>{let n=t.in._zod.run(r,o);return n instanceof Promise?n.then(i=>ei(i,t,o)):ei(n,t,o)}});function ei(e,t,r){return Ze(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Ki=u("$ZodReadonly",(e,t)=>{E.init(e,t),N(e._zod,"propValues",()=>t.innerType._zod.propValues),N(e._zod,"values",()=>t.innerType._zod.values),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(ti):ti(n)}});function ti(e){return e.value=Object.freeze(e.value),e}var Yi=u("$ZodCustom",(e,t)=>{ie.init(e,t),E.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(i=>ri(i,r,o,e));ri(n,r,o,e)}});function ri(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),t.issues.push(Zr(n))}}var au=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},cu=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${au(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${Mt(o.values[0])}`:`Invalid option: expected one of ${Lt(o.values,"|")}`;case"too_big":{let n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{let n=o.inclusive?">=":">",i=t(o.origin);return i?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{let n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Lt(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Xi(){return{localeError:cu()}}var uu=Symbol("ZodOutput"),lu=Symbol("ZodInput"),Fr=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let o=r[0];if(this._map.set(t,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let o={...this.get(r)??{}};return delete o.id,{...o,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Qi(){return new Fr}var qe=Qi();function es(e,t){return new e({type:"string",...b(t)})}function ts(e,t){return new e({type:"string",coerce:!0,...b(t)})}function rs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...b(t)})}function qr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...b(t)})}function os(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...b(t)})}function ns(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(t)})}function is(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(t)})}function ss(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(t)})}function Br(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...b(t)})}function as(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...b(t)})}function cs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(t)})}function us(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...b(t)})}function ls(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(t)})}function ps(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...b(t)})}function ds(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...b(t)})}function ms(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(t)})}function fs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(t)})}function hs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(t)})}function gs(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(t)})}function _s(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(t)})}function zs(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...b(t)})}function xs(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...b(t)})}function vs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...b(t)})}function ys(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...b(t)})}function ws(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(t)})}function bs(e,t){return new e({type:"string",format:"date",check:"string_format",...b(t)})}function $s(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...b(t)})}function Ss(e,t){return new e({type:"string",format:"duration",check:"string_format",...b(t)})}function ks(e,t){return new e({type:"number",checks:[],...b(t)})}function Rs(e,t){return new e({type:"number",coerce:!0,checks:[],...b(t)})}function Ps(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...b(t)})}function Zs(e,t){return new e({type:"boolean",...b(t)})}function Is(e,t){return new e({type:"boolean",coerce:!0,...b(t)})}function Ts(e,t){return new e({type:"bigint",coerce:!0,...b(t)})}function Os(e,t){return new e({type:"null",...b(t)})}function Cs(e){return new e({type:"any"})}function Es(e){return new e({type:"unknown"})}function As(e,t){return new e({type:"never",...b(t)})}function Us(e,t){return new e({type:"date",coerce:!0,...b(t)})}function Be(e,t){return new Nr({check:"less_than",...b(t),value:e,inclusive:!1})}function we(e,t){return new Nr({check:"less_than",...b(t),value:e,inclusive:!0})}function Ve(e,t){return new jr({check:"greater_than",...b(t),value:e,inclusive:!1})}function ze(e,t){return new jr({check:"greater_than",...b(t),value:e,inclusive:!0})}function ct(e,t){return new En({check:"multiple_of",...b(t),value:e})}function Jt(e,t){return new Un({check:"max_length",...b(t),maximum:e})}function We(e,t){return new Nn({check:"min_length",...b(t),minimum:e})}function Gt(e,t){return new jn({check:"length_equals",...b(t),length:e})}function Vr(e,t){return new Ln({check:"string_format",format:"regex",...b(t),pattern:e})}function Wr(e){return new Dn({check:"string_format",format:"lowercase",...b(e)})}function Jr(e){return new Mn({check:"string_format",format:"uppercase",...b(e)})}function Gr(e,t){return new Fn({check:"string_format",format:"includes",...b(t),includes:e})}function Hr(e,t){return new qn({check:"string_format",format:"starts_with",...b(t),prefix:e})}function Kr(e,t){return new Bn({check:"string_format",format:"ends_with",...b(t),suffix:e})}function Ie(e){return new Vn({check:"overwrite",tx:e})}function Yr(e){return Ie(t=>t.normalize(e))}function Xr(){return Ie(e=>e.trim())}function Qr(){return Ie(e=>e.toLowerCase())}function eo(){return Ie(e=>e.toUpperCase())}function Ns(e,t,r){return new e({type:"array",element:t,...b(r)})}function js(e,t,r){let o=b(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ls(e,t,r){return new e({type:"custom",check:"custom",fn:t,...b(r)})}var ut={};hr(ut,{ZodISODate:()=>Ms,ZodISODateTime:()=>Ds,ZodISODuration:()=>qs,ZodISOTime:()=>Fs,date:()=>ro,datetime:()=>to,duration:()=>no,time:()=>oo});var Ds=u("ZodISODateTime",(e,t)=>{fi.init(e,t),q.init(e,t)});function to(e){return ws(Ds,e)}var Ms=u("ZodISODate",(e,t)=>{hi.init(e,t),q.init(e,t)});function ro(e){return bs(Ms,e)}var Fs=u("ZodISOTime",(e,t)=>{gi.init(e,t),q.init(e,t)});function oo(e){return $s(Fs,e)}var qs=u("ZodISODuration",(e,t)=>{_i.init(e,t),q.init(e,t)});function no(e){return Ss(qs,e)}var Vs=(e,t)=>{Ft.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Or(e,r)},flatten:{value:r=>Tr(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},Vm=u("ZodError",Vs),lt=u("ZodError",Vs,{Parent:Error});var Ws=Xo(lt),Js=Qo(lt),Gs=Cr(lt),Hs=Er(lt);var j=u("ZodType",(e,t)=>(E.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),e.clone=(r,o)=>ge(e,r,o),e.brand=()=>e,e.register=(r,o)=>(r.add(e,o),e),e.parse=(r,o)=>Ws(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Gs(e,r,o),e.parseAsync=async(r,o)=>Js(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Hs(e,r,o),e.spa=e.safeParseAsync,e.refine=(r,o)=>e.check(nl(r,o)),e.superRefine=r=>e.check(il(r)),e.overwrite=r=>e.check(Ie(r)),e.optional=()=>V(e),e.nullable=()=>Xs(e),e.nullish=()=>V(Xs(e)),e.nonoptional=r=>Yu(e,r),e.array=()=>m(e),e.or=r=>F([e,r]),e.and=r=>Yt(e,r),e.transform=r=>so(e,ca(r)),e.default=r=>Gu(e,r),e.prefault=r=>Ku(e,r),e.catch=r=>Qu(e,r),e.pipe=r=>so(e,r),e.readonly=()=>rl(e),e.describe=r=>{let o=e.clone();return qe.add(o,{description:r}),o},Object.defineProperty(e,"description",{get(){return qe.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return qe.get(e);let o=e.clone();return qe.add(o,r[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Qs=u("_ZodString",(e,t)=>{Wt.init(e,t),j.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...o)=>e.check(Vr(...o)),e.includes=(...o)=>e.check(Gr(...o)),e.startsWith=(...o)=>e.check(Hr(...o)),e.endsWith=(...o)=>e.check(Kr(...o)),e.min=(...o)=>e.check(We(...o)),e.max=(...o)=>e.check(Jt(...o)),e.length=(...o)=>e.check(Gt(...o)),e.nonempty=(...o)=>e.check(We(1,...o)),e.lowercase=o=>e.check(Wr(o)),e.uppercase=o=>e.check(Jr(o)),e.trim=()=>e.check(Xr()),e.normalize=(...o)=>e.check(Yr(...o)),e.toLowerCase=()=>e.check(Qr()),e.toUpperCase=()=>e.check(eo())}),ao=u("ZodString",(e,t)=>{Wt.init(e,t),Qs.init(e,t),e.email=r=>e.check(rs(zu,r)),e.url=r=>e.check(Br(ea,r)),e.jwt=r=>e.check(ys(Cu,r)),e.emoji=r=>e.check(as(xu,r)),e.guid=r=>e.check(qr(Ks,r)),e.uuid=r=>e.check(os(Ht,r)),e.uuidv4=r=>e.check(ns(Ht,r)),e.uuidv6=r=>e.check(is(Ht,r)),e.uuidv7=r=>e.check(ss(Ht,r)),e.nanoid=r=>e.check(cs(vu,r)),e.guid=r=>e.check(qr(Ks,r)),e.cuid=r=>e.check(us(yu,r)),e.cuid2=r=>e.check(ls(wu,r)),e.ulid=r=>e.check(ps(bu,r)),e.base64=r=>e.check(zs(Iu,r)),e.base64url=r=>e.check(xs(Tu,r)),e.xid=r=>e.check(ds($u,r)),e.ksuid=r=>e.check(ms(Su,r)),e.ipv4=r=>e.check(fs(ku,r)),e.ipv6=r=>e.check(hs(Ru,r)),e.cidrv4=r=>e.check(gs(Pu,r)),e.cidrv6=r=>e.check(_s(Zu,r)),e.e164=r=>e.check(vs(Ou,r)),e.datetime=r=>e.check(to(r)),e.date=r=>e.check(ro(r)),e.time=r=>e.check(oo(r)),e.duration=r=>e.check(no(r))});function a(e){return es(ao,e)}var q=u("ZodStringFormat",(e,t)=>{M.init(e,t),Qs.init(e,t)}),zu=u("ZodEmail",(e,t)=>{ii.init(e,t),q.init(e,t)});var Ks=u("ZodGUID",(e,t)=>{oi.init(e,t),q.init(e,t)});var Ht=u("ZodUUID",(e,t)=>{ni.init(e,t),q.init(e,t)});var ea=u("ZodURL",(e,t)=>{si.init(e,t),q.init(e,t)});function ta(e){return Br(ea,e)}var xu=u("ZodEmoji",(e,t)=>{ai.init(e,t),q.init(e,t)});var vu=u("ZodNanoID",(e,t)=>{ci.init(e,t),q.init(e,t)});var yu=u("ZodCUID",(e,t)=>{ui.init(e,t),q.init(e,t)});var wu=u("ZodCUID2",(e,t)=>{li.init(e,t),q.init(e,t)});var bu=u("ZodULID",(e,t)=>{pi.init(e,t),q.init(e,t)});var $u=u("ZodXID",(e,t)=>{di.init(e,t),q.init(e,t)});var Su=u("ZodKSUID",(e,t)=>{mi.init(e,t),q.init(e,t)});var ku=u("ZodIPv4",(e,t)=>{zi.init(e,t),q.init(e,t)});var Ru=u("ZodIPv6",(e,t)=>{xi.init(e,t),q.init(e,t)});var Pu=u("ZodCIDRv4",(e,t)=>{vi.init(e,t),q.init(e,t)});var Zu=u("ZodCIDRv6",(e,t)=>{yi.init(e,t),q.init(e,t)});var Iu=u("ZodBase64",(e,t)=>{bi.init(e,t),q.init(e,t)});var Tu=u("ZodBase64URL",(e,t)=>{$i.init(e,t),q.init(e,t)});var Ou=u("ZodE164",(e,t)=>{Si.init(e,t),q.init(e,t)});var Cu=u("ZodJWT",(e,t)=>{ki.init(e,t),q.init(e,t)});var Kt=u("ZodNumber",(e,t)=>{Dr.init(e,t),j.init(e,t),e.gt=(o,n)=>e.check(Ve(o,n)),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.lt=(o,n)=>e.check(Be(o,n)),e.lte=(o,n)=>e.check(we(o,n)),e.max=(o,n)=>e.check(we(o,n)),e.int=o=>e.check(Ys(o)),e.safe=o=>e.check(Ys(o)),e.positive=o=>e.check(Ve(0,o)),e.nonnegative=o=>e.check(ze(0,o)),e.negative=o=>e.check(Be(0,o)),e.nonpositive=o=>e.check(we(0,o)),e.multipleOf=(o,n)=>e.check(ct(o,n)),e.step=(o,n)=>e.check(ct(o,n)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function I(e){return ks(Kt,e)}var Eu=u("ZodNumberFormat",(e,t)=>{Ri.init(e,t),Kt.init(e,t)});function Ys(e){return Ps(Eu,e)}var co=u("ZodBoolean",(e,t)=>{Pi.init(e,t),j.init(e,t)});function U(e){return Zs(co,e)}var ra=u("ZodBigInt",(e,t)=>{Zi.init(e,t),j.init(e,t),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.gt=(o,n)=>e.check(Ve(o,n)),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.lt=(o,n)=>e.check(Be(o,n)),e.lte=(o,n)=>e.check(we(o,n)),e.max=(o,n)=>e.check(we(o,n)),e.positive=o=>e.check(Ve(BigInt(0),o)),e.negative=o=>e.check(Be(BigInt(0),o)),e.nonpositive=o=>e.check(we(BigInt(0),o)),e.nonnegative=o=>e.check(ze(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(ct(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Au=u("ZodNull",(e,t)=>{Ii.init(e,t),j.init(e,t)});function oa(e){return Os(Au,e)}var Uu=u("ZodAny",(e,t)=>{Ti.init(e,t),j.init(e,t)});function na(){return Cs(Uu)}var Nu=u("ZodUnknown",(e,t)=>{Oi.init(e,t),j.init(e,t)});function B(){return Es(Nu)}var ju=u("ZodNever",(e,t)=>{Ci.init(e,t),j.init(e,t)});function Lu(e){return As(ju,e)}var ia=u("ZodDate",(e,t)=>{Ei.init(e,t),j.init(e,t),e.min=(o,n)=>e.check(ze(o,n)),e.max=(o,n)=>e.check(we(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var Du=u("ZodArray",(e,t)=>{Ai.init(e,t),j.init(e,t),e.element=t.element,e.min=(r,o)=>e.check(We(r,o)),e.nonempty=r=>e.check(We(1,r)),e.max=(r,o)=>e.check(Jt(r,o)),e.length=(r,o)=>e.check(Gt(r,o)),e.unwrap=()=>e.element});function m(e,t){return Ns(Du,e,t)}var sa=u("ZodObject",(e,t)=>{Ui.init(e,t),j.init(e,t),T.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ae(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:B()}),e.loose=()=>e.clone({...e._zod.def,catchall:B()}),e.strict=()=>e.clone({...e._zod.def,catchall:Lu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>T.extend(e,r),e.merge=r=>T.merge(e,r),e.pick=r=>T.pick(e,r),e.omit=r=>T.omit(e,r),e.partial=(...r)=>T.partial(ua,e,r[0]),e.required=(...r)=>T.required(la,e,r[0])});function h(e,t){let r={type:"object",get shape(){return T.assignProp(this,"shape",{...e}),this.shape},...T.normalizeParams(t)};return new sa(r)}function K(e,t){return new sa({type:"object",get shape(){return T.assignProp(this,"shape",{...e}),this.shape},catchall:B(),...T.normalizeParams(t)})}var aa=u("ZodUnion",(e,t)=>{Mr.init(e,t),j.init(e,t),e.options=t.options});function F(e,t){return new aa({type:"union",options:e,...T.normalizeParams(t)})}var Mu=u("ZodDiscriminatedUnion",(e,t)=>{aa.init(e,t),Ni.init(e,t)});function uo(e,t,r){return new Mu({type:"union",options:t,discriminator:e,...T.normalizeParams(r)})}var Fu=u("ZodIntersection",(e,t)=>{ji.init(e,t),j.init(e,t)});function Yt(e,t){return new Fu({type:"intersection",left:e,right:t})}var qu=u("ZodRecord",(e,t)=>{Li.init(e,t),j.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,r){return new qu({type:"record",keyType:e,valueType:t,...T.normalizeParams(r)})}var io=u("ZodEnum",(e,t)=>{Di.init(e,t),j.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new io({...t,checks:[],...T.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new io({...t,checks:[],...T.normalizeParams(n),entries:i})}});function ae(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new io({type:"enum",entries:r,...T.normalizeParams(t)})}var Bu=u("ZodLiteral",(e,t)=>{Mi.init(e,t),j.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function y(e,t){return new Bu({type:"literal",values:Array.isArray(e)?e:[e],...T.normalizeParams(t)})}var Vu=u("ZodTransform",(e,t)=>{Fi.init(e,t),j.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(T.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(T.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ca(e){return new Vu({type:"transform",transform:e})}var ua=u("ZodOptional",(e,t)=>{qi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V(e){return new ua({type:"optional",innerType:e})}var Wu=u("ZodNullable",(e,t)=>{Bi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xs(e){return new Wu({type:"nullable",innerType:e})}var Ju=u("ZodDefault",(e,t)=>{Vi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Gu(e,t){return new Ju({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Hu=u("ZodPrefault",(e,t)=>{Wi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ku(e,t){return new Hu({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var la=u("ZodNonOptional",(e,t)=>{Ji.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yu(e,t){return new la({type:"nonoptional",innerType:e,...T.normalizeParams(t)})}var Xu=u("ZodCatch",(e,t)=>{Gi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qu(e,t){return new Xu({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var el=u("ZodPipe",(e,t)=>{Hi.init(e,t),j.init(e,t),e.in=t.in,e.out=t.out});function so(e,t){return new el({type:"pipe",in:e,out:t})}var tl=u("ZodReadonly",(e,t)=>{Ki.init(e,t),j.init(e,t)});function rl(e){return new tl({type:"readonly",innerType:e})}var pa=u("ZodCustom",(e,t)=>{Yi.init(e,t),j.init(e,t)});function ol(e){let t=new ie({check:"custom"});return t._zod.check=e,t}function da(e,t){return js(pa,e??(()=>!0),t)}function nl(e,t={}){return Ls(pa,e,t)}function il(e){let t=ol(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(T.issue(o,r.value,t._zod.def));else{let n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(T.issue(n))}},e(r.value,r)));return t}function lo(e,t){return so(ca(e),t)}var ma={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Xt={};hr(Xt,{bigint:()=>ul,boolean:()=>cl,date:()=>ll,number:()=>al,string:()=>sl});function sl(e){return ts(ao,e)}function al(e){return Rs(Kt,e)}function cl(e){return Is(co,e)}function ul(e){return Ts(ra,e)}function ll(e){return Us(ia,e)}ce(Xi());var po="2025-11-25";var dl="io.modelcontextprotocol/related-task",er="2.0",Y=da(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ha=F([a(),I().int()]),ga=a(),Df=K({ttl:I().optional(),pollInterval:I().optional()}),ml=h({ttl:I().optional()}),fl=h({taskId:a()}),mo=K({progressToken:ha.optional(),[dl]:fl.optional()}),ue=h({_meta:mo.optional()}),tr=ue.extend({task:ml.optional()});var te=h({method:a(),params:ue.loose().optional()}),me=h({_meta:mo.optional()}),fe=h({method:a(),params:me.loose().optional()}),re=K({_meta:mo.optional()}),rr=F([a(),I().int()]),_a=h({jsonrpc:y(er),id:rr,...te.shape}).strict(),za=e=>_a.safeParse(e).success,hl=h({jsonrpc:y(er),...fe.shape}).strict();var fo=h({jsonrpc:y(er),id:rr,result:re}).strict(),xa=e=>fo.safeParse(e).success;var fa;(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"})(fa||(fa={}));var va=h({jsonrpc:y(er),id:rr.optional(),error:h({code:I().int(),message:a(),data:B().optional()})}).strict();var He=F([_a,hl,fo,va]),Mf=F([fo,va]),ya=re.strict(),gl=me.extend({requestId:rr.optional(),reason:a().optional()}),wa=fe.extend({method:y("notifications/cancelled"),params:gl}),_l=h({src:a(),mimeType:a().optional(),sizes:m(a()).optional(),theme:ae(["light","dark"]).optional()}),pt=h({icons:m(_l).optional()}),Ge=h({name:a(),title:a().optional()}),ba=Ge.extend({...Ge.shape,...pt.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),zl=Yt(h({applyDefaults:U().optional()}),L(a(),B())),xl=lo(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Yt(h({form:zl.optional(),url:Y.optional()}),L(a(),B()).optional())),vl=K({list:Y.optional(),cancel:Y.optional(),requests:K({sampling:K({createMessage:Y.optional()}).optional(),elicitation:K({create:Y.optional()}).optional()}).optional()}),yl=K({list:Y.optional(),cancel:Y.optional(),requests:K({tools:K({call:Y.optional()}).optional()}).optional()}),wl=h({experimental:L(a(),Y).optional(),sampling:h({context:Y.optional(),tools:Y.optional()}).optional(),elicitation:xl.optional(),roots:h({listChanged:U().optional()}).optional(),tasks:vl.optional(),extensions:L(a(),Y).optional()}),bl=ue.extend({protocolVersion:a(),capabilities:wl,clientInfo:ba}),$l=te.extend({method:y("initialize"),params:bl});var Sl=h({experimental:L(a(),Y).optional(),logging:Y.optional(),completions:Y.optional(),prompts:h({listChanged:U().optional()}).optional(),resources:h({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:h({listChanged:U().optional()}).optional(),tasks:yl.optional(),extensions:L(a(),Y).optional()}),kl=re.extend({protocolVersion:a(),capabilities:Sl,serverInfo:ba,instructions:a().optional()}),$a=fe.extend({method:y("notifications/initialized"),params:me.optional()}),Sa=e=>$a.safeParse(e).success,ka=te.extend({method:y("ping"),params:ue.optional()}),Rl=h({progress:I(),total:V(I()),message:V(a())}),Pl=h({...me.shape,...Rl.shape,progressToken:ha}),Ra=fe.extend({method:y("notifications/progress"),params:Pl}),Zl=ue.extend({cursor:ga.optional()}),dt=te.extend({params:Zl.optional()}),mt=re.extend({nextCursor:ga.optional()}),Il=ae(["working","input_required","completed","failed","cancelled"]),ft=h({taskId:a(),status:Il,ttl:F([I(),oa()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:V(I()),statusMessage:V(a())}),Pa=re.extend({task:ft}),Tl=me.merge(ft),Za=fe.extend({method:y("notifications/tasks/status"),params:Tl}),Ia=te.extend({method:y("tasks/get"),params:ue.extend({taskId:a()})}),Ta=re.merge(ft),Oa=te.extend({method:y("tasks/result"),params:ue.extend({taskId:a()})}),Ff=re.loose(),Ca=dt.extend({method:y("tasks/list")}),Ea=mt.extend({tasks:m(ft)}),Aa=te.extend({method:y("tasks/cancel"),params:ue.extend({taskId:a()})}),qf=re.merge(ft),Ua=h({uri:a(),mimeType:V(a()),_meta:L(a(),B()).optional()}),Na=Ua.extend({text:a()}),ho=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ja=Ua.extend({blob:ho}),ht=ae(["user","assistant"]),Ke=h({audience:m(ht).optional(),priority:I().min(0).max(1).optional(),lastModified:ut.datetime({offset:!0}).optional()}),La=h({...Ge.shape,...pt.shape,uri:a(),description:V(a()),mimeType:V(a()),size:V(I()),annotations:Ke.optional(),_meta:V(K({}))}),Ol=h({...Ge.shape,...pt.shape,uriTemplate:a(),description:V(a()),mimeType:V(a()),annotations:Ke.optional(),_meta:V(K({}))}),Cl=dt.extend({method:y("resources/list")}),El=mt.extend({resources:m(La)}),Al=dt.extend({method:y("resources/templates/list")}),Ul=mt.extend({resourceTemplates:m(Ol)}),go=ue.extend({uri:a()}),Nl=go,jl=te.extend({method:y("resources/read"),params:Nl}),Ll=re.extend({contents:m(F([Na,ja]))}),Dl=fe.extend({method:y("notifications/resources/list_changed"),params:me.optional()}),Ml=go,Fl=te.extend({method:y("resources/subscribe"),params:Ml}),ql=go,Bl=te.extend({method:y("resources/unsubscribe"),params:ql}),Vl=me.extend({uri:a()}),Wl=fe.extend({method:y("notifications/resources/updated"),params:Vl}),Jl=h({name:a(),description:V(a()),required:V(U())}),Gl=h({...Ge.shape,...pt.shape,description:V(a()),arguments:V(m(Jl)),_meta:V(K({}))}),Hl=dt.extend({method:y("prompts/list")}),Kl=mt.extend({prompts:m(Gl)}),Yl=ue.extend({name:a(),arguments:L(a(),a()).optional()}),Xl=te.extend({method:y("prompts/get"),params:Yl}),_o=h({type:y("text"),text:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),zo=h({type:y("image"),data:ho,mimeType:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),xo=h({type:y("audio"),data:ho,mimeType:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),Ql=h({type:y("tool_use"),name:a(),id:a(),input:L(a(),B()),_meta:L(a(),B()).optional()}),ep=h({type:y("resource"),resource:F([Na,ja]),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),tp=La.extend({type:y("resource_link")}),vo=F([_o,zo,xo,tp,ep]),rp=h({role:ht,content:vo}),op=re.extend({description:a().optional(),messages:m(rp)}),np=fe.extend({method:y("notifications/prompts/list_changed"),params:me.optional()}),ip=h({title:a().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),sp=h({taskSupport:ae(["required","optional","forbidden"]).optional()}),Da=h({...Ge.shape,...pt.shape,description:a().optional(),inputSchema:h({type:y("object"),properties:L(a(),Y).optional(),required:m(a()).optional()}).catchall(B()),outputSchema:h({type:y("object"),properties:L(a(),Y).optional(),required:m(a()).optional()}).catchall(B()).optional(),annotations:ip.optional(),execution:sp.optional(),_meta:L(a(),B()).optional()}),ap=dt.extend({method:y("tools/list")}),cp=mt.extend({tools:m(Da)}),Ma=re.extend({content:m(vo).default([]),structuredContent:L(a(),B()).optional(),isError:U().optional()}),Bf=Ma.or(re.extend({toolResult:B()})),up=tr.extend({name:a(),arguments:L(a(),B()).optional()}),lp=te.extend({method:y("tools/call"),params:up}),pp=fe.extend({method:y("notifications/tools/list_changed"),params:me.optional()}),Vf=h({autoRefresh:U().default(!0),debounceMs:I().int().nonnegative().default(300)}),Fa=ae(["debug","info","notice","warning","error","critical","alert","emergency"]),dp=ue.extend({level:Fa}),mp=te.extend({method:y("logging/setLevel"),params:dp}),fp=me.extend({level:Fa,logger:a().optional(),data:B()}),hp=fe.extend({method:y("notifications/message"),params:fp}),gp=h({name:a().optional()}),_p=h({hints:m(gp).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),zp=h({mode:ae(["auto","required","none"]).optional()}),xp=h({type:y("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:m(vo).default([]),structuredContent:h({}).loose().optional(),isError:U().optional(),_meta:L(a(),B()).optional()}),vp=uo("type",[_o,zo,xo]),Qt=uo("type",[_o,zo,xo,Ql,xp]),yp=h({role:ht,content:F([Qt,m(Qt)]),_meta:L(a(),B()).optional()}),wp=tr.extend({messages:m(yp),modelPreferences:_p.optional(),systemPrompt:a().optional(),includeContext:ae(["none","thisServer","allServers"]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:m(a()).optional(),metadata:Y.optional(),tools:m(Da).optional(),toolChoice:zp.optional()}),bp=te.extend({method:y("sampling/createMessage"),params:wp}),$p=re.extend({model:a(),stopReason:V(ae(["endTurn","stopSequence","maxTokens"]).or(a())),role:ht,content:vp}),Sp=re.extend({model:a(),stopReason:V(ae(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:ht,content:F([Qt,m(Qt)])}),kp=h({type:y("boolean"),title:a().optional(),description:a().optional(),default:U().optional()}),Rp=h({type:y("string"),title:a().optional(),description:a().optional(),minLength:I().optional(),maxLength:I().optional(),format:ae(["email","uri","date","date-time"]).optional(),default:a().optional()}),Pp=h({type:ae(["number","integer"]),title:a().optional(),description:a().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),Zp=h({type:y("string"),title:a().optional(),description:a().optional(),enum:m(a()),default:a().optional()}),Ip=h({type:y("string"),title:a().optional(),description:a().optional(),oneOf:m(h({const:a(),title:a()})),default:a().optional()}),Tp=h({type:y("string"),title:a().optional(),description:a().optional(),enum:m(a()),enumNames:m(a()).optional(),default:a().optional()}),Op=F([Zp,Ip]),Cp=h({type:y("array"),title:a().optional(),description:a().optional(),minItems:I().optional(),maxItems:I().optional(),items:h({type:y("string"),enum:m(a())}),default:m(a()).optional()}),Ep=h({type:y("array"),title:a().optional(),description:a().optional(),minItems:I().optional(),maxItems:I().optional(),items:h({anyOf:m(h({const:a(),title:a()}))}),default:m(a()).optional()}),Ap=F([Cp,Ep]),Up=F([Tp,Op,Ap]),Np=F([Up,kp,Rp,Pp]),jp=tr.extend({mode:y("form").optional(),message:a(),requestedSchema:h({type:y("object"),properties:L(a(),Np),required:m(a()).optional()})}),Lp=tr.extend({mode:y("url"),message:a(),elicitationId:a(),url:a().url()}),Dp=F([jp,Lp]),Mp=te.extend({method:y("elicitation/create"),params:Dp}),Fp=me.extend({elicitationId:a()}),qp=fe.extend({method:y("notifications/elicitation/complete"),params:Fp}),Bp=re.extend({action:ae(["accept","decline","cancel"]),content:lo(e=>e===null?void 0:e,L(a(),F([a(),I(),U(),m(a())])).optional())}),Vp=h({type:y("ref/resource"),uri:a()});var Wp=h({type:y("ref/prompt"),name:a()}),Jp=ue.extend({ref:F([Wp,Vp]),argument:h({name:a(),value:a()}),context:h({arguments:L(a(),a()).optional()}).optional()}),Gp=te.extend({method:y("completion/complete"),params:Jp});var Hp=re.extend({completion:K({values:m(a()).max(100),total:V(I().int()),hasMore:V(U())})}),Kp=h({uri:a().startsWith("file://"),name:a().optional(),_meta:L(a(),B()).optional()}),Yp=te.extend({method:y("roots/list"),params:ue.optional()}),Xp=re.extend({roots:m(Kp)}),Qp=fe.extend({method:y("notifications/roots/list_changed"),params:me.optional()}),Wf=F([ka,$l,Gp,mp,Xl,Hl,Cl,Al,jl,Fl,Bl,lp,ap,Ia,Oa,Ca,Aa]),Jf=F([wa,Ra,$a,Qp,Za]),Gf=F([ya,$p,Sp,Bp,Xp,Ta,Ea,Pa]),Hf=F([ka,bp,Mp,Yp,Ia,Oa,Ca,Aa]),Kf=F([wa,Ra,hp,Wl,Dl,pp,np,Za,qp]),Yf=F([ya,kl,Hp,op,Kl,El,Ul,Ll,Ma,cp,Ta,Ea,Pa]);var or=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
31
|
+
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),ed(r)}clear(){this._buffer=void 0}};function ed(e){return He.parse(JSON.parse(e))}function qa(e){return JSON.stringify(e)+`
|
|
32
|
+
`}var nr=class{constructor(t=Ba.stdin,r=Ba.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new or,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let o=qa(t);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};function ir(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Va(e=fetch,t){return t?async(r,o)=>{let n={...t,...o,headers:o?.headers?{...ir(t.headers),...ir(o.headers)}:t.headers};return e(r,n)}:e}var yo;yo=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function td(e){return(await yo).getRandomValues(new Uint8Array(e))}async function rd(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let n=await td(e-o.length);for(let i of n)i<r&&(o+=t[i%t.length])}return o}async function od(e){return await rd(e)}async function nd(e){let t=await(await yo).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function wo(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await od(e),r=await nd(t);return{code_verifier:t,code_challenge:r}}var oe=ta().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ma.custom,message:"URL must be parseable",fatal:!0}),zr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ja=K({resource:a().url(),authorization_servers:m(oe).optional(),jwks_uri:a().url().optional(),scopes_supported:m(a()).optional(),bearer_methods_supported:m(a()).optional(),resource_signing_alg_values_supported:m(a()).optional(),resource_name:a().optional(),resource_documentation:a().optional(),resource_policy_uri:a().url().optional(),resource_tos_uri:a().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:m(a()).optional(),dpop_signing_alg_values_supported:m(a()).optional(),dpop_bound_access_tokens_required:U().optional()}),bo=K({issuer:a(),authorization_endpoint:oe,token_endpoint:oe,registration_endpoint:oe.optional(),scopes_supported:m(a()).optional(),response_types_supported:m(a()),response_modes_supported:m(a()).optional(),grant_types_supported:m(a()).optional(),token_endpoint_auth_methods_supported:m(a()).optional(),token_endpoint_auth_signing_alg_values_supported:m(a()).optional(),service_documentation:oe.optional(),revocation_endpoint:oe.optional(),revocation_endpoint_auth_methods_supported:m(a()).optional(),revocation_endpoint_auth_signing_alg_values_supported:m(a()).optional(),introspection_endpoint:a().optional(),introspection_endpoint_auth_methods_supported:m(a()).optional(),introspection_endpoint_auth_signing_alg_values_supported:m(a()).optional(),code_challenge_methods_supported:m(a()).optional(),client_id_metadata_document_supported:U().optional()}),id=K({issuer:a(),authorization_endpoint:oe,token_endpoint:oe,userinfo_endpoint:oe.optional(),jwks_uri:oe,registration_endpoint:oe.optional(),scopes_supported:m(a()).optional(),response_types_supported:m(a()),response_modes_supported:m(a()).optional(),grant_types_supported:m(a()).optional(),acr_values_supported:m(a()).optional(),subject_types_supported:m(a()),id_token_signing_alg_values_supported:m(a()),id_token_encryption_alg_values_supported:m(a()).optional(),id_token_encryption_enc_values_supported:m(a()).optional(),userinfo_signing_alg_values_supported:m(a()).optional(),userinfo_encryption_alg_values_supported:m(a()).optional(),userinfo_encryption_enc_values_supported:m(a()).optional(),request_object_signing_alg_values_supported:m(a()).optional(),request_object_encryption_alg_values_supported:m(a()).optional(),request_object_encryption_enc_values_supported:m(a()).optional(),token_endpoint_auth_methods_supported:m(a()).optional(),token_endpoint_auth_signing_alg_values_supported:m(a()).optional(),display_values_supported:m(a()).optional(),claim_types_supported:m(a()).optional(),claims_supported:m(a()).optional(),service_documentation:a().optional(),claims_locales_supported:m(a()).optional(),ui_locales_supported:m(a()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:oe.optional(),op_tos_uri:oe.optional(),client_id_metadata_document_supported:U().optional()}),Ga=h({...id.shape,...bo.pick({code_challenge_methods_supported:!0}).shape}),Ha=h({access_token:a(),id_token:a().optional(),token_type:a(),expires_in:Xt.number().optional(),scope:a().optional(),refresh_token:a().optional()}).strip(),Ka=h({error:a(),error_description:a().optional(),error_uri:a().optional()}),Wa=oe.optional().or(y("").transform(()=>{})),sd=h({redirect_uris:m(oe),token_endpoint_auth_method:a().optional(),grant_types:m(a()).optional(),response_types:m(a()).optional(),client_name:a().optional(),client_uri:oe.optional(),logo_uri:Wa,scope:a().optional(),contacts:m(a()).optional(),tos_uri:Wa,policy_uri:a().optional(),jwks_uri:oe.optional(),jwks:na().optional(),software_id:a().optional(),software_version:a().optional(),software_statement:a().optional()}).strip(),ad=h({client_id:a(),client_secret:a().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional()}).strip(),Ya=sd.merge(ad),sh=h({error:a(),error_description:a().optional()}).strip(),ah=h({token:a(),token_type_hint:a().optional()}).strip();function Xa(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Qa({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var G=class extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},gt=class extends G{};gt.errorCode="invalid_request";var Te=class extends G{};Te.errorCode="invalid_client";var Oe=class extends G{};Oe.errorCode="invalid_grant";var Ce=class extends G{};Ce.errorCode="unauthorized_client";var _t=class extends G{};_t.errorCode="unsupported_grant_type";var zt=class extends G{};zt.errorCode="invalid_scope";var xt=class extends G{};xt.errorCode="access_denied";var be=class extends G{};be.errorCode="server_error";var vt=class extends G{};vt.errorCode="temporarily_unavailable";var yt=class extends G{};yt.errorCode="unsupported_response_type";var wt=class extends G{};wt.errorCode="unsupported_token_type";var bt=class extends G{};bt.errorCode="invalid_token";var $t=class extends G{};$t.errorCode="method_not_allowed";var St=class extends G{};St.errorCode="too_many_requests";var Ee=class extends G{};Ee.errorCode="invalid_client_metadata";var kt=class extends G{};kt.errorCode="insufficient_scope";var Rt=class extends G{};Rt.errorCode="invalid_target";var ec={[gt.errorCode]:gt,[Te.errorCode]:Te,[Oe.errorCode]:Oe,[Ce.errorCode]:Ce,[_t.errorCode]:_t,[zt.errorCode]:zt,[xt.errorCode]:xt,[be.errorCode]:be,[vt.errorCode]:vt,[yt.errorCode]:yt,[wt.errorCode]:wt,[bt.errorCode]:bt,[$t.errorCode]:$t,[St.errorCode]:St,[Ee.errorCode]:Ee,[kt.errorCode]:kt,[Rt.errorCode]:Rt};var $e=class extends Error{constructor(t){super(t??"Unauthorized")}};function cd(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var $o="code",So="S256";function ud(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&cd(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function ld(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":pd(n,i,r);return;case"client_secret_post":dd(n,i,o);return;case"none":md(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function pd(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function dd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function md(e,t){t.set("client_id",e)}async function rc(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ka.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:s}=o,c=ec[n]||be;return new c(i||"",s)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new be(n)}}async function Pt(e,t){try{return await ko(e,t)}catch(r){if(r instanceof Te||r instanceof Ce)return await e.invalidateCredentials?.("all"),await ko(e,t);if(r instanceof Oe)return await e.invalidateCredentials?.("tokens"),await ko(e,t);throw r}}async function ko(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let s=await e.discoveryState?.(),c,l,p,f=n;if(!f&&s?.resourceMetadataUrl&&(f=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await nc(l,{fetchFn:i}),!c)try{c=await oc(t,{resourceMetadataUrl:f},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let k=await vd(t,{resourceMetadataUrl:f,fetchFn:i});l=k.authorizationServerUrl,p=k.authorizationServerMetadata,c=k.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let g=await hd(t,e,c),x=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,_=await Promise.resolve(e.clientInformation());if(!_){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let k=p?.client_id_metadata_document_supported===!0,C=e.clientMetadataUrl;if(C&&!fd(C))throw new Ee(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${C}`);if(k&&C)_={client_id:C},await e.saveClientInformation?.(_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let z=await Sd(l,{metadata:p,clientMetadata:e.clientMetadata,scope:x,fetchFn:i});await e.saveClientInformation(z),_=z}}let $=!e.redirectUrl;if(r!==void 0||$){let k=await $d(e,l,{metadata:p,resource:g,authorizationCode:r,fetchFn:i});return await e.saveTokens(k),"AUTHORIZED"}let R=await e.tokens();if(R?.refresh_token)try{let k=await bd(l,{metadata:p,clientInformation:_,refreshToken:R.refresh_token,resource:g,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(k),"AUTHORIZED"}catch(k){if(!(!(k instanceof G)||k instanceof be))throw k}let ne=e.state?await e.state():void 0,{authorizationUrl:J,codeVerifier:A}=await yd(l,{metadata:p,clientInformation:_,state:ne,redirectUrl:e.redirectUrl,scope:x,resource:g});return await e.saveCodeVerifier(A),await e.redirectToAuthorization(J),"REDIRECT"}function fd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function hd(e,t,r){let o=Xa(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Qa({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function Po(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Ro(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=Ro(e,"scope")||void 0,c=Ro(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}function Ro(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function oc(e,t,r=fetch){let o=await zd(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Ja.parse(await o.json())}async function Zo(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Zo(e,void 0,r):void 0;throw o}}function gd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tc(e,t,r=fetch){return await Zo(e,{"MCP-Protocol-Version":t},r)}function _d(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function zd(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??po,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=gd(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let c=await tc(s,i,r);if(!o?.metadataUrl&&_d(c,n.pathname)){let l=new URL(`/.well-known/${t}`,n);c=await tc(l,i,r)}return c}function xd(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function nc(e,{fetchFn:t=fetch,protocolVersion:r=po}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=xd(e);for(let{url:i,type:s}of n){let c=await Zo(i,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?bo.parse(await c.json()):Ga.parse(await c.json())}}}async function vd(e,t){let r,o;try{r=await oc(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let n=await nc(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}async function yd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes($o))throw new Error(`Incompatible auth server: does not support response type ${$o}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(So))throw new Error(`Incompatible auth server: does not support code challenge method ${So}`)}else c=new URL("/authorize",e);let l=await wo(),p=l.code_verifier,f=l.code_challenge;return c.searchParams.set("response_type",$o),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",So),c.searchParams.set("redirect_uri",String(o)),i&&c.searchParams.set("state",i),n&&c.searchParams.set("scope",n),n?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}function wd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function ic(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),n)await n(l,r,c,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],g=ud(o,f);ld(g,o,l,r)}let p=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!p.ok)throw await rc(p);return Ha.parse(await p.json())}async function bd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await ic(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:n,fetchFn:s});return{refresh_token:o,...l}}async function $d(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=wd(n,p,e.redirectUrl)}let l=await e.clientInformation();return ic(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function Sd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await rc(s);return Ya.parse(await s.json())}var Zt=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},sc=10,kd=13,Ae=32;function Io(e){}function uc(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Io,onError:r=Io,onRetry:o=Io,onComment:n,maxBufferSize:i}=e,s=[],c=0,l=!0,p,f="",g=0,x,_=!1;function $(v){if(_)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),s.length===0){let D=ne(v);D!==""&&(s.push(D),c=D.length),R();return}if(v.indexOf(`
|
|
33
|
+
`)===-1&&v.indexOf("\r")===-1){s.push(v),c+=v.length,R();return}s.push(v);let z=s.join("");s.length=0,c=0;let S=ne(z);S!==""&&(s.push(S),c=S.length),R()}function R(){i!==void 0&&(c+f.length<=i||(_=!0,s.length=0,c=0,p=void 0,f="",g=0,x=void 0,r(new Zt(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function ne(v){let z=0;if(v.indexOf("\r")===-1){let S=v.indexOf(`
|
|
34
|
+
`,z);for(;S!==-1;){if(z===S){g>0&&t({id:p,event:x,data:f}),p=void 0,f="",g=0,x=void 0,z=S+1,S=v.indexOf(`
|
|
35
|
+
`,z);continue}let D=v.charCodeAt(z);if(ac(v,z,D)){let W=v.charCodeAt(z+5)===Ae?z+6:z+5,se=v.slice(W,S);if(g===0&&v.charCodeAt(S+1)===sc){t({id:p,event:x,data:se}),p=void 0,f="",x=void 0,z=S+2,S=v.indexOf(`
|
|
36
|
+
`,z);continue}f=g===0?se:`${f}
|
|
37
|
+
${se}`,g++}else cc(v,z,D)?x=v.slice(v.charCodeAt(z+6)===Ae?z+7:z+6,S)||void 0:J(v,z,S);z=S+1,S=v.indexOf(`
|
|
38
|
+
`,z)}return v.slice(z)}for(;z<v.length;){let S=v.indexOf("\r",z),D=v.indexOf(`
|
|
39
|
+
`,z),W=-1;if(S!==-1&&D!==-1?W=S<D?S:D:S!==-1?S===v.length-1?W=-1:W=S:D!==-1&&(W=D),W===-1)break;J(v,z,W),z=W+1,v.charCodeAt(z-1)===kd&&v.charCodeAt(z)===sc&&z++}return v.slice(z)}function J(v,z,S){if(z===S){k();return}let D=v.charCodeAt(z);if(ac(v,z,D)){let pe=v.charCodeAt(z+5)===Ae?z+6:z+5,De=v.slice(pe,S);f=g===0?De:`${f}
|
|
40
|
+
${De}`,g++;return}if(cc(v,z,D)){x=v.slice(v.charCodeAt(z+6)===Ae?z+7:z+6,S)||void 0;return}if(D===105&&v.charCodeAt(z+1)===100&&v.charCodeAt(z+2)===58){let pe=v.slice(v.charCodeAt(z+3)===Ae?z+4:z+3,S);p=pe.includes("\0")?void 0:pe;return}if(D===58){if(n){let pe=v.slice(z,S);n(pe.slice(v.charCodeAt(z+1)===Ae?2:1))}return}let W=v.slice(z,S),se=W.indexOf(":");if(se===-1){A(W,"",W);return}let Le=W.slice(0,se),dr=W.charCodeAt(se+1)===Ae?2:1,tt=W.slice(se+dr);A(Le,tt,W)}function A(v,z,S){switch(v){case"event":x=z||void 0;break;case"data":f=g===0?z:`${f}
|
|
41
|
+
${z}`,g++;break;case"id":p=z.includes("\0")?void 0:z;break;case"retry":/^\d+$/.test(z)?o(parseInt(z,10)):r(new Zt(`Invalid \`retry\` value: "${z}"`,{type:"invalid-retry",value:z,line:S}));break;default:r(new Zt(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:z,line:S}));break}}function k(){g>0&&t({id:p,event:x,data:f}),p=void 0,f="",g=0,x=void 0}function C(v={}){if(v.consume&&s.length>0){let z=s.join("");J(z,0,z.length)}l=!0,p=void 0,f="",g=0,x=void 0,s.length=0,c=0,_=!1}return{feed:$,reset:C}}function ac(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function cc(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var sr=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(s){i=uc({onEvent:c=>{s.enqueue(c)},onError(c){typeof t=="function"&&t(c),(t==="terminate"||c.type==="max-buffer-size-exceeded")&&s.error(c)},onRetry:r,onComment:o,maxBufferSize:n})},transform(s){i.feed(s)}})}};var Rd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ke=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},ar=class{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Va(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Rd}async _authThenStart(){if(!this._authProvider)throw new $e("No auth provider");let t;try{t=await Pt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new $e;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(t.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=ir(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new ke(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,t,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,t),n)}_scheduleReconnection(t,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},n)}_handleSseStream(t,r,o){if(!t)return;let{onresumptiontoken:n,replayMessageId:i}=r,s,c=!1,l=!1;(async()=>{try{let f=t.pipeThrough(new TextDecoderStream).pipeThrough(new sr({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){let{value:_,done:$}=await f.read();if($)break;if(_.id&&(s=_.id,c=!0,n?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let R=He.parse(JSON.parse(_.data));xa(R)&&(l=!0,i!==void 0&&(R.id=i)),this.onmessage?.(R)}catch(R){this.onerror?.(R)}}(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(f){if(this.onerror?.(new Error(`SSE stream disconnected: ${f}`)),(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(_){this.onerror?.(new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new $e("No auth provider");if(await Pt(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new $e("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:za(t)?t.id:void 0}).catch(x=>this.onerror?.(x));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),l=c.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!c.ok){let x=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ke(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:$}=Po(c);if(this._resourceMetadataUrl=_,this._scope=$,await Pt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new $e;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:$,error:R}=Po(c);if(R==="insufficient_scope"){let ne=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===ne)throw new ke(403,"Server returned 403 after trying upscoping");if($&&(this._scope=$),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=ne??void 0,await Pt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new $e;return this.send(t)}}throw new ke(c.status,`Error POSTing to endpoint: ${x}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Sa(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(x=>this.onerror?.(x));return}let f=(Array.isArray(t)?t:[t]).filter(x=>"method"in x&&"id"in x&&x.id!==void 0).length>0,g=c.headers.get("content-type");if(f)if(g?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:n},!1);else if(g?.includes("application/json")){let x=await c.json(),_=Array.isArray(x)?x.map($=>He.parse($)):[He.parse(x)];for(let $ of _)this.onmessage?.($)}else throw await c.body?.cancel(),new ke(-1,`Unexpected content type: ${g}`);else await c.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new ke(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function lc(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as Pd,writeFileSync as Zd,readFileSync as Id,readdirSync as Td,statSync as pc,unlinkSync as Od,chmodSync as dc}from"node:fs";import{join as cr}from"node:path";import{homedir as Cd}from"node:os";var Ed="0.1.0",Ad=new Set(["choose_identity","create_identity","create_root_identity"]),mc=e=>new Promise(t=>setTimeout(t,e)),Ud=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,Nd=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,fc=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},hc=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,gc=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function zc(e){let t=new URL(e.url),r=(...w)=>process.stderr.write(`[ours-proxy] ${w.join(" ")}
|
|
42
|
+
`),o=w=>Number.isInteger(w)&&w>1,n=Number(process.env.OURS_CLIENT_PID),i=o(n)?n:o(process.ppid)?process.ppid:process.pid,s=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${i}`,c=null,l=null,p,f=null,g=new Map,x=null,_=gc?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,$=e.stateDir??process.env.OURS_STATE_DIR??cr(Cd(),".ours"),R=cr($,"session-restore"),ne=_&&/^[A-Za-z0-9._-]{1,200}$/.test(_)?_:null,J=ne?cr(R,`${ne}.json`):null,A=!1,k=null;function C(w){if(J)try{Pd(R,{recursive:!0,mode:448}),Zd(J,JSON.stringify({claudeSessionId:_,identity:w,boundAt:new Date().toISOString()}),{mode:384}),dc(R,448),dc(J,384)}catch(P){r("restore persist failed (non-fatal):",String(P))}}function v(){if(!J)return null;try{if(Date.now()-pc(J).mtimeMs>hc)return null;let w=JSON.parse(Id(J,"utf8"));return(typeof w.identity=="string"?w.identity.trim():"")||null}catch{return null}}function z(){try{let w=Date.now();for(let P of Td(R)){if(!P.endsWith(".json"))continue;let O=cr(R,P);try{w-pc(O).mtimeMs>hc&&(Od(O),r("session-restore: pruned expired record",P))}catch{}}}catch{}}let S=null,D=!1,W=!1,se=!1,Le=[],dr="__ours_proxy_init__",tt=0,pe=new Set,De=new Set,Re=new nr;Re.onmessage=w=>{let P=[],O=!1;for(let he of _c(w)){let H=he;if(H.method==="notifications/initialized"&&(O=!0),Ud(H)){if(H.method==="initialize"&&(c=H,l)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Re.send({jsonrpc:"2.0",id:H.id,result:l}).catch(Q=>r("local initialize reply failed:",String(Q)));continue}if(H.method==="tools/call"){let Q=H.params;Q&&Ad.has(Q.name??"")&&typeof Q.arguments?.name=="string"&&g.set(H.id,Q.arguments.name)}}P.push(H)}if(P.length){let he=Array.isArray(w)?P:P[0];No(he)}O&&Tc()},Re.onclose=()=>void mr(0),Re.onerror=w=>r("downstream error:",String(w));function Tc(){if(A||!f)return;A=!0;let w=`__ours_proxy_restore_${++tt}__`;pe.add(w),k=w,r("session-restore: self-recovering bound identity",`"${f}"`),No({jsonrpc:"2.0",id:w,method:"tools/call",params:{name:"choose_identity",arguments:{name:f}}})}function No(w){if(D&&S){let P=S;S.send(w).catch(O=>{r("upstream send failed:",String(O)),Le.push(w),jo(P,"send failed")})}else Le.push(w)}function jo(w,P){if(W||se||S!==null&&w!==S)return;r(`upstream dropped (${P}) \u2014 reconnecting`),D=!1;let O=S;S=null;try{O?.close?.()}catch{}Cc()}function Oc(w){w.onmessage=P=>{let O=[];for(let he of _c(P)){let H=he;if(Nd(H)){let Q=H.id,fr=H.result?.protocolVersion;if(fr&&(De.has(Q)||Lo(Q))){p=fr;try{S?.setProtocolVersion?.(fr)}catch{}if(l==null&&Lo(Q)&&!pe.has(Q)){let ve=H.result??null;ve&&x&&(ve.instructions=`${ve.instructions?ve.instructions+`
|
|
43
|
+
|
|
44
|
+
`:""}${x}`),l=ve}De.delete(Q)}if(pe.has(Q)){pe.delete(Q),Q===k&&(k=null,fc(H)&&(f=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(g.has(Q)){let ve=g.get(Q);g.delete(Q),fc(H)||(f=ve,r("bound identity tracked:",ve),C(ve))}}O.push(H)}if(O.length){let he=Array.isArray(P)?O:O[0];Re.send(he).catch(H=>r("downstream send failed:",String(H)))}},w.onerror=P=>r("upstream error:",String(P)),w.onclose=()=>jo(w,"closed")}let Lo=w=>c!=null&&c.id===w;async function Do(){e.ensureDaemon&&await e.ensureDaemon().catch(P=>r("ensureDaemon:",String(P)));let w=new ar(t,{requestInit:{headers:{"x-ours-lease-token":s,"x-ours-client-pid":String(i)}}});if(Oc(w),await w.start(),p)try{w.setProtocolVersion?.(p)}catch{}S=w}async function Mo(w,P){P&&w.id!==void 0&&pe.add(w.id),await S.send(w)}async function Cc(){if(se||W)return;se=!0;let w=500;for(;;){if(W){se=!1;return}try{if(await Do(),c){let O=`${dr}${tt}`;De.add(O),await Mo({...c,id:O},!0),await S.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(f){let O=`__ours_proxy_rebind_${++tt}__`;await Mo({jsonrpc:"2.0",id:O,method:"tools/call",params:{name:"choose_identity",arguments:{name:f}}},!0)}D=!0;let P=Le.splice(0);for(let O of P)await S.send(O).catch(he=>r("flush failed:",String(he)));r("upstream reconnected",f?`(re-bound "${f}")`:""),se=!1;return}catch(P){r("reconnect attempt failed:",String(P)),await mc(w),w=Math.min(Math.floor(w*1.5),1e4)}}}async function mr(w){if(!W){W=!0;try{await S?.close()}catch{}try{await Re.close()}catch{}process.exit(w)}}process.on("SIGINT",()=>void mr(0)),process.on("SIGTERM",()=>void mr(0));async function Ec(){let w=new URL(t.href);w.pathname="/state-dir";let P;try{P=await(await fetch(w,{signal:AbortSignal.timeout(3e3)})).json()}catch(O){r("compat handshake: could not read daemon /state-dir, proceeding:",String(O));return}x=lc({selfVersion:Ed,daemonVersion:typeof P?.version=="string"?P.version:null}),x&&r(x)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(O=>r("ensureDaemon:",String(O))),await Ec();let w=500;for(;;)try{await Do();break}catch(O){r("initial upstream connect failed, retrying:",String(O)),await mc(w),w=Math.min(Math.floor(w*1.5),1e4)}D=!0;let P=Le.splice(0);for(let O of P)await S.send(O).catch(he=>r("flush failed:",String(he)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),_){z();let w=v();w&&(f=w,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${w}"`))}else gc&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Re.start(),r("proxy started (stdio transport up)")}function _c(e){return Array.isArray(e)?e:[e]}var Uo=gr(),le=Uo.stateDir,ee=Uo.port,Qe=Uo.brokerUrl,Ne=je(le,"daemon.pid"),Ue=je(le,"daemon.log"),et=Ld(import.meta.url),d=(...e)=>process.stdout.write(`${e.join(" ")}
|
|
45
|
+
`),X=(...e)=>process.stderr.write(`${e.join(" ")}
|
|
46
|
+
`),Ye="0.1.0";async function Co(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),o=await fetch(`http://127.0.0.1:${ee}${e}`,{signal:t.signal});if(clearTimeout(r),o.ok){let n=await o.json();if(n&&typeof n.version=="string")return n}}catch{}return null}function vc(e){if(d(` cli: v${Ye}`),e?.version){let t=e.version!==Ye;d(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${Ye}`:""))}else d(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var kc=e=>new Promise(t=>setTimeout(t,e));function Md(){try{let e=parseInt(Z.readFileSync(Ne,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Eo(e){try{return process.kill(e,0),!0}catch{return!1}}function Ot(){let e=Md();if(e&&Eo(e))return e;if(e)try{Z.rmSync(Ne,{force:!0})}catch{}return null}function Tt(e,t=1e3){return new Promise(r=>{let o=jd({host:"127.0.0.1",port:e}),n=i=>{o.destroy(),r(i)};o.setTimeout(t),o.once("connect",()=>n(!0)),o.once("timeout",()=>n(!1)),o.once("error",()=>n(!1))})}async function Rc(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await Tt(e))return!0;await kc(400)}return!1}async function yc(){let e=Ot();if(e){d(`ours-mcp is already running (pid ${e}, port ${ee}).`);return}Z.mkdirSync(le,{recursive:!0});let t=Z.openSync(Ue,"a"),r=bc(process.execPath,[et,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ee),OURS_BROKER_URL:Qe,OURS_STATE_DIR:le}});r.unref(),r.pid||(X("failed to spawn the daemon."),process.exit(1)),Z.writeFileSync(Ne,String(r.pid)),d(`starting ours-mcp (pid ${r.pid})\u2026`),await Rc(ee)?(d(`ours-mcp is up on http://localhost:${ee}/mcp`),d(` broker: ${Qe}`),d(` state: ${le}`),d(` logs: ${Ue}`)):(X(`daemon started (pid ${r.pid}) but port ${ee} did not open within 30s \u2014 check ${Ue}.`),process.exit(1))}async function Fd(){if(!await Tt(ee)){if(!Ot()){Z.mkdirSync(le,{recursive:!0});let e=Z.openSync(Ue,"a"),t=bc(process.execPath,[et,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ee),OURS_BROKER_URL:Qe,OURS_STATE_DIR:le}});if(t.unref(),t.pid)try{Z.writeFileSync(Ne,String(t.pid))}catch{}}await Rc(ee)}}async function lr(){let e=Ot();if(!e){d("ours-mcp is not running.");return}d(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){X(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Eo(e);t++)await kc(200);if(Eo(e)){X(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{Z.rmSync(Ne,{force:!0})}catch{}d("stopped.")}async function qd(){let e=Ot();if(!e){if(await Tt(ee)){let o=await Co();d("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),d(` url: http://localhost:${ee}/mcp (reachable)`),vc(o);return}d("ours-mcp: stopped"),d(` cli: v${Ye}`),process.exitCode=1;return}let t=await Tt(ee),r=t?await Co():null;d("ours-mcp: running"),d(` pid: ${e}`),d(` url: http://localhost:${ee}/mcp ${t?"(reachable)":"(port not answering!)"}`),d(` broker: ${Qe}`),d(` state: ${le}`),d(` logs: ${Ue}`),vc(r)}async function Bd(){if(d(`ours-mcp v${Ye}`),await Tt(ee)){let e=await Co();e?.version?d(`running daemon: v${e.version}`+(e.version!==Ye?" (differs \u2014 restart to update)":"")):d("running daemon: version unknown (predates /version)")}else d("daemon: not running")}async function Vd(){let e=gr(),t=Ut();d(`ours-mcp setup \u2014 ${t}`),d("Enter a value, or press Enter to keep the current [bracketed] one."),d("");let r=ur({input:process.stdin,output:process.stdout}),o;try{let p=async(ne,J)=>{let A=(await r.question(` ${ne} [${J}]: `)).trim();return A===""?J:A},f=await p("broker URL",e.brokerUrl),g=await p("HTTP port",String(e.port)),x=await p("state dir",e.stateDir),_=await p("GC interval (ms)",String(e.gcIntervalMs)),$=parseInt(g,10);(!Number.isFinite($)||$<=0)&&(X(`invalid port: ${g}`),process.exit(1));let R=parseInt(_,10);(!Number.isFinite(R)||R<=0)&&(X(`invalid GC interval: ${_}`),process.exit(1)),o={brokerUrl:f,port:$,stateDir:Sc(x),gcIntervalMs:R}}finally{r.close()}Wo(o),d(""),d(`wrote ${t} (mode 0600):`),d(JSON.stringify(o,null,2));let n=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS"].filter(p=>process.env[p]!==void 0);n.length&&(d(""),d(`note: these env vars are set and OVERRIDE the file at runtime: ${n.join(", ")}`));let i=Ot();if(!i)return;let s=ur({input:process.stdin,output:process.stdout}),c=!1;try{let p=(await s.question(`
|
|
47
|
+
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=p==="y"||p==="yes"}finally{s.close()}if(!c){d("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await lr();let l=pr(process.execPath,[et,"start"],{stdio:"inherit"});l.status!==0&&process.exit(l.status??1)}function To(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Oo(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function Wd(e){let t=Oo(e,"--name"),r=To(e,"--force-bind","--no-force-bind"),o=To(e,"--local-book","--no-local-book"),n=To(e,"--auto-accept-local","--no-auto-accept-local"),i=e.includes("--overwrite"),s=e.includes("--print"),c=Oo(e,"--path")??Oo(e,"--dir")??process.cwd(),l=t!==void 0||r.set||o.set||n.set||s,p;if(l?((!t||!t.trim())&&(X("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),p={name:t.trim(),force:r.value??!1,exposeLocal:o.value??!0,localAutoAccept:n.value??!0}):p=await Jd(),s){d(JSON.stringify(Nt(p),null,2));return}let f=_r(c);if(!i&&Z.existsSync(f)){l&&(X(`define-local-identity-file: ${f} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let x=ur({input:process.stdin,output:process.stdout}),_=!1;try{let $=(await x.question(`
|
|
48
|
+
${f} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();_=$==="y"||$==="yes"}finally{x.close()}if(!_){d("aborted \u2014 nothing written.");return}}let g=Jo(c,p,!0);d(""),d(`wrote ${g}:`),d(JSON.stringify(Nt(p),null,2))}async function Jd(){d("ours-mcp define-local-identity-file \u2014 interactive"),d(`Answer the prompts; the result is written to ${je(process.cwd(),Et)}.`),d("");let e=ur({input:process.stdin,output:process.stdout});try{let t=async(s,c)=>{let l=c?"Y/n":"y/N",p=(await e.question(` ${s} [${l}]: `)).trim().toLowerCase();return p===""?c:p==="y"||p==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||d(" (name is required)");let o=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),n=await t("Add to the host-local contact book?",!0),i=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:o,exposeLocal:n,localAutoAccept:i}}finally{e.close()}}async function Gd(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${ee}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let o=await r.json();if(typeof o.stateDir=="string"&&o.stateDir)return Sc(o.stateDir)}}catch{}return le}async function Hd(e){let t=await Gd(),r=new Map,o=s=>{let c;try{c=Z.readdirSync(t,{withFileTypes:!0}).filter(l=>l.isDirectory()).map(l=>l.name)}catch{return}for(let l of c){if(e&&l!==e)continue;let p=je(t,l,"notifications.log"),f;try{f=Z.statSync(p).size}catch{continue}let g=r.get(p);if(g===void 0&&(g=s?f:0,r.set(p,g),s))continue;if(f<=g){f<g&&r.set(p,f);continue}let x;try{let _=Z.openSync(p,"r"),$=Buffer.alloc(f-g);Z.readSync(_,$,0,$.length,g),Z.closeSync(_),x=$.toString("utf8")}catch{continue}r.set(p,f);for(let _ of x.split(`
|
|
49
|
+
`)){if(!_.trim())continue;let $;try{$=JSON.parse(_)}catch{continue}$.event==="local_contact_request"?d(`[${l}] pending local introduction from ${$.from??"?"} \u2014 respond_to_introduction to approve/reject`):$.event==="pending_message"?d(`[${l}] ${$.from??"?"} queued a message awaiting introduction approval (${$.queued??"?"} queued)`):d(`[${l}] new message from ${$.from??"?"}`+($.msg_id!==void 0?` (#${$.msg_id})`:"")+($.date?` (${$.date})`:""))}}};X(`ours-mcp watch: watching ${e?`identity "${e}"`:"all identities"} under ${t} (Ctrl-C to stop)`),o(!0);let n=setInterval(()=>o(!1),1e3),i=()=>{clearInterval(n),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}var It="ours.service",Pc="solutions.adaptframework.ours";function Zc(){return je($c(),".config","systemd","user",It)}function Ic(){return je($c(),"Library","LaunchAgents",`${Pc}.plist`)}function Xe(e,t){return pr(e,t,{stdio:"inherit"}).status===0}function Kd(){let e=Zc();Z.mkdirSync(Ao(e),{recursive:!0});let t=`[Unit]
|
|
50
|
+
Description=ours MCP daemon (secure agent-to-agent messaging over ADAPT)
|
|
51
|
+
After=network-online.target
|
|
52
|
+
Wants=network-online.target
|
|
53
|
+
|
|
54
|
+
[Service]
|
|
55
|
+
Type=simple
|
|
56
|
+
ExecStart=${process.execPath} ${et} serve
|
|
57
|
+
Environment=OURS_TRANSPORT=http
|
|
58
|
+
Environment=OURS_PORT=${ee}
|
|
59
|
+
Environment=OURS_BROKER_URL=${Qe}
|
|
60
|
+
Environment=OURS_STATE_DIR=${le}
|
|
61
|
+
Restart=on-failure
|
|
62
|
+
RestartSec=2
|
|
63
|
+
|
|
64
|
+
[Install]
|
|
65
|
+
WantedBy=default.target
|
|
66
|
+
`;Z.writeFileSync(e,t),d(`wrote ${e}`),Xe("systemctl",["--user","daemon-reload"]),Xe("systemctl",["--user","enable","--now",It])||(X("failed to enable/start the service via systemctl --user."),process.exit(1)),Xe("loginctl",["enable-linger",xc().username])||(X("warning: could not enable linger \u2014 the daemon may not start until you log in."),X(` run manually: loginctl enable-linger ${xc().username}`)),d(""),d("ours-mcp installed as a systemd user service and started."),d(` status: systemctl --user status ${It}`),d(` logs: journalctl --user -u ${It} -f`),d(" remove: ours-mcp uninstall-service")}function Yd(){Xe("systemctl",["--user","disable","--now",It]);let e=Zc();try{Z.rmSync(e,{force:!0}),d(`removed ${e}`)}catch(t){X(`failed to remove ${e}: ${String(t)}`)}Xe("systemctl",["--user","daemon-reload"]),d("ours-mcp service uninstalled.")}function Xd(){let e=Ic();Z.mkdirSync(Ao(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
|
|
67
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
68
|
+
<plist version="1.0">
|
|
69
|
+
<dict>
|
|
70
|
+
<key>Label</key><string>${Pc}</string>
|
|
71
|
+
<key>ProgramArguments</key>
|
|
72
|
+
<array>
|
|
73
|
+
<string>${process.execPath}</string>
|
|
74
|
+
<string>${et}</string>
|
|
75
|
+
<string>serve</string>
|
|
76
|
+
</array>
|
|
77
|
+
<key>EnvironmentVariables</key>
|
|
78
|
+
<dict>
|
|
79
|
+
<key>OURS_TRANSPORT</key><string>http</string>
|
|
80
|
+
<key>OURS_PORT</key><string>${ee}</string>
|
|
81
|
+
<key>OURS_BROKER_URL</key><string>${Qe}</string>
|
|
82
|
+
<key>OURS_STATE_DIR</key><string>${le}</string>
|
|
83
|
+
</dict>
|
|
84
|
+
<key>RunAtLoad</key><true/>
|
|
85
|
+
<key>KeepAlive</key><true/>
|
|
86
|
+
<key>StandardOutPath</key><string>${Ue}</string>
|
|
87
|
+
<key>StandardErrorPath</key><string>${Ue}</string>
|
|
88
|
+
</dict>
|
|
89
|
+
</plist>
|
|
90
|
+
`;Z.writeFileSync(e,t),d(`wrote ${e}`);let r=`gui/${process.getuid()}`;pr("launchctl",["bootout",r,e],{stdio:"ignore"}),Xe("launchctl",["bootstrap",r,e])||(X("failed to load the launchd agent."),process.exit(1)),d(""),d("ours-mcp installed as a launchd agent and started."),d(" remove: ours-mcp uninstall-service")}function Qd(){let e=Ic(),t=`gui/${process.getuid()}`;pr("launchctl",["bootout",t,e],{stdio:"ignore"});try{Z.rmSync(e,{force:!0}),d(`removed ${e}`)}catch(r){X(`failed to remove ${e}: ${String(r)}`)}d("ours-mcp service uninstalled.")}async function em(){if(await lr(),process.platform==="linux")return Kd();if(process.platform==="darwin")return Xd();X(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function tm(){if(process.platform==="linux")return Yd();if(process.platform==="darwin")return Qd();X(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function wc(){d("ours-mcp \u2014 daemon for the ours MCP server"),d(""),d("Usage: ours-mcp <command>"),d(" start start the daemon in the background"),d(" stop stop the running daemon"),d(" restart stop then start"),d(" status show whether the daemon is running (incl. CLI + running-daemon version)"),d(" version print the CLI version and the running daemon version (GET /version)"),d(" setup interactively edit the config file (broker / port / state dir / gc)"),d(" serve run in the foreground (used by start; handy for debugging)"),d(" watch [identity] stream one line per new inbound message (wake source for a Monitor)"),d(" proxy per-session stdio shim \u2192 daemon (stable binding; for the MCP client config)"),d(""),d(" define-local-identity-file write a .ours-identity workspace pin"),d(" interactive (default): 4-question survey, writes to CWD"),d(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),d(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),d(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),d(""),d(" install-service install + start a boot-persistent service (systemd/launchd)"),d(" uninstall-service stop + remove that service"),d(""),d("Config precedence (per field): env var > config.json > default."),d(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),d(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000)"),d("(install-service bakes the resolved config values into the service definition.)")}async function rm(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),Z.mkdirSync(le,{recursive:!0}),Z.writeFileSync(Ne,String(process.pid));{let t=()=>{try{Z.rmSync(Ne,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(Dd(je(Ao(et),"index.js")).href);break;case"start":await yc();break;case"stop":await lr();break;case"restart":await lr(),await yc();break;case"status":await qd();break;case"version":case"--version":case"-v":await Bd();break;case"setup":await Vd();break;case"define-local-identity-file":await Wd(process.argv.slice(3));break;case"watch":await Hd(process.argv[3]);break;case"proxy":await zc({url:`http://127.0.0.1:${ee}/mcp`,ensureDaemon:Fd,stateDir:le});break;case"install-service":await em();break;case"uninstall-service":tm();break;case"help":case"--help":case"-h":wc();break;default:X(`unknown command: ${e}
|
|
91
|
+
`),wc(),process.exit(1)}}rm().catch(e=>{X(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{basename as e,extname as a}from"node:path";var p={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".html":"text/html",".xml":"application/xml",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime"};function m(i){return p[a(i).toLowerCase()]??"application/octet-stream"}function o(i){let t=e(i).replace(/[^A-Za-z0-9._-]/g,"_");return t.length?t.slice(0,200):"file"}export{m as mimeFromExt,o as sanitizeFilename};
|