opencode-metis 0.1.0 → 0.1.2

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 CHANGED
@@ -21,7 +21,7 @@ Persistent memory system for [OpenCode](https://opencode.ai) sessions. Captures
21
21
  1. Install globally:
22
22
 
23
23
  ```bash
24
- bun add -g @metis/opencode
24
+ bun add -g opencode-metis
25
25
  ```
26
26
 
27
27
  2. Run the setup command from your project root (or any directory):
@@ -34,28 +34,29 @@ Persistent memory system for [OpenCode](https://opencode.ai) sessions. Captures
34
34
 
35
35
  ## CLI
36
36
 
37
- | Command | Description |
38
- |---------|-------------|
39
- | `opencode-metis init` | Configure `opencode.json` and copy framework files |
40
- | `opencode-metis start` | Start the memory worker and launch opencode |
41
- | `opencode-metis stop` | Stop the memory worker |
37
+ | Command | Description |
38
+ | -------------------------- | ------------------------------------------------------------------ |
39
+ | `opencode-metis init` | Configure `opencode.json` and copy framework files |
40
+ | `opencode-metis start` | Start the memory worker and launch opencode |
41
+ | `opencode-metis stop` | Stop the memory worker |
42
+ | `opencode-metis start-mcp` | Start the MCP server (used by opencode via `opencode.json` config) |
42
43
 
43
44
  ## Configuration
44
45
 
45
46
  The memory system has its own optional config file at `~/.config/opencode/memory/settings.json` (separate from OpenCode's config). All fields have sensible defaults:
46
47
 
47
- | Key | Type | Default | Description |
48
- |-----|------|---------|-------------|
49
- | `workerPort` | number | `41777` | HTTP port for the worker daemon |
50
- | `workerBind` | string | `"127.0.0.1"` | Bind address for the worker |
51
- | `chromaDbUrl` | string | `"http://localhost:8000"` | ChromaDB server URL |
52
- | `recencyWindowDays` | number | `90` | Days to boost recent results |
53
- | `retentionDays` | number | `365` | Days before observations expire |
54
- | `tddEnabled` | boolean | `true` | Enforce test-file checks on edit |
55
- | `fileLengthWarn` | number | `300` | Line count warning threshold |
56
- | `fileLengthCritical` | number | `500` | Line count critical threshold |
57
- | `testFilePatterns` | string[] | `["*.test.ts", "*.spec.ts", "*_test.go", "test_*.py"]` | Glob patterns for test files |
58
- | `toolRedirectRules` | array | `[]` | Rules to deny or redirect specific tools |
48
+ | Key | Type | Default | Description |
49
+ | -------------------- | -------- | ------------------------------------------------------ | ---------------------------------------- |
50
+ | `workerPort` | number | `41777` | HTTP port for the worker daemon |
51
+ | `workerBind` | string | `"127.0.0.1"` | Bind address for the worker |
52
+ | `chromaDbUrl` | string | `"http://localhost:8000"` | ChromaDB server URL |
53
+ | `recencyWindowDays` | number | `90` | Days to boost recent results |
54
+ | `retentionDays` | number | `365` | Days before observations expire |
55
+ | `tddEnabled` | boolean | `true` | Enforce test-file checks on edit |
56
+ | `fileLengthWarn` | number | `300` | Line count warning threshold |
57
+ | `fileLengthCritical` | number | `500` | Line count critical threshold |
58
+ | `testFilePatterns` | string[] | `["*.test.ts", "*.spec.ts", "*_test.go", "test_*.py"]` | Glob patterns for test files |
59
+ | `toolRedirectRules` | array | `[]` | Rules to deny or redirect specific tools |
59
60
 
60
61
  ## Architecture
61
62
 
@@ -70,28 +71,28 @@ The system has four components, each built as a separate bundle under `dist/`:
70
71
 
71
72
  Tools available to the AI through the MCP server:
72
73
 
73
- | Tool | Description |
74
- |------|-------------|
75
- | `search` | Semantic or keyword search across observations. Accepts `query`, optional `limit`, `type`, and `project` filters. |
76
- | `timeline` | Chronological context around an observation. Accepts `anchor` (ID, session ID, timestamp, or query) with `depth_before`/`depth_after`. |
77
- | `get_observations` | Fetch full details for specific observation IDs. |
78
- | `save_memory` | Save a new observation with `text`, optional `title` and `project`. |
79
- | `decisions` | Search decision-type observations. Optional `query` and `project` filters. |
80
- | `changes` | Get recent change-type observations. Optional `project` and `limit`. |
74
+ | Tool | Description |
75
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
76
+ | `search` | Semantic or keyword search across observations. Accepts `query`, optional `limit`, `type`, and `project` filters. |
77
+ | `timeline` | Chronological context around an observation. Accepts `anchor` (ID, session ID, timestamp, or query) with `depth_before`/`depth_after`. |
78
+ | `get_observations` | Fetch full details for specific observation IDs. |
79
+ | `save_memory` | Save a new observation with `text`, optional `title` and `project`. |
80
+ | `decisions` | Search decision-type observations. Optional `query` and `project` filters. |
81
+ | `changes` | Get recent change-type observations. Optional `project` and `limit`. |
81
82
 
82
83
  The plugin also registers `memory_search` and `memory_save` as custom tools directly in OpenCode.
83
84
 
84
85
  ## Plugin Hooks
85
86
 
86
- | Hook | Purpose |
87
- |------|---------|
88
- | `session.created` | Injects relevant memory context at session start |
89
- | `tool.execute.before` | Enforces tool redirect rules (deny/redirect) before execution |
90
- | `tool.execute.after` | Captures tool executions as observations |
91
- | `session.idle` | Saves session summaries when the session goes idle |
92
- | `experimental.session.compacting` | Saves active plan and task state before compaction |
93
- | `session.compacted` | Restores memory context after compaction |
94
- | `file.edited` | Checks for missing test files and warns on file length |
87
+ | Hook | Purpose |
88
+ | --------------------------------- | ------------------------------------------------------------- |
89
+ | `session.created` | Injects relevant memory context at session start |
90
+ | `tool.execute.before` | Enforces tool redirect rules (deny/redirect) before execution |
91
+ | `tool.execute.after` | Captures tool executions as observations |
92
+ | `session.idle` | Saves session summaries when the session goes idle |
93
+ | `experimental.session.compacting` | Saves active plan and task state before compaction |
94
+ | `session.compacted` | Restores memory context after compaction |
95
+ | `file.edited` | Checks for missing test files and warns on file length |
95
96
 
96
97
  ## Local Development
97
98
 
@@ -110,10 +111,11 @@ Then add the MCP server to `~/.config/opencode/opencode.json` (no `plugin` entry
110
111
  ```json
111
112
  {
112
113
  "$schema": "https://opencode.ai/config.json",
114
+ "plugin": ["opencode-metis"],
113
115
  "mcp": {
114
116
  "mem-search": {
115
117
  "type": "local",
116
- "command": ["bun", "run", "/absolute/path/to/opencode-metis/dist/mcp-server.cjs"]
118
+ "command": ["opencode-metis", "start-mcp"]
117
119
  }
118
120
  }
119
121
  }
package/dist/cli.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  "use strict";var kS=Object.create;var Lu=Object.defineProperty;var SS=Object.getOwnPropertyDescriptor;var PS=Object.getOwnPropertyNames;var ES=Object.getPrototypeOf,zS=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),yn=(t,e)=>{for(var r in e)Lu(t,r,{get:e[r],enumerable:!0})},TS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of PS(e))!zS.call(t,o)&&o!==r&&Lu(t,o,{get:()=>e[o],enumerable:!(n=SS(e,o))||n.enumerable});return t};var Uu=(t,e,r)=>(r=t!=null?kS(ES(t)):{},TS(e||!t||!t.__esModule?Lu(r,"default",{value:t,enumerable:!0}):r,t));async function ps(t,e={}){let r=e.defaultYes??!0,n=e.input??process.stdin,o=r?"Y/n":"y/N",s=(0,Wg.createInterface)({input:n,output:process.stdout});return new Promise(i=>{s.question(`${Yg}?${vn} ${t} [${o}] `,a=>{s.close();let c=a.trim().toLowerCase();if(c===""){i(r);return}i(c==="y"||c==="yes")})})}function Ge(t){console.log(`${Yg}=>${vn} ${t}`)}function rt(t){console.log(`${RS}ok${vn} ${t}`)}function Cr(t){console.log(`${IS}!!${vn} ${t}`)}function lt(t){console.error(`${OS}error${vn} ${t}`)}function de(t){console.log(`${jS}${t}${vn}`)}function Ar(t){console.log(`
3
- ${NS}${t}${vn}`)}var Wg,_n,vn,RS,IS,OS,Yg,NS,jS,fs=x(()=>{"use strict";Wg=require("readline"),_n=process.stdout.isTTY===!0,vn=_n?"\x1B[0m":"",RS=_n?"\x1B[32m":"",IS=_n?"\x1B[33m":"",OS=_n?"\x1B[31m":"",Yg=_n?"\x1B[36m":"",NS=_n?"\x1B[1m":"",jS=_n?"\x1B[2m":""});var Vu,or,sr,ms,ir,$n,Pt,CS,AS,hs,Xg,HD,Fu,KD,BD,GD,bn=x(()=>{"use strict";Vu=require("os"),or=require("path"),sr=41777,ms="127.0.0.1",ir=(0,or.join)((0,Vu.homedir)(),".config","opencode"),$n=(0,or.join)(ir,"opencode.json"),Pt=(0,or.join)((0,Vu.homedir)(),".config","opencode","memory"),CS="memory.db",AS="settings.json",hs=(0,or.join)(Pt,"worker.pid"),Xg=10,HD=(0,or.join)(Pt,CS),Fu=(0,or.join)(Pt,AS),KD=(0,or.join)(Pt,"logs"),BD=(0,or.join)(Pt,"models"),GD=(0,or.join)(Pt,"vector-db")});function ey(){let t=(0,Ut.dirname)(__filename);for(;t!==(0,Ut.dirname)(t);){if((0,gs.existsSync)((0,Ut.join)(t,"package.json")))return t;t=(0,Ut.dirname)(t)}return(0,Ut.dirname)(__filename)}function ty(){return(0,Ut.join)(ey(),"dist","worker.cjs")}function ry(){return(0,Ut.join)(ey(),"opencode")}function ta(){if(process.execPath.endsWith("bun"))return process.execPath;try{let n=(0,Qg.execSync)("which bun",{encoding:"utf-8"}).trim();if(n.length>0&&(0,gs.existsSync)(n))return n}catch{}let t=process.env.HOME??"",e=(0,Ut.join)(t,".bun","bin","bun");if((0,gs.existsSync)(e))return e;let r=process.env.BUN_INSTALL??"";if(r.length>0){let n=(0,Ut.join)(r,"bin","bun");if((0,gs.existsSync)(n))return n}return null}var Ut,gs,Qg,ra=x(()=>{"use strict";Ut=require("path"),gs=require("fs"),Qg=require("child_process")});function MS(t){try{return(0,ny.execSync)(`"${t}" --version`,{encoding:"utf-8"}).trim().match(/(\d+\.\d+\.\d+)/)?.[1]??null}catch{return null}}function ZS(t,e){let[r=0,n=0,o=0]=t.split(".").map(Number),[s=0,i=0,a=0]=e.split(".").map(Number);return r!==s?r>s:n!==i?n>i:o>=a}function qS(t){try{return(0,po.mkdirSync)(t,{recursive:!0}),(0,po.accessSync)(t,po.constants.W_OK),!0}catch{return!1}}function oy(){let t=[],e=ta();if(e===null)return t.push("bun not found. Install from https://bun.sh"),{passed:!1,bunPath:"",errors:t};let r=MS(e);return r===null?t.push("Could not determine bun version"):ZS(r,"1.0.0")||t.push(`bun ${r} is too old, need >= 1.0.0`),qS(ir)||t.push(`Cannot write to ${ir}`),{passed:t.length===0,bunPath:e,errors:t}}var po,ny,sy=x(()=>{"use strict";po=require("fs"),ny=require("child_process");bn();ra()});function na(t){if(!(0,Ce.existsSync)(t))return{};let e=(0,Ce.readFileSync)(t,"utf-8");return JSON.parse(e)}function iy(t,e){return Array.isArray(t.plugin)?t.plugin.some(r=>r.name===e):!1}function ay(t,e){return t.mcp===void 0||t.mcp===null?!1:Object.prototype.hasOwnProperty.call(t.mcp,e)}function cy(t){try{let e=na(t);return iy(e,"opencode-metis")}catch{return!1}}function uy(t){try{let e=na(t);return ay(e,"mem-search")}catch{return!1}}function ly(t){if(!(0,Ce.existsSync)(t))return null;let e=(0,Mr.dirname)(t),r=(0,Mr.join)(e,"backups");(0,Ce.mkdirSync)(r,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-"),o=(0,Mr.join)(r,`opencode.${n}.json`);return(0,Ce.copyFileSync)(t,o),DS(r),o}function DS(t){let e=(0,Ce.readdirSync)(t).filter(r=>r.startsWith("opencode.")&&r.endsWith(".json")).sort();for(;e.length>Xg;){let r=e.shift();r!==void 0&&(0,Ce.unlinkSync)((0,Mr.join)(t,r))}}function dy(t,e){let r=`${t}.tmp.${process.pid}`;(0,Ce.writeFileSync)(r,e,"utf-8"),(0,Ce.renameSync)(r,t)}function py(t){let e=na(t);if(iy(e,"opencode-metis"))return{added:!1,backupPath:null};let r=ly(t);return Array.isArray(e.plugin)||(e.plugin=[]),e.plugin.push({name:"opencode-metis"}),(0,Ce.mkdirSync)((0,Mr.dirname)(t),{recursive:!0}),dy(t,JSON.stringify(e,null,2)+`
3
+ ${NS}${t}${vn}`)}var Wg,_n,vn,RS,IS,OS,Yg,NS,jS,fs=x(()=>{"use strict";Wg=require("readline"),_n=process.stdout.isTTY===!0,vn=_n?"\x1B[0m":"",RS=_n?"\x1B[32m":"",IS=_n?"\x1B[33m":"",OS=_n?"\x1B[31m":"",Yg=_n?"\x1B[36m":"",NS=_n?"\x1B[1m":"",jS=_n?"\x1B[2m":""});var Vu,or,sr,ms,ir,$n,Pt,CS,AS,hs,Xg,HD,Fu,KD,BD,GD,bn=x(()=>{"use strict";Vu=require("os"),or=require("path"),sr=41777,ms="127.0.0.1",ir=(0,or.join)((0,Vu.homedir)(),".config","opencode"),$n=(0,or.join)(ir,"opencode.json"),Pt=(0,or.join)((0,Vu.homedir)(),".config","opencode","memory"),CS="memory.db",AS="settings.json",hs=(0,or.join)(Pt,"worker.pid"),Xg=10,HD=(0,or.join)(Pt,CS),Fu=(0,or.join)(Pt,AS),KD=(0,or.join)(Pt,"logs"),BD=(0,or.join)(Pt,"models"),GD=(0,or.join)(Pt,"vector-db")});function ey(){let t=(0,Ut.dirname)(__filename);for(;t!==(0,Ut.dirname)(t);){if((0,gs.existsSync)((0,Ut.join)(t,"package.json")))return t;t=(0,Ut.dirname)(t)}return(0,Ut.dirname)(__filename)}function ty(){return(0,Ut.join)(ey(),"dist","worker.cjs")}function ry(){return(0,Ut.join)(ey(),"opencode")}function ta(){if(process.execPath.endsWith("bun"))return process.execPath;try{let n=(0,Qg.execSync)("which bun",{encoding:"utf-8"}).trim();if(n.length>0&&(0,gs.existsSync)(n))return n}catch{}let t=process.env.HOME??"",e=(0,Ut.join)(t,".bun","bin","bun");if((0,gs.existsSync)(e))return e;let r=process.env.BUN_INSTALL??"";if(r.length>0){let n=(0,Ut.join)(r,"bin","bun");if((0,gs.existsSync)(n))return n}return null}var Ut,gs,Qg,ra=x(()=>{"use strict";Ut=require("path"),gs=require("fs"),Qg=require("child_process")});function MS(t){try{return(0,ny.execSync)(`"${t}" --version`,{encoding:"utf-8"}).trim().match(/(\d+\.\d+\.\d+)/)?.[1]??null}catch{return null}}function ZS(t,e){let[r=0,n=0,o=0]=t.split(".").map(Number),[s=0,i=0,a=0]=e.split(".").map(Number);return r!==s?r>s:n!==i?n>i:o>=a}function qS(t){try{return(0,po.mkdirSync)(t,{recursive:!0}),(0,po.accessSync)(t,po.constants.W_OK),!0}catch{return!1}}function oy(){let t=[],e=ta();if(e===null)return t.push("bun not found. Install from https://bun.sh"),{passed:!1,bunPath:"",errors:t};let r=MS(e);return r===null?t.push("Could not determine bun version"):ZS(r,"1.0.0")||t.push(`bun ${r} is too old, need >= 1.0.0`),qS(ir)||t.push(`Cannot write to ${ir}`),{passed:t.length===0,bunPath:e,errors:t}}var po,ny,sy=x(()=>{"use strict";po=require("fs"),ny=require("child_process");bn();ra()});function na(t){if(!(0,Ce.existsSync)(t))return{};let e=(0,Ce.readFileSync)(t,"utf-8");return JSON.parse(e)}function iy(t,e){return Array.isArray(t.plugin)?t.plugin.some(r=>r===e||typeof r=="object"&&r!==null&&r.name===e):!1}function ay(t,e){return t.mcp===void 0||t.mcp===null?!1:Object.prototype.hasOwnProperty.call(t.mcp,e)}function cy(t){try{let e=na(t);return iy(e,"opencode-metis")}catch{return!1}}function uy(t){try{let e=na(t);return ay(e,"mem-search")}catch{return!1}}function ly(t){if(!(0,Ce.existsSync)(t))return null;let e=(0,Mr.dirname)(t),r=(0,Mr.join)(e,"backups");(0,Ce.mkdirSync)(r,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-"),o=(0,Mr.join)(r,`opencode.${n}.json`);return(0,Ce.copyFileSync)(t,o),DS(r),o}function DS(t){let e=(0,Ce.readdirSync)(t).filter(r=>r.startsWith("opencode.")&&r.endsWith(".json")).sort();for(;e.length>Xg;){let r=e.shift();r!==void 0&&(0,Ce.unlinkSync)((0,Mr.join)(t,r))}}function dy(t,e){let r=`${t}.tmp.${process.pid}`;(0,Ce.writeFileSync)(r,e,"utf-8"),(0,Ce.renameSync)(r,t)}function py(t){let e=na(t);if(iy(e,"opencode-metis"))return{added:!1,backupPath:null};let r=ly(t);return Array.isArray(e.plugin)||(e.plugin=[]),e.plugin.push("opencode-metis"),(0,Ce.mkdirSync)((0,Mr.dirname)(t),{recursive:!0}),dy(t,JSON.stringify(e,null,2)+`
4
4
  `),{added:!0,backupPath:r}}function fy(t){let e=na(t);if(ay(e,"mem-search"))return{added:!1,backupPath:null};let r=ly(t);return(e.mcp===void 0||e.mcp===null)&&(e.mcp={}),e.mcp["mem-search"]={type:"local",command:["opencode-metis","start-mcp"]},(0,Ce.mkdirSync)((0,Mr.dirname)(t),{recursive:!0}),dy(t,JSON.stringify(e,null,2)+`
5
5
  `),{added:!0,backupPath:r}}var Ce,Mr,my=x(()=>{"use strict";Ce=require("fs"),Mr=require("path");bn()});function hy(t,e,r){let n=(0,Hu.join)(t,r);if(!(0,Zr.existsSync)(n))return!1;(0,Zr.mkdirSync)(e,{recursive:!0});let o=(0,Hu.join)(e,r);return(0,Zr.rmSync)(o,{recursive:!0,force:!0}),(0,Zr.cpSync)(n,o,{recursive:!0}),!0}var Zr,Hu,oa,gy=x(()=>{"use strict";Zr=require("fs"),Hu=require("path"),oa=["agent","command","skill"]});var _y={};yn(_y,{runInit:()=>FS});async function LS(){try{let t=new AbortController,e=setTimeout(()=>t.abort(),3e3),r=await fetch("http://localhost:8000/api/v1/heartbeat",{signal:t.signal});return clearTimeout(e),r.ok}catch{return!1}}async function US(){let t=ry(),e=(0,Vt.existsSync)(ir)&&(0,Vt.existsSync)(Pt),r=cy($n),n=uy($n),o={};for(let i of oa)o[i]=(0,Vt.existsSync)(`${ir}/${i}`);let s=await LS();return{opencodeDir:t,dirsExist:e,pluginConfigured:r,mcpConfigured:n,frameworkDirsExist:o,chromaReachable:s}}function yy(t){return t?" (already configured)":""}function VS(t){return t?" (will overwrite)":""}async function FS(){Ar("opencode-metis init"),Ge("Checking prerequisites...");let t=oy();if(!t.passed){for(let c of t.errors)lt(c);process.exit(1)}rt(`bun found at ${t.bunPath}`),Ge("Detecting current state...");let e=await US();e.chromaReachable?de(" ChromaDB is reachable at localhost:8000"):de(" ChromaDB not reachable \u2014 vector search will be disabled until it's running"),Ar("Select actions to run:"),de("");let r=await ps(`Create config directories${e.dirsExist?" (already exist)":""}`,{defaultYes:!e.dirsExist}),n=await ps(`Add opencode-metis plugin to opencode.json${yy(e.pluginConfigured)}`,{defaultYes:!e.pluginConfigured}),o=await ps(`Add mem-search MCP server to opencode.json${yy(e.mcpConfigured)}`,{defaultYes:!e.mcpConfigured}),s=(0,Vt.existsSync)(e.opencodeDir),i={};if(s)for(let c of oa)(0,Vt.existsSync)(`${e.opencodeDir}/${c}`)&&(i[c]=await ps(`Copy ${c} files to ${ir}/${c}${VS(e.frameworkDirsExist[c]??!1)}`,{defaultYes:!0}));de("");let a=0;if(r&&(Ge("Creating directories..."),(0,Vt.mkdirSync)(ir,{recursive:!0}),(0,Vt.mkdirSync)(Pt,{recursive:!0}),rt("Directories ready"),a++),n){Ge("Adding opencode-metis plugin...");let c=py($n);c.backupPath!==null&&de(` Backup: ${c.backupPath}`),c.added?rt("Added opencode-metis plugin"):de(" Plugin already present \u2014 skipped"),a++}if(o){Ge("Adding mem-search MCP server...");let c=fy($n);c.backupPath!==null&&de(` Backup: ${c.backupPath}`),c.added?rt("Added mem-search MCP server"):de(" MCP server already present \u2014 skipped"),a++}if(n||o){Ge("Verifying opencode.json...");try{let c=(0,Vt.readFileSync)($n,"utf-8");JSON.parse(c),rt("opencode.json is valid JSON")}catch{lt("opencode.json is not valid JSON \u2014 please check manually"),process.exit(1)}}if(s)for(let c of oa){if(!i[c])continue;Ge(`Copying ${c} files...`),hy(e.opencodeDir,ir,c)?rt(`Copied ${c}`):Cr(`${c} not found in package \u2014 skipped`),a++}else Object.keys(i).length===0&&de(" Framework files not found in package \u2014 skipping copy");a===0?(de(""),de("No actions selected \u2014 nothing changed.")):(Ar("Setup complete"),de(` Config: ${$n}`),de(` Data: ${Pt}`),de(` Worker: port ${sr}`)),de(""),de("Next steps:"),de(" opencode-metis start Start the worker and launch opencode"),de(" opencode-metis stop Stop the worker")}var Vt,vy=x(()=>{"use strict";Vt=require("fs");fs();sy();ra();my();gy();bn()});function $y(t){(0,qr.writeFileSync)(hs,String(t),"utf-8")}function sa(){if(!(0,qr.existsSync)(hs))return null;try{let t=(0,qr.readFileSync)(hs,"utf-8").trim(),e=parseInt(t,10);return Number.isNaN(e)?null:e}catch{return null}}function ys(){try{(0,qr.unlinkSync)(hs)}catch{}}function _s(t){try{return process.kill(t,0),!0}catch{return!1}}async function vs(t){let e=t??sr;try{let r=new AbortController,n=setTimeout(()=>r.abort(),2e3),o=await fetch(`http://${ms}:${e}/api/health`,{signal:r.signal});return clearTimeout(n),o.ok}catch{return!1}}async function by(t,e=1e4){let r=t??sr,n=Date.now(),o=250;for(;Date.now()-n<e;){if(await vs(r))return!0;await new Promise(s=>setTimeout(s,o))}return!1}async function wy(t){let e=t??sr;try{let r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await fetch(`http://${ms}:${e}/api/admin/shutdown`,{method:"POST",signal:r.signal});return clearTimeout(n),o.ok}catch{return!1}}function xy(t){try{return process.kill(t,"SIGTERM"),!0}catch{return!1}}async function ia(t,e=5e3){let r=Date.now(),n=250;for(;Date.now()-r<e;){if(!_s(t))return!0;await new Promise(o=>setTimeout(o,n))}return!1}function ky(t){try{process.kill(t,"SIGKILL")}catch{}}var qr,Ku=x(()=>{"use strict";qr=require("fs");bn()});var Ey={};yn(Ey,{runStart:()=>HS});async function HS(){Ar("opencode-metis start");let t=sa();if(t!==null&&_s(t)){if(await vs()){rt(`Worker already running (pid ${t})`),Sy();return}Cr(`Worker process ${t} exists but is not healthy \u2014 restarting`)}let e=ta();e===null&&(lt("bun not found. Run 'opencode-metis init' first."),process.exit(1));let r=ty();Ge("Starting worker..."),(0,Py.mkdirSync)(Pt,{recursive:!0});let n=(0,Bu.spawn)(e,[r],{detached:!0,stdio:"ignore",env:{...process.env}});n.pid===void 0&&(lt("Failed to spawn worker process"),process.exit(1)),$y(n.pid),n.unref(),de(` Worker pid: ${n.pid}`),Ge("Waiting for worker to become healthy..."),await by(sr,1e4)||(lt("Worker did not become healthy within 10 seconds"),de(" Check logs or run 'opencode-metis stop' and try again"),process.exit(1)),rt("Worker is healthy"),Sy()}function Sy(){Ge("Launching opencode...");try{let t=(0,Bu.spawn)("opencode",[],{stdio:"inherit"});t.on("error",e=>{lt(`Failed to launch opencode: ${e.message}`),de(" Make sure opencode is installed and on your PATH"),process.exit(1)}),t.on("exit",e=>{process.exit(e??0)})}catch(t){lt(`Failed to launch opencode: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}}var Bu,Py,zy=x(()=>{"use strict";Bu=require("child_process"),Py=require("fs");fs();ra();Ku();bn()});var Ty={};yn(Ty,{runStop:()=>KS});async function KS(){Ar("opencode-metis stop");let t=sa(),e=await vs();if(t===null&&!e){Cr("No worker found (no PID file and health check failed)");return}if(e)if(Ge("Sending shutdown request via API..."),await wy())if(rt("Shutdown request accepted"),t!==null){if(Ge("Waiting for process to exit..."),await ia(t)){rt("Worker stopped"),ys();return}Cr("Process did not exit in time \u2014 sending SIGTERM")}else{ys();return}else de(" API shutdown failed \u2014 falling back to signal");if(t!==null&&_s(t)){if(Ge("Sending SIGTERM..."),xy(t),await ia(t)){rt("Worker stopped"),ys();return}Cr("Process did not exit after SIGTERM \u2014 sending SIGKILL"),ky(t),await ia(t,2e3)?rt("Worker killed"):lt(`Could not stop worker (pid ${t})`)}ys()}var Ry=x(()=>{"use strict";fs();Ku()});function b(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function xt(t){return t&&Object.assign(aa,t),aa}var BS,br,aa,fo=x(()=>{BS=Object.freeze({status:"aborted"});br=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},aa={}});var Q={};yn(Q,{BIGINT_FORMAT_RANGES:()=>Oy,Class:()=>Ju,NUMBER_FORMAT_RANGES:()=>rl,aborted:()=>xn,allowsEval:()=>Qu,assert:()=>XS,assertEqual:()=>GS,assertIs:()=>WS,assertNever:()=>YS,assertNotEqual:()=>JS,assignProp:()=>Xu,cached:()=>ws,captureStackTrace:()=>ua,cleanEnum:()=>dP,cleanRegex:()=>ks,clone:()=>kt,createTransparentProxy:()=>oP,defineLazy:()=>_e,esc:()=>wn,escapeRegex:()=>Dr,extend:()=>aP,finalizeIssue:()=>Ft,floatSafeRemainder:()=>Yu,getElementAtPath:()=>QS,getEnumValues:()=>bs,getLengthableOrigin:()=>Ss,getParsedType:()=>nP,getSizableOrigin:()=>Ny,isObject:()=>mo,isPlainObject:()=>ho,issue:()=>nl,joinValues:()=>ca,jsonStringifyReplacer:()=>Wu,merge:()=>cP,normalizeParams:()=>M,nullish:()=>xs,numKeys:()=>rP,omit:()=>iP,optionalKeys:()=>tl,partial:()=>uP,pick:()=>sP,prefixIssues:()=>ar,primitiveTypes:()=>Iy,promiseAllObject:()=>eP,propertyKeyTypes:()=>el,randomString:()=>tP,required:()=>lP,stringifyPrimitive:()=>la,unwrapMessage:()=>$s});function GS(t){return t}function JS(t){return t}function WS(t){}function YS(t){throw new Error}function XS(t){}function bs(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ca(t,e="|"){return t.map(r=>la(r)).join(e)}function Wu(t,e){return typeof e=="bigint"?e.toString():e}function ws(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function xs(t){return t==null}function ks(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Yu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function _e(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Xu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function QS(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function eP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function tP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function wn(t){return JSON.stringify(t)}function mo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ho(t){if(mo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(mo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function rP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function M(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function oP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function la(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function tl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function sP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return kt(t,{...t._zod.def,shape:r,checks:[]})}function iP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return kt(t,{...t._zod.def,shape:r,checks:[]})}function aP(t,e){if(!ho(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Xu(this,"shape",n),n},checks:[]};return kt(t,r)}function cP(t,e){return kt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Xu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function uP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return kt(e,{...e._zod.def,shape:o,checks:[]})}function lP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return kt(e,{...e._zod.def,shape:o,checks:[]})}function xn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ar(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $s(t){return typeof t=="string"?t:t?.message}function Ft(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=$s(t.inst?._zod.def?.error?.(t))??$s(e?.error?.(t))??$s(r.customError?.(t))??$s(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ny(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ss(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function nl(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function dP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ua,Qu,nP,el,Iy,rl,Oy,Ju,cr=x(()=>{ua=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Qu=ws(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});nP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},el=new Set(["string","number","symbol"]),Iy=new Set(["string","number","bigint","boolean","symbol","undefined"]);rl={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]},Oy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ju=class{constructor(...e){}}});function ol(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function sl(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var jy,da,Ps,il=x(()=>{fo();cr();jy=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Wu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},da=b("$ZodError",jy),Ps=b("$ZodError",jy,{Parent:Error})});var al,cl,ul,ll,dl,kn,pl,Sn,fl=x(()=>{fo();il();cr();al=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new br;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ft(c,s,xt())));throw ua(a,o?.callee),a}return i.value},cl=al(Ps),ul=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ft(c,s,xt())));throw ua(a,o?.callee),a}return i.value},ll=ul(Ps),dl=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new br;return s.issues.length?{success:!1,error:new(t??da)(s.issues.map(i=>Ft(i,o,xt())))}:{success:!0,data:s.value}},kn=dl(Ps),pl=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Ft(i,o,xt())))}:{success:!0,data:s.value}},Sn=pl(Ps)});function Fy(){return new RegExp(fP,"u")}function e_(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function t_(t){return new RegExp(`^${e_(t)}$`)}function r_(t){let e=e_({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Xy}T(?:${n})$`)}var Cy,Ay,My,Zy,qy,Dy,Ly,Uy,ml,Vy,fP,Hy,Ky,By,Gy,Jy,hl,Wy,Yy,Xy,Qy,n_,o_,s_,i_,a_,c_,u_,fa=x(()=>{Cy=/^[cC][^\s-]{8,}$/,Ay=/^[0-9a-z]+$/,My=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zy=/^[0-9a-vA-V]{20}$/,qy=/^[A-Za-z0-9]{27}$/,Dy=/^[a-zA-Z0-9_-]{21}$/,Ly=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Uy=/^([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})$/,ml=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,Vy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,fP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Hy=/^(?:(?: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])$/,Ky=/^(([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})$/,By=/^((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])$/,Gy=/^(([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])$/,Jy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hl=/^[A-Za-z0-9_-]*$/,Wy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Yy=/^\+(?:[0-9]){6,14}[0-9]$/,Xy="(?:(?:\\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])))",Qy=new RegExp(`^${Xy}$`);n_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},o_=/^\d+$/,s_=/^-?\d+(?:\.\d+)?/i,i_=/true|false/i,a_=/null/i,c_=/^[^A-Z]*$/,u_=/^[^a-z]*$/});var qe,l_,gl,yl,d_,p_,f_,m_,h_,Es,g_,y_,__,v_,$_,b_,w_,ma=x(()=>{fo();fa();cr();qe=b("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),l_={number:"number",bigint:"bigint",object:"date"},gl=b("$ZodCheckLessThan",(t,e)=>{qe.init(t,e);let r=l_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),yl=b("$ZodCheckGreaterThan",(t,e)=>{qe.init(t,e);let r=l_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),d_=b("$ZodCheckMultipleOf",(t,e)=>{qe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Yu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),p_=b("$ZodCheckNumberFormat",(t,e)=>{qe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=rl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=o_)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),f_=b("$ZodCheckMaxLength",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ss(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),m_=b("$ZodCheckMinLength",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ss(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),h_=b("$ZodCheckLengthEquals",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ss(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Es=b("$ZodCheckStringFormat",(t,e)=>{var r,n;qe.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),g_=b("$ZodCheckRegex",(t,e)=>{Es.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),y_=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=c_),Es.init(t,e)}),__=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=u_),Es.init(t,e)}),v_=b("$ZodCheckIncludes",(t,e)=>{qe.init(t,e);let r=Dr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),$_=b("$ZodCheckStartsWith",(t,e)=>{qe.init(t,e);let r=new RegExp(`^${Dr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),b_=b("$ZodCheckEndsWith",(t,e)=>{qe.init(t,e);let r=new RegExp(`.*${Dr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),w_=b("$ZodCheckOverwrite",(t,e)=>{qe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ha,_l=x(()=>{ha=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
6
6
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
package/dist/worker.cjs CHANGED
@@ -217,7 +217,7 @@ END`;function wt(a,e){for(let t of e.split(";")){let p=t.trim();p.length>0&&a.ru
217
217
  ORDER BY o.created_at_epoch DESC
218
218
  LIMIT ?`).all(e,p);return{results:d.map(i=>H1(i)),total:d.length,mode:"FALLBACK"}}catch{return{results:[],total:0,mode:"FALLBACK"}}}resolveAnchorId(e){let t=parseInt(e,10);return!isNaN(t)&&String(t)===e.trim()?t:null}fetchRowsByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.query(`SELECT * FROM observations WHERE id IN (${t})`).all(...e)}};function Rt(a){return a.query("SELECT changes() as changes").get()?.changes??0}function ni(a){let e=a.query("SELECT page_count, page_size FROM pragma_page_count(), pragma_page_size()").get();return e===null?0:e.page_count*e.page_size}var Q1=class{constructor(e,t){this.db=e;this.vectorSync=t}purgeByAge(e){let t=Math.floor(Date.now()/1e3)-e*86400;this.db.run("DELETE FROM observations WHERE created_at_epoch < ?",[t]);let p=Rt(this.db);return p>0&&this.vectorSync?.vacuum().catch(()=>{}),{deleted:p}}purgeByProject(e){return this.db.run("DELETE FROM observations WHERE project = ?",[e]),{deleted:Rt(this.db)}}vacuum(){this.db.run("VACUUM")}getStats(){let t=this.db.query("SELECT COUNT(*) as count FROM observations").get()?.count??0,d=this.db.query("SELECT created_at FROM observations ORDER BY created_at_epoch ASC LIMIT 1").get()?.created_at??null,i=ni(this.db);return{observationCount:t,oldestObservation:d,dbSizeBytes:i}}};var H=require("fs"),Va=require("path"),si=5,Ra="memory-backup-",Ca=".db";function oi(){return`${Ra}${new Date().toISOString().replace(/[:.]/g,"-")}${Ca}`}function li(a){let e=a.replace(Ra,"").replace(Ca,""),t=e.replace(/T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/,"T$1:$2:$3.$4Z"),p=new Date(t);return isNaN(p.getTime())?new Date((0,H.statSync)(e).mtime).toISOString():p.toISOString()}function Ct(a){return(0,H.existsSync)(a)?(0,H.readdirSync)(a).filter(t=>t.startsWith(Ra)&&t.endsWith(Ca)).map(t=>{let p=(0,Va.join)(a,t),d=(0,H.statSync)(p);return{path:p,createdAt:li(t),sizeBytes:d.size}}):[]}function Dt(a){return[...a].sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}var z1=class{constructor(e,t){this.dbPath=e;this.backupDir=t}async create(){(0,H.mkdirSync)(this.backupDir,{recursive:!0});let e=oi(),t=(0,Va.join)(this.backupDir,e);(0,H.copyFileSync)(this.dbPath,t);let p=(0,H.statSync)(t);return{path:t,sizeBytes:p.size}}async restore(e){if(!(0,H.existsSync)(e))throw new Error(`Backup file not found: ${e}`);(0,H.copyFileSync)(e,this.dbPath)}async list(){return Dt(Ct(this.backupDir))}async rotate(e=si){let t=Dt(Ct(this.backupDir));if(t.length<=e)return{deleted:0};let p=t.slice(0,t.length-e);for(let d of p)(0,H.rmSync)(d.path,{force:!0});return{deleted:p.length}}};var Ot=384,At=2e3,Pt=32,mi="Xenova/all-MiniLM-L6-v2";function xt(a){return a.length>At?a.slice(0,At):a}function ci(a){let e=0;for(let t=0;t<a.length;t++)e+=(a[t]??0)*(a[t]??0);return e=Math.sqrt(e),e===0?Array.from(a):Array.from(a).map(t=>t/e)}var Da=null;async function ui(){let{pipeline:a,env:e}=await import("@xenova/transformers");return e.cacheDir=mt,await a("feature-extraction",mi,{quantized:!0})}async function hi(){return Da===null&&(Da=await ui()),Da}var G1=class{async getEmbedding(e){let t=xt(e),d=await(await hi())(t,{pooling:"mean",normalize:!0});return Array.from(d.data)}async getBatchEmbeddings(e,t=Pt){let p=[];for(let d=0;d<e.length;d+=t){let i=e.slice(d,d+t),r=await Promise.all(i.map(n=>this.getEmbedding(n)));p.push(...r)}return p}};function fi(a){let e=0;for(let t=0;t<a.length;t++)e=e*31+a.charCodeAt(t)>>>0;return e}function vi(a){let e=new Float32Array(Ot),t=a;for(let p=0;p<Ot;p++)t=t*1664525+1013904223>>>0,e[p]=t/4294967295*2-1;return ci(e)}var X1=class{async getEmbedding(e){let t=xt(e),p=fi(t);return vi(p)}async getBatchEmbeddings(e,t=Pt){return Promise.all(e.map(p=>this.getEmbedding(p)))}};var ds=j1(yp(),1),lr=Object.defineProperty,_p=Object.getOwnPropertySymbols,mr=Object.prototype.hasOwnProperty,cr=Object.prototype.propertyIsEnumerable,bp=(a,e,t)=>e in a?lr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,ta=(a,e)=>{for(var t in e||(e={}))mr.call(e,t)&&bp(a,t,e[t]);if(_p)for(var t of _p(e))cr.call(e,t)&&bp(a,t,e[t]);return a},y=fetch,_="",ur=class{constructor(a,e=_,t=y){this.basePath=e,this.fetch=t,a&&(this.configuration=a,this.basePath=a.basePath||this.basePath)}},h=class Cp extends Error{constructor(e,t){super(t),this.field=e,Object.setPrototypeOf(this,Cp.prototype),this.name="RequiredError"}},b=function(a){return{add(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling add.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling add.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling add.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling add.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/add".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},addV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling addV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling addV1.");let d="/api/v1/collections/{collection_id}/add".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},aDelete(e,t,p,d,i={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling aDelete.");if(t==null)throw new h("tenant","Required parameter tenant was null or undefined when calling aDelete.");if(p==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling aDelete.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling aDelete.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/delete".replace("{collection_id}",encodeURIComponent(String(e))).replace("{tenant}",encodeURIComponent(String(t))).replace("{database_name}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},aGet(e,t,p,d,i={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling aGet.");if(t==null)throw new h("tenant","Required parameter tenant was null or undefined when calling aGet.");if(p==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling aGet.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling aGet.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/get".replace("{collection_id}",encodeURIComponent(String(e))).replace("{tenant}",encodeURIComponent(String(t))).replace("{database_name}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},count(e,t,p,d={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling count.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling count.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling count.");let i="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/count".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),r=i.indexOf("?"),n=Object.assign({method:"GET"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},countCollections(e,t,p={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling countCollections.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling countCollections.");let d="/api/v2/tenants/{tenant}/databases/{database_name}/collections_count".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))),i=d.indexOf("?"),r=Object.assign({method:"GET"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),r.headers=n;let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},countCollectionsV1(e,t,p={}){let d="/api/v1/count_collections",i=d.indexOf("?"),r=Object.assign({method:"GET"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),e!==void 0&&s.append("tenant",String(e)),t!==void 0&&s.append("database",String(t)),r.headers=n;let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},countV1(e,t={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling countV1.");let p="/api/v1/collections/{collection_id}/count".replace("{collection_id}",encodeURIComponent(String(e))),d=p.indexOf("?"),i=Object.assign({method:"GET"},t),r=t.headers?new Headers(t.headers):new Headers,n=new URLSearchParams(d!==-1?p.substring(d+1):"");d!==-1&&(p=p.substring(0,d)),i.headers=r;let s=n.toString();return s&&(p+="?"+s),{url:p,options:i}},createCollection(e,t,p,d={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling createCollection.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling createCollection.");if(p==null)throw new h("request","Required parameter request was null or undefined when calling createCollection.");let i="/api/v2/tenants/{tenant}/databases/{database_name}/collections".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))),r=i.indexOf("?"),n=Object.assign({method:"POST"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),s.set("Content-Type","application/json"),n.headers=s,p!==void 0&&(n.body=JSON.stringify(p||{}));let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},createCollectionV1(e,t,p,d={}){if(p==null)throw new h("request","Required parameter request was null or undefined when calling createCollectionV1.");let i="/api/v1/collections",r=i.indexOf("?"),n=Object.assign({method:"POST"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),e!==void 0&&o.append("tenant",String(e)),t!==void 0&&o.append("database",String(t)),s.set("Content-Type","application/json"),n.headers=s,p!==void 0&&(n.body=JSON.stringify(p||{}));let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},createDatabase(e,t,p={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling createDatabase.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling createDatabase.");let d="/api/v2/tenants/{tenant}/databases".replace("{tenant}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},createDatabaseV1(e,t,p={}){if(t==null)throw new h("request","Required parameter request was null or undefined when calling createDatabaseV1.");let d="/api/v1/databases",i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),e!==void 0&&s.append("tenant",String(e)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},createTenant(e,t={}){if(e==null)throw new h("request","Required parameter request was null or undefined when calling createTenant.");let p="/api/v2/tenants",d=p.indexOf("?"),i=Object.assign({method:"POST"},t),r=t.headers?new Headers(t.headers):new Headers,n=new URLSearchParams(d!==-1?p.substring(d+1):"");d!==-1&&(p=p.substring(0,d)),r.set("Content-Type","application/json"),i.headers=r,e!==void 0&&(i.body=JSON.stringify(e||{}));let s=n.toString();return s&&(p+="?"+s),{url:p,options:i}},createTenantV1(e,t={}){if(e==null)throw new h("request","Required parameter request was null or undefined when calling createTenantV1.");let p="/api/v1/tenants",d=p.indexOf("?"),i=Object.assign({method:"POST"},t),r=t.headers?new Headers(t.headers):new Headers,n=new URLSearchParams(d!==-1?p.substring(d+1):"");d!==-1&&(p=p.substring(0,d)),r.set("Content-Type","application/json"),i.headers=r,e!==void 0&&(i.body=JSON.stringify(e||{}));let s=n.toString();return s&&(p+="?"+s),{url:p,options:i}},deleteCollection(e,t,p,d={}){if(e==null)throw new h("collectionName","Required parameter collectionName was null or undefined when calling deleteCollection.");if(t==null)throw new h("tenant","Required parameter tenant was null or undefined when calling deleteCollection.");if(p==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling deleteCollection.");let i="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_name}".replace("{collection_name}",encodeURIComponent(String(e))).replace("{tenant}",encodeURIComponent(String(t))).replace("{database_name}",encodeURIComponent(String(p))),r=i.indexOf("?"),n=Object.assign({method:"DELETE"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},deleteCollectionV1(e,t,p,d={}){if(e==null)throw new h("collectionName","Required parameter collectionName was null or undefined when calling deleteCollectionV1.");let i="/api/v1/collections/{collection_name}".replace("{collection_name}",encodeURIComponent(String(e))),r=i.indexOf("?"),n=Object.assign({method:"DELETE"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),t!==void 0&&o.append("tenant",String(t)),p!==void 0&&o.append("database",String(p)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},deleteDatabase(e,t,p={}){if(e==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling deleteDatabase.");if(t==null)throw new h("tenant","Required parameter tenant was null or undefined when calling deleteDatabase.");let d="/api/v2/tenants/{tenant}/databases/{database_name}".replace("{database_name}",encodeURIComponent(String(e))).replace("{tenant}",encodeURIComponent(String(t))),i=d.indexOf("?"),r=Object.assign({method:"DELETE"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),r.headers=n;let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},deleteV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling deleteV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling deleteV1.");let d="/api/v1/collections/{collection_id}/delete".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},getCollection(e,t,p,d={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling getCollection.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling getCollection.");if(p==null)throw new h("collectionName","Required parameter collectionName was null or undefined when calling getCollection.");let i="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_name}".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_name}",encodeURIComponent(String(p))),r=i.indexOf("?"),n=Object.assign({method:"GET"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},getCollectionV1(e,t,p,d={}){if(e==null)throw new h("collectionName","Required parameter collectionName was null or undefined when calling getCollectionV1.");let i="/api/v1/collections/{collection_name}".replace("{collection_name}",encodeURIComponent(String(e))),r=i.indexOf("?"),n=Object.assign({method:"GET"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),t!==void 0&&o.append("tenant",String(t)),p!==void 0&&o.append("database",String(p)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},getDatabase(e,t,p={}){if(e==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling getDatabase.");if(t==null)throw new h("tenant","Required parameter tenant was null or undefined when calling getDatabase.");let d="/api/v2/tenants/{tenant}/databases/{database_name}".replace("{database_name}",encodeURIComponent(String(e))).replace("{tenant}",encodeURIComponent(String(t))),i=d.indexOf("?"),r=Object.assign({method:"GET"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),r.headers=n;let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},getDatabaseV1(e,t,p={}){if(e==null)throw new h("database","Required parameter database was null or undefined when calling getDatabaseV1.");let d="/api/v1/databases/{database}".replace("{database}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"GET"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),t!==void 0&&s.append("tenant",String(t)),r.headers=n;let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},getNearestNeighbors(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling getNearestNeighbors.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling getNearestNeighbors.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling getNearestNeighbors.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling getNearestNeighbors.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/query".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},getNearestNeighborsV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling getNearestNeighborsV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling getNearestNeighborsV1.");let d="/api/v1/collections/{collection_id}/query".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},getTenant(e,t={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling getTenant.");let p="/api/v2/tenants/{tenant}".replace("{tenant}",encodeURIComponent(String(e))),d=p.indexOf("?"),i=Object.assign({method:"GET"},t),r=t.headers?new Headers(t.headers):new Headers,n=new URLSearchParams(d!==-1?p.substring(d+1):"");d!==-1&&(p=p.substring(0,d)),i.headers=r;let s=n.toString();return s&&(p+="?"+s),{url:p,options:i}},getTenantV1(e,t={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling getTenantV1.");let p="/api/v1/tenants/{tenant}".replace("{tenant}",encodeURIComponent(String(e))),d=p.indexOf("?"),i=Object.assign({method:"GET"},t),r=t.headers?new Headers(t.headers):new Headers,n=new URLSearchParams(d!==-1?p.substring(d+1):"");d!==-1&&(p=p.substring(0,d)),i.headers=r;let s=n.toString();return s&&(p+="?"+s),{url:p,options:i}},getUserIdentity(e={}){let t="/api/v2/auth/identity",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV11(e={}){let t="/api/v1",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV12(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling getV12.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling getV12.");let d="/api/v1/collections/{collection_id}/get".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},getV1Heartbeat(e={}){let t="/api/v1/heartbeat",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV1PreFlightChecks(e={}){let t="/api/v1/pre-flight-checks",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV1Version(e={}){let t="/api/v1/version",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV2(e={}){let t="/api/v2",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV2Heartbeat(e={}){let t="/api/v2/heartbeat",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV2PreFlightChecks(e={}){let t="/api/v2/pre-flight-checks",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},getV2Version(e={}){let t="/api/v2/version",p=t.indexOf("?"),d=Object.assign({method:"GET"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},listCollections(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling listCollections.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling listCollections.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))),n=r.indexOf("?"),s=Object.assign({method:"GET"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),p!==void 0&&l.append("limit",String(p)),d!==void 0&&l.append("offset",String(d)),s.headers=o;let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},listCollectionsV1(e,t,p,d,i={}){let r="/api/v1/collections",n=r.indexOf("?"),s=Object.assign({method:"GET"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),e!==void 0&&l.append("limit",String(e)),t!==void 0&&l.append("offset",String(t)),p!==void 0&&l.append("tenant",String(p)),d!==void 0&&l.append("database",String(d)),s.headers=o;let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},listDatabases(e,t,p,d={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling listDatabases.");let i="/api/v2/tenants/{tenant}/databases".replace("{tenant}",encodeURIComponent(String(e))),r=i.indexOf("?"),n=Object.assign({method:"GET"},d),s=d.headers?new Headers(d.headers):new Headers,o=new URLSearchParams(r!==-1?i.substring(r+1):"");r!==-1&&(i=i.substring(0,r)),t!==void 0&&o.append("limit",String(t)),p!==void 0&&o.append("offset",String(p)),n.headers=s;let l=o.toString();return l&&(i+="?"+l),{url:i,options:n}},postV1Reset(e={}){let t="/api/v1/reset",p=t.indexOf("?"),d=Object.assign({method:"POST"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},postV2Reset(e={}){let t="/api/v2/reset",p=t.indexOf("?"),d=Object.assign({method:"POST"},e),i=e.headers?new Headers(e.headers):new Headers,r=new URLSearchParams(p!==-1?t.substring(p+1):"");p!==-1&&(t=t.substring(0,p)),d.headers=i;let n=r.toString();return n&&(t+="?"+n),{url:t,options:d}},update(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling update.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling update.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling update.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling update.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/update".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},updateCollection(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling updateCollection.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling updateCollection.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling updateCollection.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling updateCollection.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"PUT"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},updateCollectionV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling updateCollectionV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling updateCollectionV1.");let d="/api/v1/collections/{collection_id}".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"PUT"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},updateV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling updateV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling updateV1.");let d="/api/v1/collections/{collection_id}/update".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}},upsert(e,t,p,d,i={}){if(e==null)throw new h("tenant","Required parameter tenant was null or undefined when calling upsert.");if(t==null)throw new h("databaseName","Required parameter databaseName was null or undefined when calling upsert.");if(p==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling upsert.");if(d==null)throw new h("request","Required parameter request was null or undefined when calling upsert.");let r="/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/upsert".replace("{tenant}",encodeURIComponent(String(e))).replace("{database_name}",encodeURIComponent(String(t))).replace("{collection_id}",encodeURIComponent(String(p))),n=r.indexOf("?"),s=Object.assign({method:"POST"},i),o=i.headers?new Headers(i.headers):new Headers,l=new URLSearchParams(n!==-1?r.substring(n+1):"");n!==-1&&(r=r.substring(0,n)),o.set("Content-Type","application/json"),s.headers=o,d!==void 0&&(s.body=JSON.stringify(d||{}));let c=l.toString();return c&&(r+="?"+c),{url:r,options:s}},upsertV1(e,t,p={}){if(e==null)throw new h("collectionId","Required parameter collectionId was null or undefined when calling upsertV1.");if(t==null)throw new h("request","Required parameter request was null or undefined when calling upsertV1.");let d="/api/v1/collections/{collection_id}/upsert".replace("{collection_id}",encodeURIComponent(String(e))),i=d.indexOf("?"),r=Object.assign({method:"POST"},p),n=p.headers?new Headers(p.headers):new Headers,s=new URLSearchParams(i!==-1?d.substring(i+1):"");i!==-1&&(d=d.substring(0,i)),n.set("Content-Type","application/json"),r.headers=n,t!==void 0&&(r.body=JSON.stringify(t||{}));let o=s.toString();return o&&(d+="?"+o),{url:d,options:r}}}},S=function(a){return{add(e,t,p,d,i){let r=b(a).add(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===201){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},addV1(e,t,p){let d=b(a).addV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===201){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},aDelete(e,t,p,d,i){let r=b(a).aDelete(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},aGet(e,t,p,d,i){let r=b(a).aGet(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},count(e,t,p,d){let i=b(a).count(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},countCollections(e,t,p){let d=b(a).countCollections(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},countCollectionsV1(e,t,p){let d=b(a).countCollectionsV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},countV1(e,t){let p=b(a).countV1(e,t);return(d=y,i=_)=>d(i+p.url,p.options).then(r=>{let n=r.headers.get("Content-Type"),s=n?n.replace(/;.*/,""):void 0;if(r.status===200){if(s==="application/json")return r.json();throw r}throw r.status===422,r})},createCollection(e,t,p,d){let i=b(a).createCollection(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},createCollectionV1(e,t,p,d){let i=b(a).createCollectionV1(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},createDatabase(e,t,p){let d=b(a).createDatabase(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},createDatabaseV1(e,t,p){let d=b(a).createDatabaseV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},createTenant(e,t){let p=b(a).createTenant(e,t);return(d=y,i=_)=>d(i+p.url,p.options).then(r=>{let n=r.headers.get("Content-Type"),s=n?n.replace(/;.*/,""):void 0;if(r.status===200){if(s==="application/json")return r.json();throw r}throw r})},createTenantV1(e,t){let p=b(a).createTenantV1(e,t);return(d=y,i=_)=>d(i+p.url,p.options).then(r=>{let n=r.headers.get("Content-Type"),s=n?n.replace(/;.*/,""):void 0;if(r.status===200){if(s==="application/json")return r.json();throw r}throw r})},deleteCollection(e,t,p,d){let i=b(a).deleteCollection(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},deleteCollectionV1(e,t,p,d){let i=b(a).deleteCollectionV1(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},deleteDatabase(e,t,p){let d=b(a).deleteDatabase(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},deleteV1(e,t,p){let d=b(a).deleteV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},getCollection(e,t,p,d){let i=b(a).getCollection(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},getCollectionV1(e,t,p,d){let i=b(a).getCollectionV1(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},getDatabase(e,t,p){let d=b(a).getDatabase(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},getDatabaseV1(e,t,p){let d=b(a).getDatabaseV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},getNearestNeighbors(e,t,p,d,i){let r=b(a).getNearestNeighbors(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},getNearestNeighborsV1(e,t,p){let d=b(a).getNearestNeighborsV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},getTenant(e,t){let p=b(a).getTenant(e,t);return(d=y,i=_)=>d(i+p.url,p.options).then(r=>{let n=r.headers.get("Content-Type"),s=n?n.replace(/;.*/,""):void 0;if(r.status===200){if(s==="application/json")return r.json();throw r}throw r.status===422,r})},getTenantV1(e,t){let p=b(a).getTenantV1(e,t);return(d=y,i=_)=>d(i+p.url,p.options).then(r=>{let n=r.headers.get("Content-Type"),s=n?n.replace(/;.*/,""):void 0;if(r.status===200){if(s==="application/json")return r.json();throw r}throw r.status===422,r})},getUserIdentity(e){let t=b(a).getUserIdentity(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV11(e){let t=b(a).getV11(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV12(e,t,p){let d=b(a).getV12(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},getV1Heartbeat(e){let t=b(a).getV1Heartbeat(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV1PreFlightChecks(e){let t=b(a).getV1PreFlightChecks(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV1Version(e){let t=b(a).getV1Version(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV2(e){let t=b(a).getV2(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV2Heartbeat(e){let t=b(a).getV2Heartbeat(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV2PreFlightChecks(e){let t=b(a).getV2PreFlightChecks(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},getV2Version(e){let t=b(a).getV2Version(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},listCollections(e,t,p,d,i){let r=b(a).listCollections(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},listCollectionsV1(e,t,p,d,i){let r=b(a).listCollectionsV1(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},listDatabases(e,t,p,d){let i=b(a).listDatabases(e,t,p,d);return(r=y,n=_)=>r(n+i.url,i.options).then(s=>{let o=s.headers.get("Content-Type"),l=o?o.replace(/;.*/,""):void 0;if(s.status===200){if(l==="application/json")return s.json();throw s}throw s.status===422,s})},postV1Reset(e){let t=b(a).postV1Reset(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},postV2Reset(e){let t=b(a).postV2Reset(e);return(p=y,d=_)=>p(d+t.url,t.options).then(i=>{let r=i.headers.get("Content-Type"),n=r?r.replace(/;.*/,""):void 0;if(i.status===200){if(n==="application/json")return i.json();throw i}throw i})},update(e,t,p,d,i){let r=b(a).update(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},updateCollection(e,t,p,d,i){let r=b(a).updateCollection(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},updateCollectionV1(e,t,p){let d=b(a).updateCollectionV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},updateV1(e,t,p){let d=b(a).updateV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})},upsert(e,t,p,d,i){let r=b(a).upsert(e,t,p,d,i);return(n=y,s=_)=>n(s+r.url,r.options).then(o=>{let l=o.headers.get("Content-Type"),c=l?l.replace(/;.*/,""):void 0;if(o.status===200){if(c==="application/json")return o.json();throw o}throw o.status===422,o})},upsertV1(e,t,p){let d=b(a).upsertV1(e,t,p);return(i=y,r=_)=>i(r+d.url,d.options).then(n=>{let s=n.headers.get("Content-Type"),o=s?s.replace(/;.*/,""):void 0;if(n.status===200){if(o==="application/json")return n.json();throw n}throw n.status===422,n})}}},Dp=class extends ur{add(a,e,t,p,d){return S(this.configuration).add(a,e,t,p,d)(this.fetch,this.basePath)}addV1(a,e,t){return S(this.configuration).addV1(a,e,t)(this.fetch,this.basePath)}aDelete(a,e,t,p,d){return S(this.configuration).aDelete(a,e,t,p,d)(this.fetch,this.basePath)}aGet(a,e,t,p,d){return S(this.configuration).aGet(a,e,t,p,d)(this.fetch,this.basePath)}count(a,e,t,p){return S(this.configuration).count(a,e,t,p)(this.fetch,this.basePath)}countCollections(a,e,t){return S(this.configuration).countCollections(a,e,t)(this.fetch,this.basePath)}countCollectionsV1(a,e,t){return S(this.configuration).countCollectionsV1(a,e,t)(this.fetch,this.basePath)}countV1(a,e){return S(this.configuration).countV1(a,e)(this.fetch,this.basePath)}createCollection(a,e,t,p){return S(this.configuration).createCollection(a,e,t,p)(this.fetch,this.basePath)}createCollectionV1(a,e,t,p){return S(this.configuration).createCollectionV1(a,e,t,p)(this.fetch,this.basePath)}createDatabase(a,e,t){return S(this.configuration).createDatabase(a,e,t)(this.fetch,this.basePath)}createDatabaseV1(a,e,t){return S(this.configuration).createDatabaseV1(a,e,t)(this.fetch,this.basePath)}createTenant(a,e){return S(this.configuration).createTenant(a,e)(this.fetch,this.basePath)}createTenantV1(a,e){return S(this.configuration).createTenantV1(a,e)(this.fetch,this.basePath)}deleteCollection(a,e,t,p){return S(this.configuration).deleteCollection(a,e,t,p)(this.fetch,this.basePath)}deleteCollectionV1(a,e,t,p){return S(this.configuration).deleteCollectionV1(a,e,t,p)(this.fetch,this.basePath)}deleteDatabase(a,e,t){return S(this.configuration).deleteDatabase(a,e,t)(this.fetch,this.basePath)}deleteV1(a,e,t){return S(this.configuration).deleteV1(a,e,t)(this.fetch,this.basePath)}getCollection(a,e,t,p){return S(this.configuration).getCollection(a,e,t,p)(this.fetch,this.basePath)}getCollectionV1(a,e,t,p){return S(this.configuration).getCollectionV1(a,e,t,p)(this.fetch,this.basePath)}getDatabase(a,e,t){return S(this.configuration).getDatabase(a,e,t)(this.fetch,this.basePath)}getDatabaseV1(a,e,t){return S(this.configuration).getDatabaseV1(a,e,t)(this.fetch,this.basePath)}getNearestNeighbors(a,e,t,p,d){return S(this.configuration).getNearestNeighbors(a,e,t,p,d)(this.fetch,this.basePath)}getNearestNeighborsV1(a,e,t){return S(this.configuration).getNearestNeighborsV1(a,e,t)(this.fetch,this.basePath)}getTenant(a,e){return S(this.configuration).getTenant(a,e)(this.fetch,this.basePath)}getTenantV1(a,e){return S(this.configuration).getTenantV1(a,e)(this.fetch,this.basePath)}getUserIdentity(a){return S(this.configuration).getUserIdentity(a)(this.fetch,this.basePath)}getV11(a){return S(this.configuration).getV11(a)(this.fetch,this.basePath)}getV12(a,e,t){return S(this.configuration).getV12(a,e,t)(this.fetch,this.basePath)}getV1Heartbeat(a){return S(this.configuration).getV1Heartbeat(a)(this.fetch,this.basePath)}getV1PreFlightChecks(a){return S(this.configuration).getV1PreFlightChecks(a)(this.fetch,this.basePath)}getV1Version(a){return S(this.configuration).getV1Version(a)(this.fetch,this.basePath)}getV2(a){return S(this.configuration).getV2(a)(this.fetch,this.basePath)}getV2Heartbeat(a){return S(this.configuration).getV2Heartbeat(a)(this.fetch,this.basePath)}getV2PreFlightChecks(a){return S(this.configuration).getV2PreFlightChecks(a)(this.fetch,this.basePath)}getV2Version(a){return S(this.configuration).getV2Version(a)(this.fetch,this.basePath)}listCollections(a,e,t,p,d){return S(this.configuration).listCollections(a,e,t,p,d)(this.fetch,this.basePath)}listCollectionsV1(a,e,t,p,d){return S(this.configuration).listCollectionsV1(a,e,t,p,d)(this.fetch,this.basePath)}listDatabases(a,e,t,p){return S(this.configuration).listDatabases(a,e,t,p)(this.fetch,this.basePath)}postV1Reset(a){return S(this.configuration).postV1Reset(a)(this.fetch,this.basePath)}postV2Reset(a){return S(this.configuration).postV2Reset(a)(this.fetch,this.basePath)}update(a,e,t,p,d){return S(this.configuration).update(a,e,t,p,d)(this.fetch,this.basePath)}updateCollection(a,e,t,p,d){return S(this.configuration).updateCollection(a,e,t,p,d)(this.fetch,this.basePath)}updateCollectionV1(a,e,t){return S(this.configuration).updateCollectionV1(a,e,t)(this.fetch,this.basePath)}updateV1(a,e,t){return S(this.configuration).updateV1(a,e,t)(this.fetch,this.basePath)}upsert(a,e,t,p,d){return S(this.configuration).upsert(a,e,t,p,d)(this.fetch,this.basePath)}upsertV1(a,e,t){return S(this.configuration).upsertV1(a,e,t)(this.fetch,this.basePath)}},Sp;(a=>{let e;(t=>{t.Documents="documents",t.Embeddings="embeddings",t.Metadatas="metadatas",t.Distances="distances",t.Uris="uris",t.Data="data"})(e=a.IncludeEnum||(a.IncludeEnum={}))})(Sp||(Sp={}));var Op=class{constructor(a={}){this.apiKey=a.apiKey,this.username=a.username,this.password=a.password,this.authorization=a.authorization,this.basePath=a.basePath}},hr=class extends Error{constructor(a,e,t){super(e),this.cause=t,this.name=a}},pa=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaConnectionError"}},fr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaServerError"}},vr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaClientError"}},gr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaAuthError"}},wr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaForbiddenError"}},yr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaNotFoundError"}},_r=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaValueError"}},br=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="InvalidCollectionError"}},Sr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="InvalidArgumentError"}},Tr=class extends Error{constructor(a,e){super(a),this.cause=e,this.name="ChromaUniqueError"}};function Er(a,e){switch(a){case"InvalidCollection":return new br(e);case"InvalidArgumentError":return new Sr(e);default:return}}var Nr=class{constructor(a,e,t,p,d){this.name=a,this.id=e,this.metadata=d,this.client=t,this.embeddingFunction=p}async add(a){await this.client.init(),await this.client.api.add(this.client.tenant,this.client.database,this.id,await $a(a,this.embeddingFunction),this.client.api.options)}async upsert(a){await this.client.init(),await this.client.api.upsert(this.client.tenant,this.client.database,this.id,await $a(a,this.embeddingFunction),this.client.api.options)}async count(){return await this.client.init(),await this.client.api.count(this.client.tenant,this.client.database,this.id,this.client.api.options)}async get({ids:a,where:e,limit:t,offset:p,include:d,whereDocument:i}={}){await this.client.init();let r=a?o1(a):void 0;return await this.client.api.aGet(this.id,this.client.tenant,this.client.database,{ids:r,where:e,limit:t,offset:p,include:d,where_document:i},this.client.api.options)}async update(a){await this.client.init(),await this.client.api.update(this.client.tenant,this.client.database,this.id,await $a(a,this.embeddingFunction,!0),this.client.api.options)}async query({nResults:a=10,where:e,whereDocument:t,include:p,queryTexts:d,queryEmbeddings:i}){if(d&&i||!d&&!i)throw new Error("You must supply exactly one of queryTexts or queryEmbeddings.");await this.client.init();let r=d!==void 0?await this.embeddingFunction.generate(o1(d)):Ap(i);return await this.client.api.getNearestNeighbors(this.client.tenant,this.client.database,this.id,{query_embeddings:r,where:e,n_results:a,where_document:t,include:p},this.client.api.options)}async modify({name:a,metadata:e}){return await this.client.init(),this.client.api.updateCollection(this.client.tenant,this.client.database,this.id,{new_name:a,new_metadata:e},this.client.api.options).then(()=>(a!==void 0&&(this.name=a),e!==void 0&&(this.metadata=e),{name:this.name,metadata:this.metadata}))}async peek({limit:a=10}={}){return await this.client.init(),await this.client.api.aGet(this.id,this.client.tenant,this.client.database,{limit:a},this.client.api.options)}async delete({ids:a,where:e,whereDocument:t}={}){await this.client.init();let p;a!==void 0&&(p=o1(a)),await this.client.api.aDelete(this.id,this.client.tenant,this.client.database,{ids:p,where:e,where_document:t},this.client.api.options)}};function o1(a){return Array.isArray(a)?a:[a]}function Ap(a){return a.length===0?[]:Array.isArray(a[0])?a:a[0]&&typeof a[0][Symbol.iterator]=="function"?a.map(e=>Array.from(e)):[a]}async function Ga(a,e,t){try{await a.getTenant({name:e})}catch(p){throw p instanceof pa?p:new Error(`Could not connect to tenant ${e}. Are you sure it exists? Underlying error:
219
219
  ${p}`)}try{await a.getDatabase({name:t,tenantName:e})}catch(p){throw p instanceof pa?p:new Error(`Could not connect to database ${t} for tenant ${e}. Are you sure it exists? Underlying error:
220
- ${p}`)}}function Vr(){return typeof window<"u"&&typeof window.document<"u"}function Rr(a){return{ids:o1(a.ids),embeddings:a.embeddings?Ap(a.embeddings):void 0,metadatas:a.metadatas?o1(a.metadatas):void 0,documents:a.documents?o1(a.documents):void 0}}async function $a(a,e,t){let{ids:p,embeddings:d,metadatas:i,documents:r}=Rr(a);if(!d&&!r&&!t)throw new Error("embeddings and documents cannot both be undefined");let n=d||(r?await e.generate(r):void 0);if(!n&&!t)throw new Error("Failed to generate embeddings for your request.");for(let o=0;o<p.length;o+=1)if(typeof p[o]!="string")throw new Error(`Expected ids to be strings, found ${typeof p[o]} at index ${o}`);if(n!==void 0&&p.length!==n.length||i!==void 0&&p.length!==i.length||r!==void 0&&p.length!==r.length)throw new Error("ids, embeddings, metadatas, and documents must all be the same length");if(new Set(p).size!==p.length){let o=p.filter((l,c)=>p.indexOf(l)!==c);throw new Error(`ID's must be unique, found duplicates for: ${o}`)}return{ids:p,metadatas:i,documents:r,embeddings:n}}function Qa(a,e){return new Nr(e.name,e.id,a,e.embeddingFunction,e.metadata)}var Cr=a=>a==="AUTHORIZATION"?"Authorization":"X-Chroma-Token",Dr=a=>Buffer.from(a).toString("base64"),Or=class{constructor(a){let e=a??process.env.CHROMA_CLIENT_AUTH_CREDENTIALS;if(e===void 0)throw new Error("Credentials must be supplied via environment variable (CHROMA_CLIENT_AUTH_CREDENTIALS) or passed in as configuration.");this.credentials={Authorization:"Basic "+Dr(e)}}authenticate(){return this.credentials}},Ar=class{constructor(a,e="AUTHORIZATION"){let t=a??process.env.CHROMA_CLIENT_AUTH_CREDENTIALS;if(t===void 0)throw new Error("Credentials must be supplied via environment variable (CHROMA_CLIENT_AUTH_CREDENTIALS) or passed in as configuration.");let p=Cr(e),d=e==="AUTHORIZATION"?`Bearer ${t}`:t;this.credentials={},this.credentials[p]=d}authenticate(){return this.credentials}},Pp=a=>{if(a.provider===void 0)throw new Error("Auth provider not specified");if(a.credentials===void 0)throw new Error("Auth credentials not specified");switch(a.provider){case"basic":return new Or(a.credentials);case"token":return new Ar(a.credentials,a.tokenHeaderType);default:throw new Error("Invalid auth provider")}};function Pr(a){var e,t,p;return!!((a?.name==="TypeError"||a?.name==="FetchError")&&((e=a.message)!=null&&e.includes("fetch failed")||(t=a.message)!=null&&t.includes("Failed to fetch")||(p=a.message)!=null&&p.includes("ENOTFOUND")))}function Tp(a){let e=/(\w+)\('(.+)'\)/,t=a?.match(e);if(t){let[,p,d]=t;return p==="ValueError"?new _r(d):new hr(p,d)}return new fr("The server encountered an error while handling the request.")}var xp=async(a,e)=>{try{let t=await fetch(a,e),p=t.clone(),d=await p.json();if(!p.ok){let i=Er(d?.error,d?.message);if(i)throw i;switch(t.status){case 400:throw new vr(`Bad request to ${a} with status: ${t.statusText}`);case 401:throw new gr("Unauthorized");case 403:throw new wr("You do not have permission to access the requested resource.");case 404:throw new yr(`The requested resource could not be found: ${a}`);case 409:throw new Tr("The resource already exists");case 500:throw Tp(d?.error);case 502:case 503:case 504:throw new pa("Unable to connect to the chromadb server. Please try again later.")}throw new Error(`Failed to fetch ${a} with status ${t.status}: ${t.statusText}`)}if(d?.error)throw Tp(d.error);return t}catch(t){throw Pr(t)?new pa("Failed to connect to chromadb. Make sure your server is running and try again. If you are running from a browser, make sure that your chromadb instance is configured to allow requests from the current origin using the CHROMA_SERVER_CORS_ALLOW_ORIGINS environment variable.",t):t}},za="default_tenant",aa="default_database",xr=class{constructor({path:a,fetchOptions:e,auth:t,tenant:p=za,database:d=aa}={}){this.tenant=za,this.database=aa,a===void 0&&(a="http://localhost:8000"),this.tenant=p,this.database=d,this.authProvider=void 0;let i=new Op({basePath:a});this.api=new Dp(i,void 0,xp),this.api.options=e??{},t!==void 0&&(this.authProvider=Pp(t),this.api.options.headers=ta(ta({},this.api.options.headers),this.authProvider.authenticate()))}async setTenant({tenant:a=za,database:e=aa}){await Ga(this,a,e),this.tenant=a,this.database=e}async setDatabase({database:a=aa}){await Ga(this,this.tenant,a),this.database=a}async createTenant({name:a}){return await this.api.createTenant({name:a},this.api.options),{name:a}}async getTenant({name:a}){return{name:(await this.api.getTenant(a,this.api.options)).name}}async createDatabase({name:a,tenantName:e}){return await this.api.createDatabase(e,{name:a},this.api.options),{name:a}}async getDatabase({name:a,tenantName:e}){return await this.api.getDatabase(a,e,this.api.options)}async deleteDatabase({name:a,tenantName:e}){await this.api.deleteDatabase(a,e,this.api.options)}async listDatabases({limit:a,offset:e,tenantName:t}){return await this.api.listDatabases(t,a,e,this.api.options)}},Ep,Np=class Ip{constructor({model:e="Xenova/all-MiniLM-L6-v2",revision:t="main",quantized:p=!1,progress_callback:d=null}={}){this.model=e,this.revision=t,this.quantized=p,this.progress_callback=d}async generate(e){return await this.loadClient(),this.pipelinePromise=new Promise(async(d,i)=>{try{let r=this.transformersApi,n=this.quantized,s=this.revision,o=this.progress_callback;d(await r("feature-extraction",this.model,{quantized:n,revision:s,progress_callback:o}))}catch(r){i(r)}}),(await(await this.pipelinePromise)(e,{pooling:"mean",normalize:!0})).tolist()}async loadClient(){if(!this.transformersApi){try{let{pipeline:e}=await Ip.import();Ep=e}catch(e){throw e.code==="MODULE_NOT_FOUND"?new Error("Please install the chromadb-default-embed package to use the DefaultEmbeddingFunction, `npm install chromadb-default-embed`"):e}this.transformersApi=Ep}}static async import(){try{let e;Vr()?e=await import("https://unpkg.com/chromadb-default-embed@2.14.0"):e=await import("chromadb-default-embed");let{pipeline:t,env:p}=e;return p.allowLocalModels=!1,{pipeline:t}}catch{throw new Error("Please install chromadb-default-embed as a dependency with, e.g. `npm install chromadb-default-embed`")}}},Vp="default_tenant",Rp="default_database",Xa=class{constructor({path:a="http://localhost:8000",fetchOptions:e,auth:t,tenant:p=Vp,database:d=Rp}={}){this.tenant=p,this.database=d,this.authProvider=void 0;let i=new Op({basePath:a});this.api=new Dp(i,void 0,xp),this.api.options=e??{},t!==void 0&&(this.authProvider=Pp(t),this.api.options.headers=ta(ta({},this.api.options.headers),this.authProvider.authenticate())),this._adminClient=new xr({path:a,fetchOptions:e,auth:t,tenant:p,database:d})}async init(){return this._initPromise||(this.authProvider!==void 0&&await this.getUserIdentity(),this._initPromise=Ga(this._adminClient,this.tenant,this.database)),this._initPromise}async getUserIdentity(){let a=await this.api.getUserIdentity(this.api.options),e=a.tenant,t=a.databases;e!=null&&e!=="*"&&this.tenant==Vp&&(this.tenant=e),t!=null&&t.length==1&&t[0]!=="*"&&this.database==Rp&&(this.database=t[0])}async reset(){return await this.init(),await this.api.postV2Reset(this.api.options)}async version(){return await this.api.getV2Version(this.api.options)}async heartbeat(){return(await this.api.getV2Heartbeat(this.api.options))["nanosecond heartbeat"]}async createCollection({name:a,metadata:e,embeddingFunction:t=new Np}){await this.init();let p=await this.api.createCollection(this.tenant,this.database,{name:a,configuration:null,metadata:e},this.api.options);return Qa(this,{name:p.name,id:p.id,metadata:p.metadata,embeddingFunction:t})}async getOrCreateCollection({name:a,metadata:e,embeddingFunction:t=new Np}){await this.init();let p=await this.api.createCollection(this.tenant,this.database,{name:a,configuration:null,metadata:e,get_or_create:!0},this.api.options);return Qa(this,{name:p.name,id:p.id,metadata:p.metadata,embeddingFunction:t})}async listCollections({limit:a,offset:e}={}){return await this.init(),(await this.api.listCollections(this.tenant,this.database,a,e,this.api.options)).map(p=>p.name)}async listCollectionsAndMetadata({limit:a,offset:e}={}){return await this.init(),await this.api.listCollections(this.tenant,this.database,a,e,this.api.options)}async countCollections(){return await this.init(),await this.api.countCollections(this.tenant,this.database,this.api.options)}async getCollection({name:a,embeddingFunction:e}){await this.init();let t=await this.api.getCollection(this.tenant,this.database,a,this.api.options);return Qa(this,{name:t.name,id:t.id,metadata:t.metadata,embeddingFunction:e})}async deleteCollection({name:a}){await this.init(),await this.api.deleteCollection(a,this.tenant,this.database,this.api.options)}};var kp=require("fs");var da=class{circuit;maxFailures;cooldownMs;hasAttemptedRecovery;client;chromaDbUrl;mutex;collections;constructor(e){this.chromaDbUrl=e.chromaDbUrl,this.maxFailures=e.maxFailures??3,this.cooldownMs=e.cooldownMs??6e4,this.circuit={failures:0,lastFailure:0,state:"closed"},this.hasAttemptedRecovery=!1,this.client=null,this.mutex=Promise.resolve(),this.collections=new Map}async executeWithCircuitBreaker(e){if(this.circuit.state==="open")if(Date.now()-this.circuit.lastFailure>this.cooldownMs)this.circuit.state="half-open";else throw new Error("Circuit breaker open: ChromaDB unavailable");try{let t=await e();return this.circuit={failures:0,lastFailure:0,state:"closed"},t}catch(t){throw this.circuit.failures++,this.circuit.lastFailure=Date.now(),this.circuit.failures>=this.maxFailures&&(this.circuit.state="open",this.hasAttemptedRecovery||(this.hasAttemptedRecovery=!0,await this.recoverFromCorruptedDatabase())),t}}async getClient(){let e,t=new Promise(d=>e=d),p=this.mutex;this.mutex=t,await p;try{return this.client===null&&(this.client=new Xa({path:this.chromaDbUrl})),this.client}finally{e()}}async getCollection(e){let t,p=new Promise(i=>t=i),d=this.mutex;this.mutex=p,await d;try{let i=this.collections.get(e);if(i!==void 0)return i;this.client===null&&(this.client=new Xa({path:this.chromaDbUrl}));let r=await this.client.getOrCreateCollection({name:e});return this.collections.set(e,r),r}finally{t()}}async isAvailable(){if(this.circuit.state==="open")return!1;try{return await(await this.getClient()).heartbeat(),!0}catch{return!1}}reset(){this.circuit={failures:0,lastFailure:0,state:"closed"},this.hasAttemptedRecovery=!1,this.client=null,this.collections.clear()}async recoverFromCorruptedDatabase(){try{(0,kp.rmSync)(ct,{recursive:!0,force:!0})}catch{}}getCircuitState(){return this.circuit.state}getCircuitFailures(){return this.circuit.failures}};function jp(a){let e=[],t={observationId:a.id,project:a.project,type:a.type,createdAtEpoch:a.createdAtEpoch};a.narrative&&e.push({id:`obs_${a.id}_narrative`,document:a.narrative,metadata:{...t,field:"narrative"}}),a.text&&e.push({id:`obs_${a.id}_text`,document:a.text,metadata:{...t,field:"text"}});for(let p=0;p<a.facts.length;p++){let d=a.facts[p];d!==void 0&&e.push({id:`obs_${a.id}_fact_${p}`,document:d,metadata:{...t,field:"fact"}})}return e}function Lp(a){let e=[],t={summaryId:a.id,project:a.project,createdAtEpoch:a.createdAtEpoch},p=[["request",a.request],["investigated",a.investigated],["learned",a.learned],["completed",a.completed],["next_steps",a.nextSteps],["notes",a.notes]];for(let[d,i]of p)i&&e.push({id:`summary_${a.id}_${d}`,document:i,metadata:{...t,field:d}});return e}var Ir=10,kr=90,jr=100;function ia(a){return`cm__${a.toLowerCase()}`}function Lr(a){let e=/^obs_(\d+)_/.exec(a);return e===null||e[1]===void 0?null:parseInt(e[1],10)}function Fr(a){let e=a.split("_");return e.length<3?"unknown":e[2]??"unknown"}var ra=class{connection;embeddingService;constructor(e,t){this.connection=e,this.embeddingService=t}async syncObservation(e){let t=jp(e);if(t.length===0)return;let p=ia(e.project),d=await this.connection.getCollection(p),i=t.map(n=>n.document),r=await this.embeddingService.getBatchEmbeddings(i);await d.upsert({ids:t.map(n=>n.id),documents:i,embeddings:r,metadatas:t.map(n=>n.metadata)})}async syncSummary(e){let t=Lp(e);if(t.length===0)return;let p=ia(e.project),d=await this.connection.getCollection(p),i=t.map(n=>n.document),r=await this.embeddingService.getBatchEmbeddings(i);await d.upsert({ids:t.map(n=>n.id),documents:i,embeddings:r,metadatas:t.map(n=>n.metadata)})}async query(e,t,p=Ir,d=kr){let i=ia(t),r=await this.connection.getCollection(i),n=Math.floor(Date.now()/1e3)-d*24*60*60,s=await r.query({queryEmbeddings:[e],nResults:p,where:{createdAtEpoch:{$gte:n}}}),o=s.ids[0]??[],l=s.distances?.[0]??[],c=new Set,C=[];for(let D=0;D<o.length;D++){let T=o[D];if(T==null)continue;let F=Lr(T);if(F===null||c.has(F))continue;c.add(F);let j=l[D]??0;C.push({observationId:F,score:1-j,field:Fr(T)})}return C}async vacuum(e){if(e===void 0)return;let t=ia(e);await(await this.connection.getCollection(t)).delete({})}async backfill(e,t=jr){for(let p=0;p<e.length;p+=t){let d=e.slice(p,p+t);await Promise.all(d.map(i=>this.syncObservation(i)))}}};function Wa(a){return a.split("/").filter(Boolean).map(e=>e.startsWith(":")?{kind:"param",name:e.slice(1)}:{kind:"literal",value:e})}function Ur(a,e){if(a.length!==e.length)return null;let t={};for(let p=0;p<a.length;p++){let d=a[p],i=e[p];if(d===void 0||i===void 0)return null;if(d.kind==="literal"){if(d.value!==i)return null}else t[d.name]=i}return t}function Fp(a,e){return new Response(JSON.stringify({error:a}),{status:e,headers:{"Content-Type":"application/json"}})}var na=class{routes=[];get(e,t){this.routes.push({method:"GET",segments:Wa(e),handler:t})}post(e,t){this.routes.push({method:"POST",segments:Wa(e),handler:t})}delete(e,t){this.routes.push({method:"DELETE",segments:Wa(e),handler:t})}async handle(e){let t=new URL(e.url),p=t.pathname.split("/").filter(Boolean),d=e.method.toUpperCase(),i=!1;for(let r of this.routes){let n=Ur(r.segments,p);if(n!==null&&(i=!0,r.method===d))return await r.handler(e,n)}return i?Fp(`Method ${d} not allowed`,405):Fp(`Route not found: ${t.pathname}`,404)}};function Mr(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Up(a,e){return`event: ${a}
220
+ ${p}`)}}function Vr(){return typeof window<"u"&&typeof window.document<"u"}function Rr(a){return{ids:o1(a.ids),embeddings:a.embeddings?Ap(a.embeddings):void 0,metadatas:a.metadatas?o1(a.metadatas):void 0,documents:a.documents?o1(a.documents):void 0}}async function $a(a,e,t){let{ids:p,embeddings:d,metadatas:i,documents:r}=Rr(a);if(!d&&!r&&!t)throw new Error("embeddings and documents cannot both be undefined");let n=d||(r?await e.generate(r):void 0);if(!n&&!t)throw new Error("Failed to generate embeddings for your request.");for(let o=0;o<p.length;o+=1)if(typeof p[o]!="string")throw new Error(`Expected ids to be strings, found ${typeof p[o]} at index ${o}`);if(n!==void 0&&p.length!==n.length||i!==void 0&&p.length!==i.length||r!==void 0&&p.length!==r.length)throw new Error("ids, embeddings, metadatas, and documents must all be the same length");if(new Set(p).size!==p.length){let o=p.filter((l,c)=>p.indexOf(l)!==c);throw new Error(`ID's must be unique, found duplicates for: ${o}`)}return{ids:p,metadatas:i,documents:r,embeddings:n}}function Qa(a,e){return new Nr(e.name,e.id,a,e.embeddingFunction,e.metadata)}var Cr=a=>a==="AUTHORIZATION"?"Authorization":"X-Chroma-Token",Dr=a=>Buffer.from(a).toString("base64"),Or=class{constructor(a){let e=a??process.env.CHROMA_CLIENT_AUTH_CREDENTIALS;if(e===void 0)throw new Error("Credentials must be supplied via environment variable (CHROMA_CLIENT_AUTH_CREDENTIALS) or passed in as configuration.");this.credentials={Authorization:"Basic "+Dr(e)}}authenticate(){return this.credentials}},Ar=class{constructor(a,e="AUTHORIZATION"){let t=a??process.env.CHROMA_CLIENT_AUTH_CREDENTIALS;if(t===void 0)throw new Error("Credentials must be supplied via environment variable (CHROMA_CLIENT_AUTH_CREDENTIALS) or passed in as configuration.");let p=Cr(e),d=e==="AUTHORIZATION"?`Bearer ${t}`:t;this.credentials={},this.credentials[p]=d}authenticate(){return this.credentials}},Pp=a=>{if(a.provider===void 0)throw new Error("Auth provider not specified");if(a.credentials===void 0)throw new Error("Auth credentials not specified");switch(a.provider){case"basic":return new Or(a.credentials);case"token":return new Ar(a.credentials,a.tokenHeaderType);default:throw new Error("Invalid auth provider")}};function Pr(a){var e,t,p;return!!((a?.name==="TypeError"||a?.name==="FetchError")&&((e=a.message)!=null&&e.includes("fetch failed")||(t=a.message)!=null&&t.includes("Failed to fetch")||(p=a.message)!=null&&p.includes("ENOTFOUND")))}function Tp(a){let e=/(\w+)\('(.+)'\)/,t=a?.match(e);if(t){let[,p,d]=t;return p==="ValueError"?new _r(d):new hr(p,d)}return new fr("The server encountered an error while handling the request.")}var xp=async(a,e)=>{try{let t=await fetch(a,e),p=t.clone(),d=await p.json();if(!p.ok){let i=Er(d?.error,d?.message);if(i)throw i;switch(t.status){case 400:throw new vr(`Bad request to ${a} with status: ${t.statusText}`);case 401:throw new gr("Unauthorized");case 403:throw new wr("You do not have permission to access the requested resource.");case 404:throw new yr(`The requested resource could not be found: ${a}`);case 409:throw new Tr("The resource already exists");case 500:throw Tp(d?.error);case 502:case 503:case 504:throw new pa("Unable to connect to the chromadb server. Please try again later.")}throw new Error(`Failed to fetch ${a} with status ${t.status}: ${t.statusText}`)}if(d?.error)throw Tp(d.error);return t}catch(t){throw Pr(t)?new pa("Failed to connect to chromadb. Make sure your server is running and try again. If you are running from a browser, make sure that your chromadb instance is configured to allow requests from the current origin using the CHROMA_SERVER_CORS_ALLOW_ORIGINS environment variable.",t):t}},za="default_tenant",aa="default_database",xr=class{constructor({path:a,fetchOptions:e,auth:t,tenant:p=za,database:d=aa}={}){this.tenant=za,this.database=aa,a===void 0&&(a="http://localhost:8000"),this.tenant=p,this.database=d,this.authProvider=void 0;let i=new Op({basePath:a});this.api=new Dp(i,void 0,xp),this.api.options=e??{},t!==void 0&&(this.authProvider=Pp(t),this.api.options.headers=ta(ta({},this.api.options.headers),this.authProvider.authenticate()))}async setTenant({tenant:a=za,database:e=aa}){await Ga(this,a,e),this.tenant=a,this.database=e}async setDatabase({database:a=aa}){await Ga(this,this.tenant,a),this.database=a}async createTenant({name:a}){return await this.api.createTenant({name:a},this.api.options),{name:a}}async getTenant({name:a}){return{name:(await this.api.getTenant(a,this.api.options)).name}}async createDatabase({name:a,tenantName:e}){return await this.api.createDatabase(e,{name:a},this.api.options),{name:a}}async getDatabase({name:a,tenantName:e}){return await this.api.getDatabase(a,e,this.api.options)}async deleteDatabase({name:a,tenantName:e}){await this.api.deleteDatabase(a,e,this.api.options)}async listDatabases({limit:a,offset:e,tenantName:t}){return await this.api.listDatabases(t,a,e,this.api.options)}},Ep,Np=class Ip{constructor({model:e="Xenova/all-MiniLM-L6-v2",revision:t="main",quantized:p=!1,progress_callback:d=null}={}){this.model=e,this.revision=t,this.quantized=p,this.progress_callback=d}async generate(e){return await this.loadClient(),this.pipelinePromise=new Promise(async(d,i)=>{try{let r=this.transformersApi,n=this.quantized,s=this.revision,o=this.progress_callback;d(await r("feature-extraction",this.model,{quantized:n,revision:s,progress_callback:o}))}catch(r){i(r)}}),(await(await this.pipelinePromise)(e,{pooling:"mean",normalize:!0})).tolist()}async loadClient(){if(!this.transformersApi){try{let{pipeline:e}=await Ip.import();Ep=e}catch(e){throw e.code==="MODULE_NOT_FOUND"?new Error("Please install the chromadb-default-embed package to use the DefaultEmbeddingFunction, `npm install chromadb-default-embed`"):e}this.transformersApi=Ep}}static async import(){try{let e;Vr()?e=await import("https://unpkg.com/chromadb-default-embed@2.14.0"):e=await import("chromadb-default-embed");let{pipeline:t,env:p}=e;return p.allowLocalModels=!1,{pipeline:t}}catch{throw new Error("Please install chromadb-default-embed as a dependency with, e.g. `npm install chromadb-default-embed`")}}},Vp="default_tenant",Rp="default_database",Xa=class{constructor({path:a="http://localhost:8000",fetchOptions:e,auth:t,tenant:p=Vp,database:d=Rp}={}){this.tenant=p,this.database=d,this.authProvider=void 0;let i=new Op({basePath:a});this.api=new Dp(i,void 0,xp),this.api.options=e??{},t!==void 0&&(this.authProvider=Pp(t),this.api.options.headers=ta(ta({},this.api.options.headers),this.authProvider.authenticate())),this._adminClient=new xr({path:a,fetchOptions:e,auth:t,tenant:p,database:d})}async init(){return this._initPromise||(this.authProvider!==void 0&&await this.getUserIdentity(),this._initPromise=Ga(this._adminClient,this.tenant,this.database)),this._initPromise}async getUserIdentity(){let a=await this.api.getUserIdentity(this.api.options),e=a.tenant,t=a.databases;e!=null&&e!=="*"&&this.tenant==Vp&&(this.tenant=e),t!=null&&t.length==1&&t[0]!=="*"&&this.database==Rp&&(this.database=t[0])}async reset(){return await this.init(),await this.api.postV2Reset(this.api.options)}async version(){return await this.api.getV2Version(this.api.options)}async heartbeat(){return(await this.api.getV2Heartbeat(this.api.options))["nanosecond heartbeat"]}async createCollection({name:a,metadata:e,embeddingFunction:t=new Np}){await this.init();let p=await this.api.createCollection(this.tenant,this.database,{name:a,configuration:null,metadata:e},this.api.options);return Qa(this,{name:p.name,id:p.id,metadata:p.metadata,embeddingFunction:t})}async getOrCreateCollection({name:a,metadata:e,embeddingFunction:t=new Np}){await this.init();let p=await this.api.createCollection(this.tenant,this.database,{name:a,configuration:null,metadata:e,get_or_create:!0},this.api.options);return Qa(this,{name:p.name,id:p.id,metadata:p.metadata,embeddingFunction:t})}async listCollections({limit:a,offset:e}={}){return await this.init(),(await this.api.listCollections(this.tenant,this.database,a,e,this.api.options)).map(p=>p.name)}async listCollectionsAndMetadata({limit:a,offset:e}={}){return await this.init(),await this.api.listCollections(this.tenant,this.database,a,e,this.api.options)}async countCollections(){return await this.init(),await this.api.countCollections(this.tenant,this.database,this.api.options)}async getCollection({name:a,embeddingFunction:e}){await this.init();let t=await this.api.getCollection(this.tenant,this.database,a,this.api.options);return Qa(this,{name:t.name,id:t.id,metadata:t.metadata,embeddingFunction:e})}async deleteCollection({name:a}){await this.init(),await this.api.deleteCollection(a,this.tenant,this.database,this.api.options)}};var kp=require("fs");var da=class{circuit;maxFailures;cooldownMs;hasAttemptedRecovery;client;chromaDbUrl;mutex;collections;constructor(e){this.chromaDbUrl=e.chromaDbUrl,this.maxFailures=e.maxFailures??3,this.cooldownMs=e.cooldownMs??6e4,this.circuit={failures:0,lastFailure:0,state:"closed"},this.hasAttemptedRecovery=!1,this.client=null,this.mutex=Promise.resolve(),this.collections=new Map}async executeWithCircuitBreaker(e){if(this.circuit.state==="open")if(Date.now()-this.circuit.lastFailure>this.cooldownMs)this.circuit.state="half-open";else throw new Error("Circuit breaker open: ChromaDB unavailable");try{let t=await e();return this.circuit={failures:0,lastFailure:0,state:"closed"},t}catch(t){throw this.circuit.failures++,this.circuit.lastFailure=Date.now(),this.circuit.failures>=this.maxFailures&&(this.circuit.state="open",this.hasAttemptedRecovery||(this.hasAttemptedRecovery=!0,await this.recoverFromCorruptedDatabase())),t}}async getClient(){let e,t=new Promise(d=>e=d),p=this.mutex;this.mutex=t,await p;try{return this.client===null&&(this.client=new Xa({path:this.chromaDbUrl})),this.client}finally{e()}}async getCollection(e){let t,p=new Promise(i=>t=i),d=this.mutex;this.mutex=p,await d;try{let i=this.collections.get(e);if(i!==void 0)return i;this.client===null&&(this.client=new Xa({path:this.chromaDbUrl}));let r=await this.client.getOrCreateCollection({name:e});return this.collections.set(e,r),r}finally{t()}}async isAvailable(){if(this.circuit.state==="open")return!1;try{return await(await this.getClient()).heartbeat(),!0}catch{return!1}}reset(){this.circuit={failures:0,lastFailure:0,state:"closed"},this.hasAttemptedRecovery=!1,this.client=null,this.collections.clear()}async recoverFromCorruptedDatabase(){try{(0,kp.rmSync)(ct,{recursive:!0,force:!0})}catch{}}getCircuitState(){return this.circuit.state}getCircuitFailures(){return this.circuit.failures}};function jp(a){let e=[],t={observationId:a.id,project:a.project,type:a.type,createdAtEpoch:a.createdAtEpoch};a.narrative&&e.push({id:`obs_${a.id}_narrative`,document:a.narrative,metadata:{...t,field:"narrative"}}),a.text&&e.push({id:`obs_${a.id}_text`,document:a.text,metadata:{...t,field:"text"}});for(let p=0;p<a.facts.length;p++){let d=a.facts[p];d!==void 0&&e.push({id:`obs_${a.id}_fact_${p}`,document:d,metadata:{...t,field:"fact"}})}return e}function Lp(a){let e=[],t={summaryId:a.id,project:a.project,createdAtEpoch:a.createdAtEpoch},p=[["request",a.request],["investigated",a.investigated],["learned",a.learned],["completed",a.completed],["next_steps",a.nextSteps],["notes",a.notes]];for(let[d,i]of p)i&&e.push({id:`summary_${a.id}_${d}`,document:i,metadata:{...t,field:d}});return e}var Ir=10,kr=90,jr=100;function ia(a){return`cm__${a.length>0?a.toLowerCase():"default"}`}function Lr(a){let e=/^obs_(\d+)_/.exec(a);return e===null||e[1]===void 0?null:parseInt(e[1],10)}function Fr(a){let e=a.split("_");return e.length<3?"unknown":e[2]??"unknown"}var ra=class{connection;embeddingService;constructor(e,t){this.connection=e,this.embeddingService=t}async syncObservation(e){let t=jp(e);if(t.length===0)return;let p=ia(e.project),d=await this.connection.getCollection(p),i=t.map(n=>n.document),r=await this.embeddingService.getBatchEmbeddings(i);await d.upsert({ids:t.map(n=>n.id),documents:i,embeddings:r,metadatas:t.map(n=>n.metadata)})}async syncSummary(e){let t=Lp(e);if(t.length===0)return;let p=ia(e.project),d=await this.connection.getCollection(p),i=t.map(n=>n.document),r=await this.embeddingService.getBatchEmbeddings(i);await d.upsert({ids:t.map(n=>n.id),documents:i,embeddings:r,metadatas:t.map(n=>n.metadata)})}async query(e,t,p=Ir,d=kr){let i=ia(t),r=await this.connection.getCollection(i),n=Math.floor(Date.now()/1e3)-d*24*60*60,s=await r.query({queryEmbeddings:[e],nResults:p,where:{createdAtEpoch:{$gte:n}}}),o=s.ids[0]??[],l=s.distances?.[0]??[],c=new Set,C=[];for(let D=0;D<o.length;D++){let T=o[D];if(T==null)continue;let F=Lr(T);if(F===null||c.has(F))continue;c.add(F);let j=l[D]??0;C.push({observationId:F,score:1-j,field:Fr(T)})}return C}async vacuum(e){if(e===void 0)return;let t=ia(e);await(await this.connection.getCollection(t)).delete({})}async backfill(e,t=jr){for(let p=0;p<e.length;p+=t){let d=e.slice(p,p+t);await Promise.all(d.map(i=>this.syncObservation(i)))}}};function Wa(a){return a.split("/").filter(Boolean).map(e=>e.startsWith(":")?{kind:"param",name:e.slice(1)}:{kind:"literal",value:e})}function Ur(a,e){if(a.length!==e.length)return null;let t={};for(let p=0;p<a.length;p++){let d=a[p],i=e[p];if(d===void 0||i===void 0)return null;if(d.kind==="literal"){if(d.value!==i)return null}else t[d.name]=i}return t}function Fp(a,e){return new Response(JSON.stringify({error:a}),{status:e,headers:{"Content-Type":"application/json"}})}var na=class{routes=[];get(e,t){this.routes.push({method:"GET",segments:Wa(e),handler:t})}post(e,t){this.routes.push({method:"POST",segments:Wa(e),handler:t})}delete(e,t){this.routes.push({method:"DELETE",segments:Wa(e),handler:t})}async handle(e){let t=new URL(e.url),p=t.pathname.split("/").filter(Boolean),d=e.method.toUpperCase(),i=!1;for(let r of this.routes){let n=Ur(r.segments,p);if(n!==null&&(i=!0,r.method===d))return await r.handler(e,n)}return i?Fp(`Method ${d} not allowed`,405):Fp(`Route not found: ${t.pathname}`,404)}};function Mr(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Up(a,e){return`event: ${a}
221
221
  data: ${JSON.stringify(e)}
222
222
 
223
223
  `}var sa=class{clients=new Set;connect(){let e,t=new ReadableStream({start:p=>{e=p,this.clients.add(e),this.sendToController(e,"connected",{clientId:Mr(),timestamp:new Date().toISOString()})},cancel:()=>{this.clients.delete(e)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}broadcast(e,t){let p=Up(e,t),d=new TextEncoder().encode(p);for(let i of this.clients)try{i.enqueue(d)}catch{this.clients.delete(i)}}getClientCount(){return this.clients.size}disconnectAll(){for(let e of this.clients)try{e.close()}catch{}this.clients.clear()}sendToController(e,t,p){let d=Up(t,p);e.enqueue(new TextEncoder().encode(d))}};function Mp(a,e){a.get("/stream",()=>e.connect())}var Br=process.env.npm_package_version??"0.1.0",qr=Date.now();function Hr(a){return a==="core-ready"||a==="ready"}function $r(a){return a==="ready"}function l1(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function Bp(a,e){a.get("/api/health",()=>l1({build:Br,initState:e.initState,pid:process.pid,uptime:Math.floor((Date.now()-qr)/1e3)})),a.get("/api/core-ready",()=>Hr(e.initState)?l1({ready:!0}):l1({ready:!1,initState:e.initState},503)),a.get("/api/readiness",()=>$r(e.initState)?l1({ready:!0}):l1({ready:!1,initState:e.initState},503)),a.get("/api/process-stats",()=>{let t=process.memoryUsage();return l1({rss:t.rss,heapUsed:t.heapUsed,uptime:process.uptime()})})}var A={};rt(A,{BRAND:()=>v2,DIRTY:()=>je,EMPTY_PATH:()=>Xr,INVALID:()=>g,NEVER:()=>en,OK:()=>$,ParseStatus:()=>q,Schema:()=>N,ZodAny:()=>Oe,ZodArray:()=>_e,ZodBigInt:()=>Fe,ZodBoolean:()=>Ue,ZodBranded:()=>D1,ZodCatch:()=>Ze,ZodDate:()=>Me,ZodDefault:()=>We,ZodDiscriminatedUnion:()=>ma,ZodEffects:()=>ee,ZodEnum:()=>Ge,ZodError:()=>Q,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>ua,ZodIntersection:()=>$e,ZodIssueCode:()=>m,ZodLazy:()=>Qe,ZodLiteral:()=>ze,ZodMap:()=>v1,ZodNaN:()=>w1,ZodNativeEnum:()=>Xe,ZodNever:()=>de,ZodNull:()=>qe,ZodNullable:()=>ce,ZodNumber:()=>Le,ZodObject:()=>z,ZodOptional:()=>Y,ZodParsedType:()=>f,ZodPipeline:()=>O1,ZodPromise:()=>Ae,ZodReadonly:()=>Je,ZodRecord:()=>ca,ZodSchema:()=>N,ZodSet:()=>g1,ZodString:()=>De,ZodSymbol:()=>h1,ZodTransformer:()=>ee,ZodTuple:()=>me,ZodType:()=>N,ZodUndefined:()=>Be,ZodUnion:()=>He,ZodUnknown:()=>ye,ZodVoid:()=>f1,addIssueToContext:()=>u,any:()=>N2,array:()=>D2,bigint:()=>_2,boolean:()=>Yp,coerce:()=>K2,custom:()=>Wp,date:()=>b2,datetimeRegex:()=>Gp,defaultErrorMap:()=>ge,discriminatedUnion:()=>x2,effect:()=>Q2,enum:()=>q2,function:()=>U2,getErrorMap:()=>m1,getParsedType:()=>le,instanceof:()=>w2,intersection:()=>I2,isAborted:()=>oa,isAsync:()=>c1,isDirty:()=>la,isValid:()=>Ce,late:()=>g2,lazy:()=>M2,literal:()=>B2,makeIssue:()=>C1,map:()=>L2,nan:()=>y2,nativeEnum:()=>H2,never:()=>R2,null:()=>E2,nullable:()=>G2,number:()=>Jp,object:()=>O2,objectUtil:()=>Za,oboolean:()=>Y2,onumber:()=>J2,optional:()=>z2,ostring:()=>Z2,pipeline:()=>W2,preprocess:()=>X2,promise:()=>$2,quotelessJson:()=>Qr,record:()=>j2,set:()=>F2,setErrorMap:()=>Gr,strictObject:()=>A2,string:()=>Zp,symbol:()=>S2,transformer:()=>Q2,tuple:()=>k2,undefined:()=>T2,union:()=>P2,unknown:()=>V2,util:()=>R,void:()=>C2});var R;(function(a){a.assertEqual=d=>{};function e(d){}a.assertIs=e;function t(d){throw new Error}a.assertNever=t,a.arrayToEnum=d=>{let i={};for(let r of d)i[r]=r;return i},a.getValidEnumValues=d=>{let i=a.objectKeys(d).filter(n=>typeof d[d[n]]!="number"),r={};for(let n of i)r[n]=d[n];return a.objectValues(r)},a.objectValues=d=>a.objectKeys(d).map(function(i){return d[i]}),a.objectKeys=typeof Object.keys=="function"?d=>Object.keys(d):d=>{let i=[];for(let r in d)Object.prototype.hasOwnProperty.call(d,r)&&i.push(r);return i},a.find=(d,i)=>{for(let r of d)if(i(r))return r},a.isInteger=typeof Number.isInteger=="function"?d=>Number.isInteger(d):d=>typeof d=="number"&&Number.isFinite(d)&&Math.floor(d)===d;function p(d,i=" | "){return d.map(r=>typeof r=="string"?`'${r}'`:r).join(i)}a.joinValues=p,a.jsonStringifyReplacer=(d,i)=>typeof i=="bigint"?i.toString():i})(R||(R={}));var Za;(function(a){a.mergeShapes=(e,t)=>({...e,...t})})(Za||(Za={}));var f=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),le=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}};var m=R.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Qr=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:"),Q=class a extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=p=>{this.issues=[...this.issues,p]},this.addIssues=(p=[])=>{this.issues=[...this.issues,...p]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},p={_errors:[]},d=i=>{for(let r of i.issues)if(r.code==="invalid_union")r.unionErrors.map(d);else if(r.code==="invalid_return_type")d(r.returnTypeError);else if(r.code==="invalid_arguments")d(r.argumentsError);else if(r.path.length===0)p._errors.push(t(r));else{let n=p,s=0;for(;s<r.path.length;){let o=r.path[s];s===r.path.length-1?(n[o]=n[o]||{_errors:[]},n[o]._errors.push(t(r))):n[o]=n[o]||{_errors:[]},n=n[o],s++}}};return d(this),p}static assert(e){if(!(e instanceof a))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},p=[];for(let d of this.issues)if(d.path.length>0){let i=d.path[0];t[i]=t[i]||[],t[i].push(e(d))}else p.push(e(d));return{formErrors:p,fieldErrors:t}}get formErrors(){return this.flatten()}};Q.create=a=>new Q(a);var zr=(a,e)=>{let t;switch(a.code){case m.invalid_type:a.received===f.undefined?t="Required":t=`Expected ${a.expected}, received ${a.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(a.expected,R.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(a.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(a.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${R.joinValues(a.options)}, received '${a.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(t=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?t=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?t=`Invalid input: must end with "${a.validation.endsWith}"`:R.assertNever(a.validation):a.validation!=="regex"?t=`Invalid ${a.validation}`:t="Invalid";break;case m.too_small:a.type==="array"?t=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?t=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?t=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="bigint"?t=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?t=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:t="Invalid input";break;case m.too_big:a.type==="array"?t=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?t=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?t=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?t=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?t=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:t="Invalid input";break;case m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${a.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=e.defaultError,R.assertNever(a)}return{message:t}},ge=zr;var qp=ge;function Gr(a){qp=a}function m1(){return qp}var C1=a=>{let{data:e,path:t,errorMaps:p,issueData:d}=a,i=[...t,...d.path||[]],r={...d,path:i};if(d.message!==void 0)return{...d,path:i,message:d.message};let n="",s=p.filter(o=>!!o).slice().reverse();for(let o of s)n=o(r,{data:e,defaultError:n}).message;return{...d,path:i,message:n}},Xr=[];function u(a,e){let t=m1(),p=C1({issueData:e,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,t,t===ge?void 0:ge].filter(d=>!!d)});a.common.issues.push(p)}var q=class a{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let p=[];for(let d of t){if(d.status==="aborted")return g;d.status==="dirty"&&e.dirty(),p.push(d.value)}return{status:e.value,value:p}}static async mergeObjectAsync(e,t){let p=[];for(let d of t){let i=await d.key,r=await d.value;p.push({key:i,value:r})}return a.mergeObjectSync(e,p)}static mergeObjectSync(e,t){let p={};for(let d of t){let{key:i,value:r}=d;if(i.status==="aborted"||r.status==="aborted")return g;i.status==="dirty"&&e.dirty(),r.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof r.value<"u"||d.alwaysSet)&&(p[i.value]=r.value)}return{status:e.value,value:p}}},g=Object.freeze({status:"aborted"}),je=a=>({status:"dirty",value:a}),$=a=>({status:"valid",value:a}),oa=a=>a.status==="aborted",la=a=>a.status==="dirty",Ce=a=>a.status==="valid",c1=a=>typeof Promise<"u"&&a instanceof Promise;var v;(function(a){a.errToObj=e=>typeof e=="string"?{message:e}:e||{},a.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var K=class{constructor(e,t,p,d){this._cachedPath=[],this.parent=e,this.data=t,this._path=p,this._key=d}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Hp=(a,e)=>{if(Ce(e))return{success:!0,data:e.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Q(a.common.issues);return this._error=t,this._error}}};function E(a){if(!a)return{};let{errorMap:e,invalid_type_error:t,required_error:p,description:d}=a;if(e&&(t||p))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:d}:{errorMap:(r,n)=>{let{message:s}=a;return r.code==="invalid_enum_value"?{message:s??n.defaultError}:typeof n.data>"u"?{message:s??p??n.defaultError}:r.code!=="invalid_type"?{message:n.defaultError}:{message:s??t??n.defaultError}},description:d}}var N=class{get description(){return this._def.description}_getType(e){return le(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(c1(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let p=this.safeParse(e,t);if(p.success)return p.data;throw p.error}safeParse(e,t){let p={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)},d=this._parseSync({data:e,path:p.path,parent:p});return Hp(p,d)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)};if(!this["~standard"].async)try{let p=this._parseSync({data:e,path:[],parent:t});return Ce(p)?{value:p.value}:{issues:t.common.issues}}catch(p){p?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(p=>Ce(p)?{value:p.value}:{issues:t.common.issues})}async parseAsync(e,t){let p=await this.safeParseAsync(e,t);if(p.success)return p.data;throw p.error}async safeParseAsync(e,t){let p={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)},d=this._parse({data:e,path:p.path,parent:p}),i=await(c1(d)?d:Promise.resolve(d));return Hp(p,i)}refine(e,t){let p=d=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(d):t;return this._refinement((d,i)=>{let r=e(d),n=()=>i.addIssue({code:m.custom,...p(d)});return typeof Promise<"u"&&r instanceof Promise?r.then(s=>s?!0:(n(),!1)):r?!0:(n(),!1)})}refinement(e,t){return this._refinement((p,d)=>e(p)?!0:(d.addIssue(typeof t=="function"?t(p,d):t),!1))}_refinement(e){return new ee({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Y.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _e.create(this)}promise(){return Ae.create(this,this._def)}or(e){return He.create([this,e],this._def)}and(e){return $e.create(this,e,this._def)}transform(e){return new ee({...E(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new We({...E(this._def),innerType:this,defaultValue:t,typeName:w.ZodDefault})}brand(){return new D1({typeName:w.ZodBranded,type:this,...E(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ze({...E(this._def),innerType:this,catchValue:t,typeName:w.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return O1.create(this,e)}readonly(){return Je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Wr=/^c[^\s-]{8,}$/i,Zr=/^[0-9a-z]+$/,Jr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kr=/^[a-z0-9_-]{21}$/i,e2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,a2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,t2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ja,d2=/^(?:(?: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])$/,i2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,r2=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,n2=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,s2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,o2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qp="((\\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])))",l2=new RegExp(`^${Qp}$`);function zp(a){let e="[0-5]\\d";a.precision?e=`${e}\\.\\d{${a.precision}}`:a.precision==null&&(e=`${e}(\\.\\d+)?`);let t=a.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function m2(a){return new RegExp(`^${zp(a)}$`)}function Gp(a){let e=`${Qp}T${zp(a)}`,t=[];return t.push(a.local?"Z?":"Z"),a.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function c2(a,e){return!!((e==="v4"||!e)&&d2.test(a)||(e==="v6"||!e)&&r2.test(a))}function u2(a,e){if(!e2.test(a))return!1;try{let[t]=a.split(".");if(!t)return!1;let p=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),d=JSON.parse(atob(p));return!(typeof d!="object"||d===null||"typ"in d&&d?.typ!=="JWT"||!d.alg||e&&d.alg!==e)}catch{return!1}}function h2(a,e){return!!((e==="v4"||!e)&&i2.test(a)||(e==="v6"||!e)&&n2.test(a))}var De=class a extends N{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return u(i,{code:m.invalid_type,expected:f.string,received:i.parsedType}),g}let p=new q,d;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(d=this._getOrReturnCtx(e,d),u(d,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),p.dirty());else if(i.kind==="max")e.data.length>i.value&&(d=this._getOrReturnCtx(e,d),u(d,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),p.dirty());else if(i.kind==="length"){let r=e.data.length>i.value,n=e.data.length<i.value;(r||n)&&(d=this._getOrReturnCtx(e,d),r?u(d,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&u(d,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),p.dirty())}else if(i.kind==="email")t2.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"email",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="emoji")Ja||(Ja=new RegExp(p2,"u")),Ja.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"emoji",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="uuid")Yr.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"uuid",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="nanoid")Kr.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"nanoid",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="cuid")Wr.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"cuid",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="cuid2")Zr.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"cuid2",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="ulid")Jr.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"ulid",code:m.invalid_string,message:i.message}),p.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{d=this._getOrReturnCtx(e,d),u(d,{validation:"url",code:m.invalid_string,message:i.message}),p.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"regex",code:m.invalid_string,message:i.message}),p.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),p.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:{startsWith:i.value},message:i.message}),p.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:{endsWith:i.value},message:i.message}),p.dirty()):i.kind==="datetime"?Gp(i).test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:"datetime",message:i.message}),p.dirty()):i.kind==="date"?l2.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:"date",message:i.message}),p.dirty()):i.kind==="time"?m2(i).test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{code:m.invalid_string,validation:"time",message:i.message}),p.dirty()):i.kind==="duration"?a2.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"duration",code:m.invalid_string,message:i.message}),p.dirty()):i.kind==="ip"?c2(e.data,i.version)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"ip",code:m.invalid_string,message:i.message}),p.dirty()):i.kind==="jwt"?u2(e.data,i.alg)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"jwt",code:m.invalid_string,message:i.message}),p.dirty()):i.kind==="cidr"?h2(e.data,i.version)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"cidr",code:m.invalid_string,message:i.message}),p.dirty()):i.kind==="base64"?s2.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"base64",code:m.invalid_string,message:i.message}),p.dirty()):i.kind==="base64url"?o2.test(e.data)||(d=this._getOrReturnCtx(e,d),u(d,{validation:"base64url",code:m.invalid_string,message:i.message}),p.dirty()):R.assertNever(i);return{status:p.value,value:e.data}}_regex(e,t,p){return this.refinement(d=>e.test(d),{validation:t,code:m.invalid_string,...v.errToObj(p)})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new a({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new a({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new a({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};De.create=a=>new De({checks:[],typeName:w.ZodString,coerce:a?.coerce??!1,...E(a)});function f2(a,e){let t=(a.toString().split(".")[1]||"").length,p=(e.toString().split(".")[1]||"").length,d=t>p?t:p,i=Number.parseInt(a.toFixed(d).replace(".","")),r=Number.parseInt(e.toFixed(d).replace(".",""));return i%r/10**d}var Le=class a extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return u(i,{code:m.invalid_type,expected:f.number,received:i.parsedType}),g}let p,d=new q;for(let i of this._def.checks)i.kind==="int"?R.isInteger(e.data)||(p=this._getOrReturnCtx(e,p),u(p,{code:m.invalid_type,expected:"integer",received:"float",message:i.message}),d.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),d.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),d.dirty()):i.kind==="multipleOf"?f2(e.data,i.value)!==0&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),d.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(p=this._getOrReturnCtx(e,p),u(p,{code:m.not_finite,message:i.message}),d.dirty()):R.assertNever(i);return{status:d.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,p,d){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:p,message:v.toString(d)}]})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let p of this._def.checks){if(p.kind==="finite"||p.kind==="int"||p.kind==="multipleOf")return!0;p.kind==="min"?(t===null||p.value>t)&&(t=p.value):p.kind==="max"&&(e===null||p.value<e)&&(e=p.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Le.create=a=>new Le({checks:[],typeName:w.ZodNumber,coerce:a?.coerce||!1,...E(a)});var Fe=class a extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let p,d=new q;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),d.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),d.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(p=this._getOrReturnCtx(e,p),u(p,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),d.dirty()):R.assertNever(i);return{status:d.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return u(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,p,d){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:p,message:v.toString(d)}]})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Fe.create=a=>new Fe({checks:[],typeName:w.ZodBigInt,coerce:a?.coerce??!1,...E(a)});var Ue=class extends N{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.boolean,received:p.parsedType}),g}return $(e.data)}};Ue.create=a=>new Ue({typeName:w.ZodBoolean,coerce:a?.coerce||!1,...E(a)});var Me=class a extends N{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return u(i,{code:m.invalid_type,expected:f.date,received:i.parsedType}),g}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return u(i,{code:m.invalid_date}),g}let p=new q,d;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(d=this._getOrReturnCtx(e,d),u(d,{code:m.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),p.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(d=this._getOrReturnCtx(e,d),u(d,{code:m.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),p.dirty()):R.assertNever(i);return{status:p.value,value:new Date(e.data.getTime())}}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Me.create=a=>new Me({checks:[],coerce:a?.coerce||!1,typeName:w.ZodDate,...E(a)});var h1=class extends N{_parse(e){if(this._getType(e)!==f.symbol){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.symbol,received:p.parsedType}),g}return $(e.data)}};h1.create=a=>new h1({typeName:w.ZodSymbol,...E(a)});var Be=class extends N{_parse(e){if(this._getType(e)!==f.undefined){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.undefined,received:p.parsedType}),g}return $(e.data)}};Be.create=a=>new Be({typeName:w.ZodUndefined,...E(a)});var qe=class extends N{_parse(e){if(this._getType(e)!==f.null){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.null,received:p.parsedType}),g}return $(e.data)}};qe.create=a=>new qe({typeName:w.ZodNull,...E(a)});var Oe=class extends N{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};Oe.create=a=>new Oe({typeName:w.ZodAny,...E(a)});var ye=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};ye.create=a=>new ye({typeName:w.ZodUnknown,...E(a)});var de=class extends N{_parse(e){let t=this._getOrReturnCtx(e);return u(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),g}};de.create=a=>new de({typeName:w.ZodNever,...E(a)});var f1=class extends N{_parse(e){if(this._getType(e)!==f.undefined){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.void,received:p.parsedType}),g}return $(e.data)}};f1.create=a=>new f1({typeName:w.ZodVoid,...E(a)});var _e=class a extends N{_parse(e){let{ctx:t,status:p}=this._processInputParams(e),d=this._def;if(t.parsedType!==f.array)return u(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),g;if(d.exactLength!==null){let r=t.data.length>d.exactLength.value,n=t.data.length<d.exactLength.value;(r||n)&&(u(t,{code:r?m.too_big:m.too_small,minimum:n?d.exactLength.value:void 0,maximum:r?d.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:d.exactLength.message}),p.dirty())}if(d.minLength!==null&&t.data.length<d.minLength.value&&(u(t,{code:m.too_small,minimum:d.minLength.value,type:"array",inclusive:!0,exact:!1,message:d.minLength.message}),p.dirty()),d.maxLength!==null&&t.data.length>d.maxLength.value&&(u(t,{code:m.too_big,maximum:d.maxLength.value,type:"array",inclusive:!0,exact:!1,message:d.maxLength.message}),p.dirty()),t.common.async)return Promise.all([...t.data].map((r,n)=>d.type._parseAsync(new K(t,r,t.path,n)))).then(r=>q.mergeArray(p,r));let i=[...t.data].map((r,n)=>d.type._parseSync(new K(t,r,t.path,n)));return q.mergeArray(p,i)}get element(){return this._def.type}min(e,t){return new a({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new a({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new a({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}};_e.create=(a,e)=>new _e({type:a,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...E(e)});function u1(a){if(a instanceof z){let e={};for(let t in a.shape){let p=a.shape[t];e[t]=Y.create(u1(p))}return new z({...a._def,shape:()=>e})}else return a instanceof _e?new _e({...a._def,type:u1(a.element)}):a instanceof Y?Y.create(u1(a.unwrap())):a instanceof ce?ce.create(u1(a.unwrap())):a instanceof me?me.create(a.items.map(e=>u1(e))):a}var z=class a extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=R.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let o=this._getOrReturnCtx(e);return u(o,{code:m.invalid_type,expected:f.object,received:o.parsedType}),g}let{status:p,ctx:d}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),n=[];if(!(this._def.catchall instanceof de&&this._def.unknownKeys==="strip"))for(let o in d.data)r.includes(o)||n.push(o);let s=[];for(let o of r){let l=i[o],c=d.data[o];s.push({key:{status:"valid",value:o},value:l._parse(new K(d,c,d.path,o)),alwaysSet:o in d.data})}if(this._def.catchall instanceof de){let o=this._def.unknownKeys;if(o==="passthrough")for(let l of n)s.push({key:{status:"valid",value:l},value:{status:"valid",value:d.data[l]}});else if(o==="strict")n.length>0&&(u(d,{code:m.unrecognized_keys,keys:n}),p.dirty());else if(o!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let o=this._def.catchall;for(let l of n){let c=d.data[l];s.push({key:{status:"valid",value:l},value:o._parse(new K(d,c,d.path,l)),alwaysSet:l in d.data})}}return d.common.async?Promise.resolve().then(async()=>{let o=[];for(let l of s){let c=await l.key,C=await l.value;o.push({key:c,value:C,alwaysSet:l.alwaysSet})}return o}).then(o=>q.mergeObjectSync(p,o)):q.mergeObjectSync(p,s)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new a({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,p)=>{let d=this._def.errorMap?.(t,p).message??p.defaultError;return t.code==="unrecognized_keys"?{message:v.errToObj(e).message??d}:{message:d}}}:{}})}strip(){return new a({...this._def,unknownKeys:"strip"})}passthrough(){return new a({...this._def,unknownKeys:"passthrough"})}extend(e){return new a({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new a({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new a({...this._def,catchall:e})}pick(e){let t={};for(let p of R.objectKeys(e))e[p]&&this.shape[p]&&(t[p]=this.shape[p]);return new a({...this._def,shape:()=>t})}omit(e){let t={};for(let p of R.objectKeys(this.shape))e[p]||(t[p]=this.shape[p]);return new a({...this._def,shape:()=>t})}deepPartial(){return u1(this)}partial(e){let t={};for(let p of R.objectKeys(this.shape)){let d=this.shape[p];e&&!e[p]?t[p]=d:t[p]=d.optional()}return new a({...this._def,shape:()=>t})}required(e){let t={};for(let p of R.objectKeys(this.shape))if(e&&!e[p])t[p]=this.shape[p];else{let i=this.shape[p];for(;i instanceof Y;)i=i._def.innerType;t[p]=i}return new a({...this._def,shape:()=>t})}keyof(){return Xp(R.objectKeys(this.shape))}};z.create=(a,e)=>new z({shape:()=>a,unknownKeys:"strip",catchall:de.create(),typeName:w.ZodObject,...E(e)});z.strictCreate=(a,e)=>new z({shape:()=>a,unknownKeys:"strict",catchall:de.create(),typeName:w.ZodObject,...E(e)});z.lazycreate=(a,e)=>new z({shape:a,unknownKeys:"strip",catchall:de.create(),typeName:w.ZodObject,...E(e)});var He=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),p=this._def.options;function d(i){for(let n of i)if(n.result.status==="valid")return n.result;for(let n of i)if(n.result.status==="dirty")return t.common.issues.push(...n.ctx.common.issues),n.result;let r=i.map(n=>new Q(n.ctx.common.issues));return u(t,{code:m.invalid_union,unionErrors:r}),g}if(t.common.async)return Promise.all(p.map(async i=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(d);{let i,r=[];for(let s of p){let o={...t,common:{...t.common,issues:[]},parent:null},l=s._parseSync({data:t.data,path:t.path,parent:o});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:o}),o.common.issues.length&&r.push(o.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let n=r.map(s=>new Q(s));return u(t,{code:m.invalid_union,unionErrors:n}),g}}get options(){return this._def.options}};He.create=(a,e)=>new He({options:a,typeName:w.ZodUnion,...E(e)});var we=a=>a instanceof Qe?we(a.schema):a instanceof ee?we(a.innerType()):a instanceof ze?[a.value]:a instanceof Ge?a.options:a instanceof Xe?R.objectValues(a.enum):a instanceof We?we(a._def.innerType):a instanceof Be?[void 0]:a instanceof qe?[null]:a instanceof Y?[void 0,...we(a.unwrap())]:a instanceof ce?[null,...we(a.unwrap())]:a instanceof D1||a instanceof Je?we(a.unwrap()):a instanceof Ze?we(a._def.innerType):[],ma=class a extends N{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return u(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),g;let p=this.discriminator,d=t.data[p],i=this.optionsMap.get(d);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[p]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,p){let d=new Map;for(let i of t){let r=we(i.shape[e]);if(!r.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of r){if(d.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);d.set(n,i)}}return new a({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:d,...E(p)})}};function Ya(a,e){let t=le(a),p=le(e);if(a===e)return{valid:!0,data:a};if(t===f.object&&p===f.object){let d=R.objectKeys(e),i=R.objectKeys(a).filter(n=>d.indexOf(n)!==-1),r={...a,...e};for(let n of i){let s=Ya(a[n],e[n]);if(!s.valid)return{valid:!1};r[n]=s.data}return{valid:!0,data:r}}else if(t===f.array&&p===f.array){if(a.length!==e.length)return{valid:!1};let d=[];for(let i=0;i<a.length;i++){let r=a[i],n=e[i],s=Ya(r,n);if(!s.valid)return{valid:!1};d.push(s.data)}return{valid:!0,data:d}}else return t===f.date&&p===f.date&&+a==+e?{valid:!0,data:a}:{valid:!1}}var $e=class extends N{_parse(e){let{status:t,ctx:p}=this._processInputParams(e),d=(i,r)=>{if(oa(i)||oa(r))return g;let n=Ya(i.value,r.value);return n.valid?((la(i)||la(r))&&t.dirty(),{status:t.value,value:n.data}):(u(p,{code:m.invalid_intersection_types}),g)};return p.common.async?Promise.all([this._def.left._parseAsync({data:p.data,path:p.path,parent:p}),this._def.right._parseAsync({data:p.data,path:p.path,parent:p})]).then(([i,r])=>d(i,r)):d(this._def.left._parseSync({data:p.data,path:p.path,parent:p}),this._def.right._parseSync({data:p.data,path:p.path,parent:p}))}};$e.create=(a,e,t)=>new $e({left:a,right:e,typeName:w.ZodIntersection,...E(t)});var me=class a extends N{_parse(e){let{status:t,ctx:p}=this._processInputParams(e);if(p.parsedType!==f.array)return u(p,{code:m.invalid_type,expected:f.array,received:p.parsedType}),g;if(p.data.length<this._def.items.length)return u(p,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&p.data.length>this._def.items.length&&(u(p,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...p.data].map((r,n)=>{let s=this._def.items[n]||this._def.rest;return s?s._parse(new K(p,r,p.path,n)):null}).filter(r=>!!r);return p.common.async?Promise.all(i).then(r=>q.mergeArray(t,r)):q.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new a({...this._def,rest:e})}};me.create=(a,e)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new me({items:a,typeName:w.ZodTuple,rest:null,...E(e)})};var ca=class a extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:p}=this._processInputParams(e);if(p.parsedType!==f.object)return u(p,{code:m.invalid_type,expected:f.object,received:p.parsedType}),g;let d=[],i=this._def.keyType,r=this._def.valueType;for(let n in p.data)d.push({key:i._parse(new K(p,n,p.path,n)),value:r._parse(new K(p,p.data[n],p.path,n)),alwaysSet:n in p.data});return p.common.async?q.mergeObjectAsync(t,d):q.mergeObjectSync(t,d)}get element(){return this._def.valueType}static create(e,t,p){return t instanceof N?new a({keyType:e,valueType:t,typeName:w.ZodRecord,...E(p)}):new a({keyType:De.create(),valueType:e,typeName:w.ZodRecord,...E(t)})}},v1=class extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:p}=this._processInputParams(e);if(p.parsedType!==f.map)return u(p,{code:m.invalid_type,expected:f.map,received:p.parsedType}),g;let d=this._def.keyType,i=this._def.valueType,r=[...p.data.entries()].map(([n,s],o)=>({key:d._parse(new K(p,n,p.path,[o,"key"])),value:i._parse(new K(p,s,p.path,[o,"value"]))}));if(p.common.async){let n=new Map;return Promise.resolve().then(async()=>{for(let s of r){let o=await s.key,l=await s.value;if(o.status==="aborted"||l.status==="aborted")return g;(o.status==="dirty"||l.status==="dirty")&&t.dirty(),n.set(o.value,l.value)}return{status:t.value,value:n}})}else{let n=new Map;for(let s of r){let o=s.key,l=s.value;if(o.status==="aborted"||l.status==="aborted")return g;(o.status==="dirty"||l.status==="dirty")&&t.dirty(),n.set(o.value,l.value)}return{status:t.value,value:n}}}};v1.create=(a,e,t)=>new v1({valueType:e,keyType:a,typeName:w.ZodMap,...E(t)});var g1=class a extends N{_parse(e){let{status:t,ctx:p}=this._processInputParams(e);if(p.parsedType!==f.set)return u(p,{code:m.invalid_type,expected:f.set,received:p.parsedType}),g;let d=this._def;d.minSize!==null&&p.data.size<d.minSize.value&&(u(p,{code:m.too_small,minimum:d.minSize.value,type:"set",inclusive:!0,exact:!1,message:d.minSize.message}),t.dirty()),d.maxSize!==null&&p.data.size>d.maxSize.value&&(u(p,{code:m.too_big,maximum:d.maxSize.value,type:"set",inclusive:!0,exact:!1,message:d.maxSize.message}),t.dirty());let i=this._def.valueType;function r(s){let o=new Set;for(let l of s){if(l.status==="aborted")return g;l.status==="dirty"&&t.dirty(),o.add(l.value)}return{status:t.value,value:o}}let n=[...p.data.values()].map((s,o)=>i._parse(new K(p,s,p.path,o)));return p.common.async?Promise.all(n).then(s=>r(s)):r(n)}min(e,t){return new a({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new a({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};g1.create=(a,e)=>new g1({valueType:a,minSize:null,maxSize:null,typeName:w.ZodSet,...E(e)});var ua=class a extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return u(t,{code:m.invalid_type,expected:f.function,received:t.parsedType}),g;function p(n,s){return C1({data:n,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m1(),ge].filter(o=>!!o),issueData:{code:m.invalid_arguments,argumentsError:s}})}function d(n,s){return C1({data:n,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m1(),ge].filter(o=>!!o),issueData:{code:m.invalid_return_type,returnTypeError:s}})}let i={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof Ae){let n=this;return $(async function(...s){let o=new Q([]),l=await n._def.args.parseAsync(s,i).catch(D=>{throw o.addIssue(p(s,D)),o}),c=await Reflect.apply(r,this,l);return await n._def.returns._def.type.parseAsync(c,i).catch(D=>{throw o.addIssue(d(c,D)),o})})}else{let n=this;return $(function(...s){let o=n._def.args.safeParse(s,i);if(!o.success)throw new Q([p(s,o.error)]);let l=Reflect.apply(r,this,o.data),c=n._def.returns.safeParse(l,i);if(!c.success)throw new Q([d(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new a({...this._def,args:me.create(e).rest(ye.create())})}returns(e){return new a({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,p){return new a({args:e||me.create([]).rest(ye.create()),returns:t||ye.create(),typeName:w.ZodFunction,...E(p)})}},Qe=class extends N{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Qe.create=(a,e)=>new Qe({getter:a,typeName:w.ZodLazy,...E(e)});var ze=class extends N{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};ze.create=(a,e)=>new ze({value:a,typeName:w.ZodLiteral,...E(e)});function Xp(a,e){return new Ge({values:a,typeName:w.ZodEnum,...E(e)})}var Ge=class a extends N{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),p=this._def.values;return u(t,{expected:R.joinValues(p),received:t.parsedType,code:m.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),p=this._def.values;return u(t,{received:t.data,code:m.invalid_enum_value,options:p}),g}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return a.create(e,{...this._def,...t})}exclude(e,t=this._def){return a.create(this.options.filter(p=>!e.includes(p)),{...this._def,...t})}};Ge.create=Xp;var Xe=class extends N{_parse(e){let t=R.getValidEnumValues(this._def.values),p=this._getOrReturnCtx(e);if(p.parsedType!==f.string&&p.parsedType!==f.number){let d=R.objectValues(t);return u(p,{expected:R.joinValues(d),received:p.parsedType,code:m.invalid_type}),g}if(this._cache||(this._cache=new Set(R.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let d=R.objectValues(t);return u(p,{received:p.data,code:m.invalid_enum_value,options:d}),g}return $(e.data)}get enum(){return this._def.values}};Xe.create=(a,e)=>new Xe({values:a,typeName:w.ZodNativeEnum,...E(e)});var Ae=class extends N{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return u(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),g;let p=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(p.then(d=>this._def.type.parseAsync(d,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ae.create=(a,e)=>new Ae({type:a,typeName:w.ZodPromise,...E(e)});var ee=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:p}=this._processInputParams(e),d=this._def.effect||null,i={addIssue:r=>{u(p,r),r.fatal?t.abort():t.dirty()},get path(){return p.path}};if(i.addIssue=i.addIssue.bind(i),d.type==="preprocess"){let r=d.transform(p.data,i);if(p.common.async)return Promise.resolve(r).then(async n=>{if(t.value==="aborted")return g;let s=await this._def.schema._parseAsync({data:n,path:p.path,parent:p});return s.status==="aborted"?g:s.status==="dirty"?je(s.value):t.value==="dirty"?je(s.value):s});{if(t.value==="aborted")return g;let n=this._def.schema._parseSync({data:r,path:p.path,parent:p});return n.status==="aborted"?g:n.status==="dirty"?je(n.value):t.value==="dirty"?je(n.value):n}}if(d.type==="refinement"){let r=n=>{let s=d.refinement(n,i);if(p.common.async)return Promise.resolve(s);if(s instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return n};if(p.common.async===!1){let n=this._def.schema._parseSync({data:p.data,path:p.path,parent:p});return n.status==="aborted"?g:(n.status==="dirty"&&t.dirty(),r(n.value),{status:t.value,value:n.value})}else return this._def.schema._parseAsync({data:p.data,path:p.path,parent:p}).then(n=>n.status==="aborted"?g:(n.status==="dirty"&&t.dirty(),r(n.value).then(()=>({status:t.value,value:n.value}))))}if(d.type==="transform")if(p.common.async===!1){let r=this._def.schema._parseSync({data:p.data,path:p.path,parent:p});if(!Ce(r))return g;let n=d.transform(r.value,i);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}else return this._def.schema._parseAsync({data:p.data,path:p.path,parent:p}).then(r=>Ce(r)?Promise.resolve(d.transform(r.value,i)).then(n=>({status:t.value,value:n})):g);R.assertNever(d)}};ee.create=(a,e,t)=>new ee({schema:a,typeName:w.ZodEffects,effect:e,...E(t)});ee.createWithPreprocess=(a,e,t)=>new ee({schema:e,effect:{type:"preprocess",transform:a},typeName:w.ZodEffects,...E(t)});var Y=class extends N{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Y.create=(a,e)=>new Y({innerType:a,typeName:w.ZodOptional,...E(e)});var ce=class extends N{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(a,e)=>new ce({innerType:a,typeName:w.ZodNullable,...E(e)});var We=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),p=t.data;return t.parsedType===f.undefined&&(p=this._def.defaultValue()),this._def.innerType._parse({data:p,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};We.create=(a,e)=>new We({innerType:a,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});var Ze=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),p={...t,common:{...t.common,issues:[]}},d=this._def.innerType._parse({data:p.data,path:p.path,parent:{...p}});return c1(d)?d.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Q(p.common.issues)},input:p.data})})):{status:"valid",value:d.status==="valid"?d.value:this._def.catchValue({get error(){return new Q(p.common.issues)},input:p.data})}}removeCatch(){return this._def.innerType}};Ze.create=(a,e)=>new Ze({innerType:a,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});var w1=class extends N{_parse(e){if(this._getType(e)!==f.nan){let p=this._getOrReturnCtx(e);return u(p,{code:m.invalid_type,expected:f.nan,received:p.parsedType}),g}return{status:"valid",value:e.data}}};w1.create=a=>new w1({typeName:w.ZodNaN,...E(a)});var v2=Symbol("zod_brand"),D1=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),p=t.data;return this._def.type._parse({data:p,path:t.path,parent:t})}unwrap(){return this._def.type}},O1=class a extends N{_parse(e){let{status:t,ctx:p}=this._processInputParams(e);if(p.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:p.data,path:p.path,parent:p});return i.status==="aborted"?g:i.status==="dirty"?(t.dirty(),je(i.value)):this._def.out._parseAsync({data:i.value,path:p.path,parent:p})})();{let d=this._def.in._parseSync({data:p.data,path:p.path,parent:p});return d.status==="aborted"?g:d.status==="dirty"?(t.dirty(),{status:"dirty",value:d.value}):this._def.out._parseSync({data:d.value,path:p.path,parent:p})}}static create(e,t){return new a({in:e,out:t,typeName:w.ZodPipeline})}},Je=class extends N{_parse(e){let t=this._def.innerType._parse(e),p=d=>(Ce(d)&&(d.value=Object.freeze(d.value)),d);return c1(t)?t.then(d=>p(d)):p(t)}unwrap(){return this._def.innerType}};Je.create=(a,e)=>new Je({innerType:a,typeName:w.ZodReadonly,...E(e)});function $p(a,e){let t=typeof a=="function"?a(e):typeof a=="string"?{message:a}:a;return typeof t=="string"?{message:t}:t}function Wp(a,e={},t){return a?Oe.create().superRefine((p,d)=>{let i=a(p);if(i instanceof Promise)return i.then(r=>{if(!r){let n=$p(e,p),s=n.fatal??t??!0;d.addIssue({code:"custom",...n,fatal:s})}});if(!i){let r=$p(e,p),n=r.fatal??t??!0;d.addIssue({code:"custom",...r,fatal:n})}}):Oe.create()}var g2={object:z.lazycreate},w;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(w||(w={}));var w2=(a,e={message:`Input not instance of ${a.name}`})=>Wp(t=>t instanceof a,e),Zp=De.create,Jp=Le.create,y2=w1.create,_2=Fe.create,Yp=Ue.create,b2=Me.create,S2=h1.create,T2=Be.create,E2=qe.create,N2=Oe.create,V2=ye.create,R2=de.create,C2=f1.create,D2=_e.create,O2=z.create,A2=z.strictCreate,P2=He.create,x2=ma.create,I2=$e.create,k2=me.create,j2=ca.create,L2=v1.create,F2=g1.create,U2=ua.create,M2=Qe.create,B2=ze.create,q2=Ge.create,H2=Xe.create,$2=Ae.create,Q2=ee.create,z2=Y.create,G2=ce.create,X2=ee.createWithPreprocess,W2=O1.create,Z2=()=>Zp().optional(),J2=()=>Jp().optional(),Y2=()=>Yp().optional(),K2={string:(a=>De.create({...a,coerce:!0})),number:(a=>Le.create({...a,coerce:!0})),boolean:(a=>Ue.create({...a,coerce:!0})),bigint:(a=>Fe.create({...a,coerce:!0})),date:(a=>Me.create({...a,coerce:!0}))};var en=g;var Kp=A.object({text:A.string().min(1),title:A.string().optional(),project:A.string().optional()}),ed=A.object({query:A.string().optional(),limit:A.number().int().min(1).max(100).default(20),type:A.string().optional(),project:A.string().optional(),dateStart:A.string().optional(),dateEnd:A.string().optional()}),ad=A.object({query:A.string().min(1)}),td=A.object({anchor:A.string().min(1),depth_before:A.number().int().min(0).default(5),depth_after:A.number().int().min(0).default(5)}),Ka=A.object({ids:A.array(A.number().int()).min(1)}),s0=A.object({contentSessionId:A.string().min(1),project:A.string().min(1),memorySessionId:A.string().optional()});var an="default";function pd(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function ha(a,e){return pd({error:a},e)}function dd(a,e){a.post("/api/memory/save",async t=>{let{observationWriter:p,sessionManager:d}=e;if(p===void 0||d===void 0)return ha("Service unavailable",503);let i;try{i=await t.json()}catch{return ha("Invalid JSON body",400)}let r=Kp.safeParse(i);if(!r.success)return ha(r.error.issues[0]?.message??"Validation error",400);let{text:n,title:s,project:o=an}=r.data;try{let l=d.createSession({contentSessionId:crypto.randomUUID(),project:o}),c={memorySessionId:l.memorySessionId,sessionDbId:l.id,contentSessionId:l.contentSessionId,project:o,text:n,...s!==void 0?{title:s}:{}},C=await p.write(c);return pd({success:!0,id:C.id,title:C.title??s??"",project:C.project,message:"Observation saved"})}catch(l){let c=l instanceof Error?l.message:"Failed to save observation";return ha(c,500)}})}function et(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function y1(a,e){return et({error:a},e)}function tn(a){let e={},t=a.searchParams.get("query");t!==null&&(e.query=t);let p=a.searchParams.get("limit");if(p!==null){let s=Number(p);e.limit=isNaN(s)?p:s}let d=a.searchParams.get("type");d!==null&&(e.type=d);let i=a.searchParams.get("project");i!==null&&(e.project=i);let r=a.searchParams.get("dateStart");r!==null&&(e.dateStart=r);let n=a.searchParams.get("dateEnd");return n!==null&&(e.dateEnd=n),e}function id(a,e){a.get("/api/search",async t=>{let{searchManager:p}=e;if(p===void 0)return y1("Service unavailable",503);let d=new URL(t.url),i=tn(d),r=ed.safeParse(i);if(!r.success)return y1(r.error.issues[0]?.message??"Validation error",400);let{query:n,limit:s,type:o,project:l,dateStart:c,dateEnd:C}=r.data;try{let D={limit:s,...n!==void 0?{query:n}:{},...o!==void 0?{type:o}:{},...l!==void 0?{project:l}:{},...c!==void 0?{dateStart:c}:{},...C!==void 0?{dateEnd:C}:{}},T=await p.search(D);return et({results:T.results,total:T.total,mode:T.mode})}catch(D){let T=D instanceof Error?D.message:"Search failed";return y1(T,500)}}),a.get("/api/search/semantic",async t=>{let{searchManager:p}=e;if(p===void 0)return y1("Service unavailable",503);let i=new URL(t.url).searchParams.get("query")??"",r=ad.safeParse({query:i});if(!r.success)return y1(r.error.issues[0]?.message??"Validation error",400);try{let n=await p.searchSemantic(r.data.query);return et({results:n})}catch(n){let s=n instanceof Error?n.message:"Semantic search failed";return y1(s,500)}})}function fa(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function ie(a,e){return fa({error:a},e)}function rd(a,e){a.post("/api/observations/batch",async t=>{let{searchManager:p}=e;if(p===void 0)return ie("Service unavailable",503);let d;try{d=await t.json()}catch{return ie("Invalid JSON body",400)}let i=Ka.safeParse(d);if(!i.success)return ie(i.error.issues[0]?.message??"Validation error",400);try{let r=p.batchFetch(i.data.ids);return fa({observations:r})}catch(r){let n=r instanceof Error?r.message:"Batch fetch failed";return ie(n,500)}}),a.delete("/api/observation/:id",(t,p)=>{let{observationWriter:d}=e;if(d===void 0)return ie("Service unavailable",503);let i=parseInt(p.id??"",10);if(isNaN(i))return ie("Invalid observation id",400);try{return d.delete(i),fa({deleted:!0})}catch(r){let n=r instanceof Error?r.message:"Delete failed";return ie(n,500)}}),a.post("/api/observations/delete",async t=>{let{observationWriter:p}=e;if(p===void 0)return ie("Service unavailable",503);let d;try{d=await t.json()}catch{return ie("Invalid JSON body",400)}let i=Ka.safeParse(d);if(!i.success)return ie(i.error.issues[0]?.message??"Validation error",400);try{let r=p.bulkDelete(i.data.ids);return fa({deleted:r})}catch(r){let n=r instanceof Error?r.message:"Bulk delete failed";return ie(n,500)}})}function nd(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function at(a,e){return nd({error:a},e)}function pn(a){let e={},t=a.searchParams.get("anchor");t!==null&&(e.anchor=t);let p=a.searchParams.get("depth_before");if(p!==null){let i=Number(p);e.depth_before=isNaN(i)?p:i}let d=a.searchParams.get("depth_after");if(d!==null){let i=Number(d);e.depth_after=isNaN(i)?d:i}return e}function sd(a,e){a.get("/api/timeline",t=>{let{searchManager:p}=e;if(p===void 0)return at("Service unavailable",503);let d=new URL(t.url),i=pn(d),r=td.safeParse(i);if(!r.success)return at(r.error.issues[0]?.message??"Validation error",400);let{anchor:n,depth_before:s,depth_after:o}=r.data;try{let l=p.timeline({anchor:n,depthBefore:s,depthAfter:o});return nd({entries:l.entries})}catch(l){let c=l instanceof Error?l.message:"Timeline query failed";return at(c,500)}})}function tt(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"Content-Type":"application/json"}})}function od(a){return a==="core-ready"||a==="ready"}async function dn(a){if(od(a.initState))return!0;let e=Date.now()+5e3;for(;Date.now()<e;)if(await new Promise(t=>setTimeout(t,100)),od(a.initState))return!0;return!1}function A1(a){if(a===null||a==="")return[];try{let e=JSON.parse(a);return Array.isArray(e)?e:[]}catch{return[]}}function ld(a){return{id:a.id,memorySessionId:a.memory_session_id,project:a.project,text:a.text,type:a.type,title:a.title,subtitle:a.subtitle,facts:A1(a.facts),narrative:a.narrative,concepts:A1(a.concepts),filesRead:A1(a.files_read),filesModified:A1(a.files_modified),promptNumber:a.prompt_number,discoveryTokens:a.discovery_tokens,tags:A1(a.tags),createdAt:a.created_at,createdAtEpoch:a.created_at_epoch}}function md(a){return{id:a.id,memorySessionId:a.memory_session_id,project:a.project,request:a.request,investigated:a.investigated,learned:a.learned,completed:a.completed,nextSteps:a.next_steps,notes:a.notes,createdAt:a.created_at,createdAtEpoch:a.created_at_epoch}}function cd(a){let t=new URL(a.url).searchParams.get("project");if(t!==null)return t;let p=a.headers.get("x-project");if(p!==null)return p}function ud(a,e,t){if(a.db===void 0)return[];let p=Math.floor(Date.now()/1e3)-t*3600;return e!==void 0?a.db.query("SELECT * FROM observations WHERE created_at_epoch >= ? AND project = ? ORDER BY created_at_epoch DESC").all(p,e).map(ld):a.db.query("SELECT * FROM observations WHERE created_at_epoch >= ? ORDER BY created_at_epoch DESC").all(p).map(ld)}function hd(a,e){return a.db===void 0?[]:e!==void 0?a.db.query("SELECT * FROM session_summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT 5").all(e).map(md):a.db.query("SELECT * FROM session_summaries ORDER BY created_at_epoch DESC LIMIT 5").all().map(md)}function rn(a,e){let t=e.length>0?e[0]:null,p=t?.completed??t?.request??"None",d=a.filter(s=>s.type==="decision").flatMap(s=>s.facts).filter(s=>s.length>0).slice(0,5),i=a.flatMap(s=>[...s.filesModified,...s.filesRead]).filter((s,o,l)=>s.length>0&&l.indexOf(s)===o).slice(0,10),r=d.length>0?d.join(", "):"None",n=i.length>0?i.join(", "):"None";return["[Memory Context]",`Recent observations: ${a.length}`,`Last session: ${p}`,`Key decisions: ${r}`,`Recent files: ${n}`].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-metis",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Persistent memory system for OpenCode sessions",
6
6
  "license": "MIT",