@vibecontrols/agent 2026.902.1 → 2026.1125.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/dist/agent-config-v9d7gcz0.js +2 -0
  2. package/dist/agent-ready-tracker-mewxehg9.js +2 -0
  3. package/dist/app-a95wetk5.js +2 -0
  4. package/dist/autostart.cmd-ahet7b1t.js +2 -0
  5. package/dist/bootstrap-workspace-3pb8qjsh.js +2 -0
  6. package/dist/bootstrap.service-9m7m1ksa.js +2 -0
  7. package/dist/bridge-client-xvqy3n15.js +2 -0
  8. package/dist/cli.js +2 -2
  9. package/dist/daemon-profile-sg8fp50z.js +2 -0
  10. package/dist/finalize-retry-handle-registry-z9mbbjmj.js +2 -0
  11. package/dist/finalize-retry-worker-az74f2qv.js +2 -0
  12. package/dist/gateway-client-ermpz52n.js +2 -0
  13. package/dist/getMachineId-bsd-4w1wmcjv.js +2 -0
  14. package/dist/getMachineId-darwin-kejwz8w5.js +3 -0
  15. package/dist/getMachineId-linux-mpm53wat.js +2 -0
  16. package/dist/getMachineId-unsupported-54seyw5v.js +2 -0
  17. package/dist/getMachineId-win-cva7ghz9.js +2 -0
  18. package/dist/highlights-3nz7pbkh.js +2 -0
  19. package/dist/highlights-6dgztt5d.js +2 -0
  20. package/dist/highlights-jq0g1547.js +2 -0
  21. package/dist/highlights-yc7cwzcr.js +2 -0
  22. package/dist/highlights-z2sw1kpq.js +2 -0
  23. package/dist/index-01fp85ft.js +171 -0
  24. package/dist/index-0gmhd3hs.js +4 -0
  25. package/dist/index-0qjbnyg4.js +21 -0
  26. package/dist/index-2r6cmxxz.js +9 -0
  27. package/dist/index-2vcxt38h.js +3 -0
  28. package/dist/index-4527yp1c.js +178 -0
  29. package/dist/index-4z1y39jt.js +3 -0
  30. package/dist/index-5021rk8n.js +3 -0
  31. package/dist/index-652f9scs.js +4 -0
  32. package/dist/index-75hk5q9s.js +13 -0
  33. package/dist/index-76m37yd8.js +22 -0
  34. package/dist/index-7f2k4g6q.js +8 -0
  35. package/dist/index-7gk1x74m.js +15 -0
  36. package/dist/index-7wben1jx.js +3 -0
  37. package/dist/index-8rbhm4g8.js +7 -0
  38. package/dist/index-9xrhb68w.js +14 -0
  39. package/dist/index-a0vx2zyx.js +3 -0
  40. package/dist/index-akk3rxnn.js +4 -0
  41. package/dist/index-b3v08awy.js +3 -0
  42. package/dist/index-byerrz46.js +3 -0
  43. package/dist/index-c4whjk5r.js +3 -0
  44. package/dist/index-cy97asyh.js +133 -0
  45. package/dist/index-d59kp6zr.js +3 -0
  46. package/dist/index-ec08v08h.js +116 -0
  47. package/dist/index-g08z6z5v.js +5 -0
  48. package/dist/index-gaztfvyz.js +158 -0
  49. package/dist/index-gnb8xw13.js +83 -0
  50. package/dist/index-haww9jpq.js +27 -0
  51. package/dist/index-hsrt2v87.js +2 -0
  52. package/dist/index-jmx5awkj.js +3 -0
  53. package/dist/index-jnxjjx2y.js +3 -0
  54. package/dist/index-kwhx023z.js +11 -0
  55. package/dist/index-mmx2kp76.js +16 -0
  56. package/dist/index-ne8q0a64.js +26 -0
  57. package/dist/index-nzfqdhsx.js +11 -0
  58. package/dist/index-qe3xpt41.js +3 -0
  59. package/dist/index-qfxwk38p.js +82 -0
  60. package/dist/index-ss5gez2p.js +2 -0
  61. package/dist/index-t5cfkz1e.js +4 -0
  62. package/dist/index-t6p4szqx.js +5 -0
  63. package/dist/index-tahaxp6n.js +3 -0
  64. package/dist/index-v16qz1fa.js +3 -0
  65. package/dist/index-v35k2y31.js +17 -0
  66. package/dist/index-vtsd74g0.js +9 -0
  67. package/dist/index-w0m3jm0s.js +408 -0
  68. package/dist/index-w4jqdhc2.js +5 -0
  69. package/dist/index-xtd0j8ve.js +3 -0
  70. package/dist/index-ywnfz6nm.js +3 -0
  71. package/dist/index.js +3 -3
  72. package/dist/injections-h25c1fmk.js +2 -0
  73. package/dist/interactive-vbz68zh5.js +2 -0
  74. package/dist/key.cmd-f6rjvjy8.js +2 -0
  75. package/dist/log-shipper-0erbwn0q.js +2 -0
  76. package/dist/path-utils-r4df8d3w.js +2 -0
  77. package/dist/plugin-system-zj50tg4k.js +2 -0
  78. package/dist/prereqs-runner-gca0bytz.js +2 -0
  79. package/dist/profile-mount-s4mc1x18.js +2 -0
  80. package/dist/prune-stale-shims-4nqtv0xt.js +2 -0
  81. package/dist/register-core-vng5hdga.js +2 -0
  82. package/dist/secondary-profile-attach-pyqqf4ny.js +2 -0
  83. package/dist/subprocess-4gg77skg.js +2 -0
  84. package/dist/telemetry-nmtywcba.js +2 -0
  85. package/dist/tree-sitter-javascript-rfadfcwb.js +2 -0
  86. package/dist/tree-sitter-markdown-gkyb2qez.js +2 -0
  87. package/dist/tree-sitter-markdown_inline-xzttqkvb.js +2 -0
  88. package/dist/tree-sitter-typescript-4z897028.js +2 -0
  89. package/dist/tree-sitter-zig-y6n7djp6.js +2 -0
  90. package/dist/tunnel-bootstrap-zwyzxrkt.js +2 -0
  91. package/package.json +10 -9
  92. package/dist/agent-config-5b0avmy6.js +0 -2
  93. package/dist/agent-ready-tracker-ez6r9djg.js +0 -2
  94. package/dist/app-mhms2gs0.js +0 -2
  95. package/dist/autostart.cmd-4zb9xhj0.js +0 -2
  96. package/dist/bootstrap-workspace-t5fyq07m.js +0 -2
  97. package/dist/bootstrap.service-nxhkrsf1.js +0 -2
  98. package/dist/bridge-client-bgkr7bcn.js +0 -2
  99. package/dist/daemon-profile-j2wt35x8.js +0 -2
  100. package/dist/esm-n9r8p5n2.js +0 -2
  101. package/dist/finalize-retry-handle-registry-fvm4gm8s.js +0 -2
  102. package/dist/finalize-retry-worker-wb8wj1yw.js +0 -2
  103. package/dist/gateway-client-6dqagbg4.js +0 -2
  104. package/dist/getMachineId-bsd-fgatzdd7.js +0 -2
  105. package/dist/getMachineId-darwin-gt8j2jw2.js +0 -3
  106. package/dist/getMachineId-linux-bcz4rr1x.js +0 -2
  107. package/dist/getMachineId-unsupported-079qwwb4.js +0 -2
  108. package/dist/getMachineId-win-2hk4e8bg.js +0 -2
  109. package/dist/highlights-0gfz787m.js +0 -2
  110. package/dist/highlights-86sbx76f.js +0 -2
  111. package/dist/highlights-n55f5jnk.js +0 -2
  112. package/dist/highlights-tbmszdr7.js +0 -2
  113. package/dist/highlights-wm2cs773.js +0 -2
  114. package/dist/index-06es0fmw.js +0 -10
  115. package/dist/index-0d4wfjbt.js +0 -171
  116. package/dist/index-29fmptfn.js +0 -13
  117. package/dist/index-2q2jadag.js +0 -11
  118. package/dist/index-2sn36kaj.js +0 -7
  119. package/dist/index-3p4n7nwg.js +0 -83
  120. package/dist/index-3tf12pw3.js +0 -3
  121. package/dist/index-54mmh1eb.js +0 -4
  122. package/dist/index-6jzsthh9.js +0 -3
  123. package/dist/index-7wejfjj9.js +0 -5
  124. package/dist/index-8q19ryt2.js +0 -28
  125. package/dist/index-8xh8m2z7.js +0 -8
  126. package/dist/index-98gr644s.js +0 -116
  127. package/dist/index-a8n6s2ae.js +0 -2
  128. package/dist/index-b16y8wyz.js +0 -15
  129. package/dist/index-bv1z3fxw.js +0 -3
  130. package/dist/index-cs78wq6y.js +0 -3
  131. package/dist/index-df19rrbe.js +0 -5
  132. package/dist/index-dx9hjdp4.js +0 -178
  133. package/dist/index-ea42kfvk.js +0 -5
  134. package/dist/index-ekr40gvh.js +0 -3
  135. package/dist/index-evnbrmdf.js +0 -4
  136. package/dist/index-f2asckf0.js +0 -26
  137. package/dist/index-ggxs7nwz.js +0 -3
  138. package/dist/index-gz5t0vvc.js +0 -4
  139. package/dist/index-hey6w5m0.js +0 -3
  140. package/dist/index-hp8jrj6j.js +0 -3
  141. package/dist/index-hrfkzecw.js +0 -3
  142. package/dist/index-hwpmdq5z.js +0 -4
  143. package/dist/index-hz5cy6vz.js +0 -11
  144. package/dist/index-jbxh0ffn.js +0 -407
  145. package/dist/index-js2r0men.js +0 -9
  146. package/dist/index-k3jkzj3k.js +0 -9
  147. package/dist/index-kteawn2b.js +0 -3
  148. package/dist/index-mbhq916m.js +0 -3
  149. package/dist/index-mxc61yr1.js +0 -3
  150. package/dist/index-qdbxvcwr.js +0 -17
  151. package/dist/index-qqq9qyy6.js +0 -21
  152. package/dist/index-rmh8pff5.js +0 -3
  153. package/dist/index-sspydg85.js +0 -15
  154. package/dist/index-tk81f249.js +0 -3
  155. package/dist/index-vjdg5qb2.js +0 -2
  156. package/dist/index-vkrf8kzp.js +0 -158
  157. package/dist/index-vnxqna70.js +0 -16
  158. package/dist/index-w7gctzhm.js +0 -83
  159. package/dist/index-wj5hx7gq.js +0 -4
  160. package/dist/index-x4eaagvr.js +0 -3
  161. package/dist/index-xjr60th0.js +0 -3
  162. package/dist/index-xtbppqnv.js +0 -3
  163. package/dist/index-y42xsgr6.js +0 -133
  164. package/dist/index-zr9rmjyp.js +0 -3
  165. package/dist/injections-2g0zh0bq.js +0 -2
  166. package/dist/interactive-08vyaapn.js +0 -2
  167. package/dist/key.cmd-642xcxb4.js +0 -2
  168. package/dist/log-shipper-9xfnjwr6.js +0 -2
  169. package/dist/path-utils-g449hqvm.js +0 -2
  170. package/dist/plugin-system-gpzcch00.js +0 -2
  171. package/dist/prereqs-runner-re9f51fp.js +0 -2
  172. package/dist/profile-mount-txvgkaz8.js +0 -2
  173. package/dist/prune-stale-shims-vs6a07tb.js +0 -2
  174. package/dist/register-core-ma4kse87.js +0 -2
  175. package/dist/secondary-profile-attach-m9x9e7py.js +0 -2
  176. package/dist/subprocess-zcgpccp1.js +0 -2
  177. package/dist/telemetry-k6em3vy2.js +0 -2
  178. package/dist/tree-sitter-javascript-qh90w7td.js +0 -2
  179. package/dist/tree-sitter-markdown-favzteb6.js +0 -2
  180. package/dist/tree-sitter-markdown_inline-x2726t9j.js +0 -2
  181. package/dist/tree-sitter-typescript-m7ep8z1h.js +0 -2
  182. package/dist/tree-sitter-zig-3vsxg5wh.js +0 -2
  183. package/dist/tunnel-bootstrap-y8dczezc.js +0 -2
@@ -0,0 +1,178 @@
1
+ // @bun
2
+ import{z,ii,Vt,It,T,O,C,N,e,it}from"./index-0qjbnyg4.js";import{M,X}from"./index-kwhx023z.js";import{_e,W}from"./index-g08z6z5v.js";import{K}from"./index-mmx2kp76.js";import{pt}from"./index-qfxwk38p.js";import{Te,Ee,ke}from"./index-gnb8xw13.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Wa,readFileSync as Ja}from"fs";import{dirname as Ei,join as Ya}from"path";import{fileURLToPath as Qa}from"url";import{closeSync as Za,existsSync as eo,mkdirSync as to,openSync as io,readFileSync as ro,unlinkSync as Nr,writeFileSync as so}from"fs";import{join as no}from"path";import ao from"crypto";import rt from"path";import G from"fs";import xi from"zlib";import oo from"http";import{closeSync as lo,existsSync as co,mkdirSync as uo,openSync as ho,readFileSync as fo,unlinkSync as $r,writeFileSync as _o}from"fs";import{join as po}from"path";import go from"crypto";import st from"path";import H from"fs";import Si from"zlib";import mo from"http";import{closeSync as yo,existsSync as wo,mkdirSync as Ao,openSync as vo,readFileSync as Eo,unlinkSync as kr,writeFileSync as xo}from"fs";import{join as So}from"path";import Io from"crypto";import nt from"path";import J from"fs";import Ii from"zlib";import bo from"http";import{closeSync as To,existsSync as Oo,mkdirSync as Ro,openSync as Co,readFileSync as No,unlinkSync as Dr,writeFileSync as $o}from"fs";import{join as ko}from"path";import Do from"crypto";import at from"path";import Y from"fs";import bi from"zlib";import Lo from"http";function Po(){let t=Date.now().toString(16),i;try{i=ao.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Lr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Pr=new Set(["__proto__","constructor","prototype"]);function ni(t,i){if(!i.includes(".")){if(Pr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Pr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Re extends Je{}class Ve extends Je{}class Se extends Je{}class ut extends Je{}function Li(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Li(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Li(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ni(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Li(n,s))return!1}else if(n!==s)return!1}return!0}function Mo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Pi=new Set(["string","number","boolean","object","array","date","any"]);function zi(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ds(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Pi.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Pi.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function Mr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=zi(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function jr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(zi(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function jo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=zi(s);i[r]=Pi.has(n)?n:"any"}return i}function qo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Uo(t){return new Date(Date.now()+qo(t))}function Fo(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function qr(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Ko(t){return t.length}function zo(t,i){let r=0;for(let s of t){let n=ni(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Bo(t,i){let r=0,s=0;for(let n of t){let a=ni(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Xo(t,i){let r=Object.create(null);for(let s of t){let n=String(ni(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ls{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Vo(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ps=new Set(["__proto__","constructor","prototype"]);function Ms(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ps.has(r))continue;i[r]=Ms(t[r])}return i}class js{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ls(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ps.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=Ms(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=Mr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=jr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Vo(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Ko(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Mo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=qr(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=qr(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
3
+ `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
4
+ `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Se("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=Mr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return jr(t,this._schema);default:throw new D("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ie(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ie(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ie(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ie(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ie(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ie(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Po)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Uo(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Bi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class qs extends Bi{constructor({dir:t,format:i="gz"}){super();this.dir=rt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return rt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await G.promises.readFile(i);if(this.format==="gz")r=xi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=rt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=xi.deflateSync(i);await G.promises.writeFile(s,n)}else await G.promises.writeFile(s,i,"utf8");await G.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=rt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=xi.deflateSync(s);await G.promises.writeFile(a,o)}else await G.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await G.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await G.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await G.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await G.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return rt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(rt.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(rt.resolve(t),"utf8")}}class Us{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new D("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Ur={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Fr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ti(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ei{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ti(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Fr(s):Ur}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ti(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Fr(a):Ur}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new D("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new D("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ti(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var jt="_flush",qt="migrations";class Fs{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ve("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ve("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[jt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[jt])i[jt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(qt);if(!r)return;let s=r[jt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(qt);if(!r)r={_id:qt},i.data.push(r),i.index.set(qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Go=0;class Ks{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Go,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Re("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Re("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Re("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class zs{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Ds(i);let _=f.uniqueFields;if(r.length||_.length)h=new ei(r,_)}else if(r.length)h=new ei(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return jo(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Xi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var we=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bs extends Xi{constructor({apiKey:t=we("OPENAI_API_KEY"),model:i=we("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=we("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=we("OPENAI_EMBED_DIMENSIONS")!=null?Number(we("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=we("OPENAI_ORGANIZATION")??void 0,timeout:a=we("OPENAI_EMBED_TIMEOUT")!=null?Number(we("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(we("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(we("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var mt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xs extends Xi{constructor({model:t=mt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=mt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=mt("OLLAMA_EMBED_TIMEOUT")!=null?Number(mt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(mt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(mt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ai{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Vi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
5
+
6
+ Rules:
7
+ - Return ONLY a valid JSON object, nothing else
8
+ - Use standard query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $regex
9
+ - For simple equality, use plain key-value pairs: {"field": "value"}
10
+ - For numeric comparisons use operators: {"age": {"$gt": 18}}
11
+ - For text search use $regex: {"name": {"$regex": "pattern"}}
12
+ - Return {} to match all documents
13
+ - No explanations, no markdown, no code fences`,Gi="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",U=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vs extends ai{constructor({apiKey:t=U("OPENAI_API_KEY"),model:i=U("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=U("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=U("OPENAI_MAX_TOKENS")!=null?Number(U("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(U("OPENAI_TEMPERATURE")??0.3),topP:a=U("OPENAI_TOP_P")!=null?Number(U("OPENAI_TOP_P")):void 0,organization:o=U("OPENAI_ORGANIZATION")??void 0,timeout:c=U("OPENAI_TIMEOUT")!=null?Number(U("OPENAI_TIMEOUT")):void 0,retries:l=Number(U("OPENAI_RETRIES")??0),retryDelay:d=Number(U("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=U("OPENAI_SEED")!=null?Number(U("OPENAI_SEED")):void 0,generatePrompt:_=Vi,summarizePrompt:p=Gi}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
14
+ Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ae=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Gs extends ai{constructor({apiKey:t=ae("ANTHROPIC_API_KEY"),model:i=ae("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=ae("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(ae("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(ae("ANTHROPIC_TEMPERATURE")??0.3),topP:o=ae("ANTHROPIC_TOP_P")!=null?Number(ae("ANTHROPIC_TOP_P")):void 0,topK:c=ae("ANTHROPIC_TOP_K")!=null?Number(ae("ANTHROPIC_TOP_K")):void 0,timeout:l=ae("ANTHROPIC_TIMEOUT")!=null?Number(ae("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(ae("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(ae("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=Vi,summarizePrompt:p=Gi}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
15
+ Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var pe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Hs extends ai{constructor({model:t=pe("OLLAMA_MODEL")??"llama3.2",host:i=pe("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(pe("OLLAMA_TEMPERATURE")??0.3),topP:s=pe("OLLAMA_TOP_P")!=null?Number(pe("OLLAMA_TOP_P")):void 0,topK:n=pe("OLLAMA_TOP_K")!=null?Number(pe("OLLAMA_TOP_K")):void 0,timeout:a=pe("OLLAMA_TIMEOUT")!=null?Number(pe("OLLAMA_TIMEOUT")):void 0,retries:o=Number(pe("OLLAMA_RETRIES")??0),retryDelay:c=Number(pe("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=Vi,summarizePrompt:f=Gi}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
16
+ Schema: ${JSON.stringify(t)}
17
+ Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
18
+
19
+ ${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function Ho({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new Bs({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new Xs({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Se("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function Wo({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new Vs({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new Gs({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new Hs({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Oi="AES-GCM",$t=12,Le=32,Jo=new TextEncoder,Yo=new TextDecoder;class Ws extends Bi{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Qo(i):Uint8Array.from(i),this._rawKey.length!==Le)throw new Se("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Le} bytes (${Le*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Oi},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array($t)),s=Jo.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Oi,iv:r,tagLength:128},i,s),a=new Uint8Array($t+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),$t),Zo(a)}async _decrypt(t){let i=await this._getKey(),r=el(t),s=r.slice(0,$t),n=r.slice($t),a=await globalThis.crypto.subtle.decrypt({name:Oi,iv:s,tagLength:128},i,n);return Yo.decode(a)}}function Qo(t){if(t.length!==Le*2)throw new Se("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Le*2} characters (${Le} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Se("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Le);for(let r=0;r<Le;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function Zo(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function el(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var tl=4;class Js{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
20
+ `)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
21
+ `),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/tl)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Ys{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function il(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Qs{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return il(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function rl(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&sl(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function sl(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function nl(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Zs{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class en{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class tn{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class rn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ot(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var Kr=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function al(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ot(i.collection))??null;case"skalex_find":{let s=r.useCollection(ot(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ot(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ot(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ot(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ot(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ot(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var Hi="2.0",Wi=-32700,ol=-32600,zr=-32601,ll=-32602,cl=-32603;function yt(t,i){return{jsonrpc:Hi,id:t,result:i}}function Ke(t,i,r,s){return{jsonrpc:Hi,id:t,error:{code:i,message:r}}}function dl(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==Hi)return{parseError:Ke(null,ol,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Ke(null,Wi,"Parse error")}}}function ul(t){return{content:[{type:"text",text:t}]}}function Br(t){return{content:[{type:"text",text:t}],isError:!0}}class sn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
22
+
23
+ `;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=oo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
24
+ data: /message
25
+
26
+ `),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,Wi,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class nn{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
27
+ `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
28
+ `))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,Wi,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var hl={name:"skalex",version:"4.0.0-alpha"},fl="2024-11-05";class an{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new sn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new nn;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?dl(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(yt(s,{protocolVersion:fl,capabilities:{tools:{}},serverInfo:hl}));break;case"tools/list":this._send(yt(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(yt(s,{}));break;default:this._send(Ke(s,zr,`Method not found: ${n}`))}}catch(o){this._send(Ke(s,cl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Ke(t,ll,"tools/call requires params.name"));return}let n=Kr.find((o)=>o.name===r);if(!n){this._send(Ke(t,zr,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(yt(t,Br(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await al(r,s,this._db);this._send(yt(t,ul(JSON.stringify(o,null,2))))}catch(o){this._send(yt(t,Br(o.message||String(o))))}}_visibleTools(){return Kr.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Ut="migrations",Xr=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Vr=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class de{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!de._errorsAttached)de.SkalexError=Je,de.ValidationError=D,de.UniqueConstraintError=De,de.TransactionError=Re,de.PersistenceError=Ve,de.AdapterError=Se,de.QueryError=ut,de._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new qs({dir:t,format:i});if(a)E=new Ws(E,a.key);if(this.fs=E,this._registry=new zs(js),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new Us,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Xr,this._deserializer=m??Vr,this._autoSave=w??!1,this._txManager=new Ks,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Lr,this._embeddingAdapter=h??(n?Ho(n):null),this._aiAdapter=f??(n?Wo(n):null),this._persistence=new Fs({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Ys(this),this._queryCache=new Qs(c||{}),this._eventBus=new Zs,this._queryLog=o?new en(o):null,this._sessionStats=new tn,this._plugins=new rn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:Ds,buildIndex:this._registry.buildIndex,IndexEngine:ei});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Se("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new D("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new de({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Lr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Xr?this._serializer:void 0,deserializer:this._deserializer!==Vr?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ve("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Se("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Se("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=nl(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(rl(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Js(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new an(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Ut)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Ut);if(r)Object.assign(r,t);else{let s={_id:Ut,...t};i.data.push(s),i.index.set(Ut,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Fo(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function _l(){let t=Date.now().toString(16),i;try{i=go.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Gr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Hr=new Set(["__proto__","constructor","prototype"]);function oi(t,i){if(!i.includes(".")){if(Hr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Hr.has(s))return;if(r==null)return;r=r[s]}return r}class Ye extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class L extends Ye{}class Pe extends Ye{}class Ce extends Ye{}class Ge extends Ye{}class Ie extends Ye{}class ht extends Ye{}function Mi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Mi(t[s],i[s]))return!1}return!0}return!1}function re(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>re(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>re(t,s)))return!1}if("$not"in i){if(re(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=oi(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Mi(n,s))return!1}else if(n!==s)return!1}return!0}function pl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ji=new Set(["string","number","boolean","object","array","date","any"]);function Ji(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function on(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ji.has(n))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ji.has(o))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new L("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function Wr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ji(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function Jr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ji(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function gl(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ji(s);i[r]=ji.has(n)?n:"any"}return i}function ml(t){if(typeof t==="number"){if(t<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new L("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new L("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function yl(t){return new Date(Date.now()+ml(t))}function wl(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Yr(t,i){if(t.length!==i.length)throw new ht("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Z(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Al(t){return t.length}function vl(t,i){let r=0;for(let s of t){let n=oi(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function El(t,i){let r=0,s=0;for(let n of t){let a=oi(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function xl(t,i){let r=Object.create(null);for(let s of t){let n=String(oi(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class ln{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Z(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Z(m)});return{docs:p,prevDocs:g}}}function Sl(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var cn=new Set(["__proto__","constructor","prototype"]);function dn(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(cn.has(r))continue;i[r]=dn(t[r])}return i}class un{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new ln(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Z({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Z(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Z)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Pe("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Z(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Z)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(cn.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=dn(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=Wr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new L("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=Jr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ge("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Sl(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ht("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Z(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||re(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!re(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Al(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),vl(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),El(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),xl(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=pl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!re(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Yr(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Z(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Yr(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Z(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Z(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Z(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Z)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Z)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(re(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>re(u,t));if(a.length===0)throw new ht("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
29
+ `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
30
+ `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Ie("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=Wr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return Jr(t,this._schema);default:throw new L("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return re(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(re(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(re(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return re(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(re(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(re(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??_l)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=yl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Yi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class hn extends Yi{constructor({dir:t,format:i="gz"}){super();this.dir=st.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!H.existsSync(t))H.mkdirSync(t,{recursive:!0})}_filePath(t){return st.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await H.promises.readFile(i);if(this.format==="gz")r=Si.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=st.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Si.deflateSync(i);await H.promises.writeFile(s,n)}else await H.promises.writeFile(s,i,"utf8");await H.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=st.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Si.deflateSync(s);await H.promises.writeFile(a,o)}else await H.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await H.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await H.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await H.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await H.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return st.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(st.dirname(t)),await H.promises.writeFile(t,i,"utf8")}async readRaw(t){return H.promises.readFile(st.resolve(t),"utf8")}}class fn{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new L("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Qr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Zr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ri(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ti{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ri(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Zr(s):Qr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ri(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Zr(a):Qr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new L("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new L("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ri(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Ft="_flush",Kt="migrations";class _n{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ge("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ge("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Ft]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Ft])i[Ft].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Kt);if(!r)return;let s=r[Ft];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Kt);if(!r)r={_id:Kt},i.data.push(r),i.index.set(Kt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Il=0;class pn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Il,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ce("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ce("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ce("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class gn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=on(i);let _=f.uniqueFields;if(r.length||_.length)h=new ti(r,_)}else if(r.length)h=new ti(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return gl(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Qi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var Ae=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class mn extends Qi{constructor({apiKey:t=Ae("OPENAI_API_KEY"),model:i=Ae("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=Ae("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=Ae("OPENAI_EMBED_DIMENSIONS")!=null?Number(Ae("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=Ae("OPENAI_ORGANIZATION")??void 0,timeout:a=Ae("OPENAI_EMBED_TIMEOUT")!=null?Number(Ae("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(Ae("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(Ae("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var wt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class yn extends Qi{constructor({model:t=wt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=wt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=wt("OLLAMA_EMBED_TIMEOUT")!=null?Number(wt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(wt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(wt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class di{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Zi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
31
+
32
+ Rules:
33
+ - Return ONLY a valid JSON object, nothing else
34
+ - Use standard query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $regex
35
+ - For simple equality, use plain key-value pairs: {"field": "value"}
36
+ - For numeric comparisons use operators: {"age": {"$gt": 18}}
37
+ - For text search use $regex: {"name": {"$regex": "pattern"}}
38
+ - Return {} to match all documents
39
+ - No explanations, no markdown, no code fences`,er="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",F=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class wn extends di{constructor({apiKey:t=F("OPENAI_API_KEY"),model:i=F("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=F("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=F("OPENAI_MAX_TOKENS")!=null?Number(F("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(F("OPENAI_TEMPERATURE")??0.3),topP:a=F("OPENAI_TOP_P")!=null?Number(F("OPENAI_TOP_P")):void 0,organization:o=F("OPENAI_ORGANIZATION")??void 0,timeout:c=F("OPENAI_TIMEOUT")!=null?Number(F("OPENAI_TIMEOUT")):void 0,retries:l=Number(F("OPENAI_RETRIES")??0),retryDelay:d=Number(F("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=F("OPENAI_SEED")!=null?Number(F("OPENAI_SEED")):void 0,generatePrompt:_=Zi,summarizePrompt:p=er}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
40
+ Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var oe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class An extends di{constructor({apiKey:t=oe("ANTHROPIC_API_KEY"),model:i=oe("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=oe("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(oe("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(oe("ANTHROPIC_TEMPERATURE")??0.3),topP:o=oe("ANTHROPIC_TOP_P")!=null?Number(oe("ANTHROPIC_TOP_P")):void 0,topK:c=oe("ANTHROPIC_TOP_K")!=null?Number(oe("ANTHROPIC_TOP_K")):void 0,timeout:l=oe("ANTHROPIC_TIMEOUT")!=null?Number(oe("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(oe("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(oe("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=Zi,summarizePrompt:p=er}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
41
+ Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ge=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class vn extends di{constructor({model:t=ge("OLLAMA_MODEL")??"llama3.2",host:i=ge("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(ge("OLLAMA_TEMPERATURE")??0.3),topP:s=ge("OLLAMA_TOP_P")!=null?Number(ge("OLLAMA_TOP_P")):void 0,topK:n=ge("OLLAMA_TOP_K")!=null?Number(ge("OLLAMA_TOP_K")):void 0,timeout:a=ge("OLLAMA_TIMEOUT")!=null?Number(ge("OLLAMA_TIMEOUT")):void 0,retries:o=Number(ge("OLLAMA_RETRIES")??0),retryDelay:c=Number(ge("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=Zi,summarizePrompt:f=er}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
42
+ Schema: ${JSON.stringify(t)}
43
+ Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
44
+
45
+ ${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function bl({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new mn({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new yn({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Ie("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function Tl({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new wn({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new An({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new vn({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Ci="AES-GCM",kt=12,Me=32,Ol=new TextEncoder,Rl=new TextDecoder;class En extends Yi{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Cl(i):Uint8Array.from(i),this._rawKey.length!==Me)throw new Ie("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Me} bytes (${Me*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Ci},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(kt)),s=Ol.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Ci,iv:r,tagLength:128},i,s),a=new Uint8Array(kt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),kt),Nl(a)}async _decrypt(t){let i=await this._getKey(),r=$l(t),s=r.slice(0,kt),n=r.slice(kt),a=await globalThis.crypto.subtle.decrypt({name:Ci,iv:s,tagLength:128},i,n);return Rl.decode(a)}}function Cl(t){if(t.length!==Me*2)throw new Ie("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Me*2} characters (${Me} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Ie("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Me);for(let r=0;r<Me;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function Nl(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function $l(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var kl=4;class xn{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
46
+ `)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
47
+ `),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/kl)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Sn{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Dl(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class In{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Dl(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Ll(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Pl(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Pl(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function Ml(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class bn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Tn{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class On{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Rn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function lt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var es=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function jl(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(lt(i.collection))??null;case"skalex_find":{let s=r.useCollection(lt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(lt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(lt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(lt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(lt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(lt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var tr="2.0",ir=-32700,ql=-32600,ts=-32601,Ul=-32602,Fl=-32603;function At(t,i){return{jsonrpc:tr,id:t,result:i}}function ze(t,i,r,s){return{jsonrpc:tr,id:t,error:{code:i,message:r}}}function Kl(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==tr)return{parseError:ze(null,ql,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:ze(null,ir,"Parse error")}}}function zl(t){return{content:[{type:"text",text:t}]}}function is(t){return{content:[{type:"text",text:t}],isError:!0}}class Cn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
48
+
49
+ `;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=mo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
50
+ data: /message
51
+
52
+ `),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,ir,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class Nn{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
53
+ `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
54
+ `))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,ir,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var Bl={name:"skalex",version:"4.0.0-alpha"},Xl="2024-11-05";class $n{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Cn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new Nn;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Kl(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(At(s,{protocolVersion:Xl,capabilities:{tools:{}},serverInfo:Bl}));break;case"tools/list":this._send(At(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(At(s,{}));break;default:this._send(ze(s,ts,`Method not found: ${n}`))}}catch(o){this._send(ze(s,Fl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(ze(t,Ul,"tools/call requires params.name"));return}let n=es.find((o)=>o.name===r);if(!n){this._send(ze(t,ts,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(At(t,is(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await jl(r,s,this._db);this._send(At(t,zl(JSON.stringify(o,null,2))))}catch(o){this._send(At(t,is(o.message||String(o))))}}_visibleTools(){return es.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var zt="migrations",rs=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),ss=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class ue{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!ue._errorsAttached)ue.SkalexError=Ye,ue.ValidationError=L,ue.UniqueConstraintError=Pe,ue.TransactionError=Ce,ue.PersistenceError=Ge,ue.AdapterError=Ie,ue.QueryError=ht,ue._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new hn({dir:t,format:i});if(a)E=new En(E,a.key);if(this.fs=E,this._registry=new gn(un),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new fn,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??rs,this._deserializer=m??ss,this._autoSave=w??!1,this._txManager=new pn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Gr,this._embeddingAdapter=h??(n?bl(n):null),this._aiAdapter=f??(n?Tl(n):null),this._persistence=new _n({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Sn(this),this._queryCache=new In(c||{}),this._eventBus=new bn,this._queryLog=o?new Tn(o):null,this._sessionStats=new On,this._plugins=new Rn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:on,buildIndex:this._registry.buildIndex,IndexEngine:ti});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Ie("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new L("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new ue({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Gr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==rs?this._serializer:void 0,deserializer:this._deserializer!==ss?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ge("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Ie("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Ie("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=Ml(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Ll(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new xn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new $n(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(zt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(zt);if(r)Object.assign(r,t);else{let s={_id:zt,...t};i.data.push(s),i.index.set(zt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=wl(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Vl(){let t=Date.now().toString(16),i;try{i=Io.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function ns(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var as=new Set(["__proto__","constructor","prototype"]);function hi(t,i){if(!i.includes(".")){if(as.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(as.has(s))return;if(r==null)return;r=r[s]}return r}class Qe extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class P extends Qe{}class je extends Qe{}class Ne extends Qe{}class He extends Qe{}class be extends Qe{}class ft extends Qe{}function qi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!qi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!qi(t[s],i[s]))return!1}return!0}return!1}function se(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>se(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>se(t,s)))return!1}if("$not"in i){if(se(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=hi(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!qi(n,s))return!1}else if(n!==s)return!1}return!0}function Gl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Ui=new Set(["string","number","boolean","object","array","date","any"]);function rr(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function kn(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Ui.has(n))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Ui.has(o))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new P("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function os(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=rr(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function ls(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(rr(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function Hl(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=rr(s);i[r]=Ui.has(n)?n:"any"}return i}function Wl(t){if(typeof t==="number"){if(t<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new P("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new P("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Jl(t){return new Date(Date.now()+Wl(t))}function Yl(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function cs(t,i){if(t.length!==i.length)throw new ft("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function ee(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Ql(t){return t.length}function Zl(t,i){let r=0;for(let s of t){let n=hi(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function ec(t,i){let r=0,s=0;for(let n of t){let a=hi(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function tc(t,i){let r=Object.create(null);for(let s of t){let n=String(hi(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Dn{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:ee(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:ee(m)});return{docs:p,prevDocs:g}}}function ic(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ln=new Set(["__proto__","constructor","prototype"]);function Pn(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ln.has(r))continue;i[r]=Pn(t[r])}return i}class Mn{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Dn(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return ee({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return ee(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(ee)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new je("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return ee(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(ee)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ln.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=Pn(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=os(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new P("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=ls(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new He("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...ic(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ft("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return ee(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||se(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!se(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Ql(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Zl(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),ec(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),tc(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Gl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!se(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=cs(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>ee(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=cs(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>ee(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return ee(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return ee(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(ee)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(ee)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(se(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>se(u,t));if(a.length===0)throw new ft("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
55
+ `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
56
+ `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new be("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=os(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return ls(t,this._schema);default:throw new P("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return se(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(se(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(se(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return se(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(se(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(se(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Vl)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Jl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class sr{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class jn extends sr{constructor({dir:t,format:i="gz"}){super();this.dir=nt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!J.existsSync(t))J.mkdirSync(t,{recursive:!0})}_filePath(t){return nt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await J.promises.readFile(i);if(this.format==="gz")r=Ii.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=nt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ii.deflateSync(i);await J.promises.writeFile(s,n)}else await J.promises.writeFile(s,i,"utf8");await J.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=nt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ii.deflateSync(s);await J.promises.writeFile(a,o)}else await J.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await J.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await J.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await J.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await J.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return nt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(nt.dirname(t)),await J.promises.writeFile(t,i,"utf8")}async readRaw(t){return J.promises.readFile(nt.resolve(t),"utf8")}}class qn{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new P("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var ds={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function us(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ni(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ri{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ni(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?us(s):ds}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ni(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?us(a):ds}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new P("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new P("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ni(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Bt="_flush",Gt="migrations";class Un{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new He("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new He("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Bt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Bt])i[Bt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Gt);if(!r)return;let s=r[Bt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Gt);if(!r)r={_id:Gt},i.data.push(r),i.index.set(Gt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var rc=0;class Fn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++rc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ne("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ne("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ne("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class Kn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=kn(i);let _=f.uniqueFields;if(r.length||_.length)h=new ri(r,_)}else if(r.length)h=new ri(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return Hl(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class nr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var ve=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class zn extends nr{constructor({apiKey:t=ve("OPENAI_API_KEY"),model:i=ve("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=ve("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=ve("OPENAI_EMBED_DIMENSIONS")!=null?Number(ve("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=ve("OPENAI_ORGANIZATION")??void 0,timeout:a=ve("OPENAI_EMBED_TIMEOUT")!=null?Number(ve("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(ve("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(ve("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var vt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bn extends nr{constructor({model:t=vt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=vt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=vt("OLLAMA_EMBED_TIMEOUT")!=null?Number(vt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(vt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(vt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class fi{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var ar=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
57
+
58
+ Rules:
59
+ - Return ONLY a valid JSON object, nothing else
60
+ - Use standard query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $regex
61
+ - For simple equality, use plain key-value pairs: {"field": "value"}
62
+ - For numeric comparisons use operators: {"age": {"$gt": 18}}
63
+ - For text search use $regex: {"name": {"$regex": "pattern"}}
64
+ - Return {} to match all documents
65
+ - No explanations, no markdown, no code fences`,or="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",B=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xn extends fi{constructor({apiKey:t=B("OPENAI_API_KEY"),model:i=B("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=B("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=B("OPENAI_MAX_TOKENS")!=null?Number(B("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(B("OPENAI_TEMPERATURE")??0.3),topP:a=B("OPENAI_TOP_P")!=null?Number(B("OPENAI_TOP_P")):void 0,organization:o=B("OPENAI_ORGANIZATION")??void 0,timeout:c=B("OPENAI_TIMEOUT")!=null?Number(B("OPENAI_TIMEOUT")):void 0,retries:l=Number(B("OPENAI_RETRIES")??0),retryDelay:d=Number(B("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=B("OPENAI_SEED")!=null?Number(B("OPENAI_SEED")):void 0,generatePrompt:_=ar,summarizePrompt:p=or}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
66
+ Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var le=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vn extends fi{constructor({apiKey:t=le("ANTHROPIC_API_KEY"),model:i=le("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=le("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(le("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(le("ANTHROPIC_TEMPERATURE")??0.3),topP:o=le("ANTHROPIC_TOP_P")!=null?Number(le("ANTHROPIC_TOP_P")):void 0,topK:c=le("ANTHROPIC_TOP_K")!=null?Number(le("ANTHROPIC_TOP_K")):void 0,timeout:l=le("ANTHROPIC_TIMEOUT")!=null?Number(le("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(le("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(le("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=ar,summarizePrompt:p=or}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
67
+ Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var me=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Gn extends fi{constructor({model:t=me("OLLAMA_MODEL")??"llama3.2",host:i=me("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(me("OLLAMA_TEMPERATURE")??0.3),topP:s=me("OLLAMA_TOP_P")!=null?Number(me("OLLAMA_TOP_P")):void 0,topK:n=me("OLLAMA_TOP_K")!=null?Number(me("OLLAMA_TOP_K")):void 0,timeout:a=me("OLLAMA_TIMEOUT")!=null?Number(me("OLLAMA_TIMEOUT")):void 0,retries:o=Number(me("OLLAMA_RETRIES")??0),retryDelay:c=Number(me("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=ar,summarizePrompt:f=or}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
68
+ Schema: ${JSON.stringify(t)}
69
+ Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
70
+
71
+ ${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function sc({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new zn({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new Bn({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new be("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function nc({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new Xn({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new Vn({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new Gn({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var $i="AES-GCM",Dt=12,qe=32,ac=new TextEncoder,oc=new TextDecoder;class Hn extends sr{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?lc(i):Uint8Array.from(i),this._rawKey.length!==qe)throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${qe} bytes (${qe*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:$i},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(Dt)),s=ac.encode(t),n=await globalThis.crypto.subtle.encrypt({name:$i,iv:r,tagLength:128},i,s),a=new Uint8Array(Dt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),Dt),cc(a)}async _decrypt(t){let i=await this._getKey(),r=dc(t),s=r.slice(0,Dt),n=r.slice(Dt),a=await globalThis.crypto.subtle.decrypt({name:$i,iv:s,tagLength:128},i,n);return oc.decode(a)}}function lc(t){if(t.length!==qe*2)throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${qe*2} characters (${qe} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(qe);for(let r=0;r<qe;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function cc(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function dc(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var uc=4;class Wn{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
72
+ `)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
73
+ `),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/uc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Jn{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function hc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Yn{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return hc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function fc(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&_c(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function _c(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function pc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Qn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Zn{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class ea{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class ta{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ct(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var hs=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function gc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ct(i.collection))??null;case"skalex_find":{let s=r.useCollection(ct(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ct(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ct(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ct(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ct(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ct(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var lr="2.0",cr=-32700,mc=-32600,fs=-32601,yc=-32602,wc=-32603;function Et(t,i){return{jsonrpc:lr,id:t,result:i}}function Be(t,i,r,s){return{jsonrpc:lr,id:t,error:{code:i,message:r}}}function Ac(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==lr)return{parseError:Be(null,mc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Be(null,cr,"Parse error")}}}function vc(t){return{content:[{type:"text",text:t}]}}function _s(t){return{content:[{type:"text",text:t}],isError:!0}}class ia{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
74
+
75
+ `;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=bo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
76
+ data: /message
77
+
78
+ `),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class ra{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
79
+ `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
80
+ `))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var Ec={name:"skalex",version:"4.0.0-alpha"},xc="2024-11-05";class sa{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new ia({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new ra;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Ac(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(Et(s,{protocolVersion:xc,capabilities:{tools:{}},serverInfo:Ec}));break;case"tools/list":this._send(Et(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(Et(s,{}));break;default:this._send(Be(s,fs,`Method not found: ${n}`))}}catch(o){this._send(Be(s,wc,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Be(t,yc,"tools/call requires params.name"));return}let n=hs.find((o)=>o.name===r);if(!n){this._send(Be(t,fs,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(Et(t,_s(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await gc(r,s,this._db);this._send(Et(t,vc(JSON.stringify(o,null,2))))}catch(o){this._send(Et(t,_s(o.message||String(o))))}}_visibleTools(){return hs.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Ht="migrations",ps=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),gs=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class he{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!he._errorsAttached)he.SkalexError=Qe,he.ValidationError=P,he.UniqueConstraintError=je,he.TransactionError=Ne,he.PersistenceError=He,he.AdapterError=be,he.QueryError=ft,he._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new jn({dir:t,format:i});if(a)E=new Hn(E,a.key);if(this.fs=E,this._registry=new Kn(Mn),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new qn,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??ps,this._deserializer=m??gs,this._autoSave=w??!1,this._txManager=new Fn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??ns,this._embeddingAdapter=h??(n?sc(n):null),this._aiAdapter=f??(n?nc(n):null),this._persistence=new Un({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Jn(this),this._queryCache=new Yn(c||{}),this._eventBus=new Qn,this._queryLog=o?new Zn(o):null,this._sessionStats=new ea,this._plugins=new ta,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:kn,buildIndex:this._registry.buildIndex,IndexEngine:ri});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new be("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new P("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new he({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==ns?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==ps?this._serializer:void 0,deserializer:this._deserializer!==gs?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new He("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new be("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new be("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=pc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(fc(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Wn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new sa(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Ht)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Ht);if(r)Object.assign(r,t);else{let s={_id:Ht,...t};i.data.push(s),i.index.set(Ht,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Yl(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Sc(){let t=Date.now().toString(16),i;try{i=Do.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function ms(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var ys=new Set(["__proto__","constructor","prototype"]);function _i(t,i){if(!i.includes(".")){if(ys.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(ys.has(s))return;if(r==null)return;r=r[s]}return r}class Ze extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class j extends Ze{}class Ue extends Ze{}class $e extends Ze{}class We extends Ze{}class Oe extends Ze{}class _t extends Ze{}function Fi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Fi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Fi(t[s],i[s]))return!1}return!0}return!1}function ne(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new _t("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ne(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new _t("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ne(t,s)))return!1}if("$not"in i){if(ne(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=_i(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Fi(n,s))return!1}else if(n!==s)return!1}return!0}function Ic(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Ki=new Set(["string","number","boolean","object","array","date","any"]);function dr(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function na(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Ki.has(n))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Ki.has(o))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new j("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function ws(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=dr(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function As(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(dr(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function bc(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=dr(s);i[r]=Ki.has(n)?n:"any"}return i}function Tc(t){if(typeof t==="number"){if(t<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new j("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new j("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Oc(t){return new Date(Date.now()+Tc(t))}function Rc(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function vs(t,i){if(t.length!==i.length)throw new _t("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function te(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Cc(t){return t.length}function Nc(t,i){let r=0;for(let s of t){let n=_i(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function $c(t,i){let r=0,s=0;for(let n of t){let a=_i(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function kc(t,i){let r=Object.create(null);for(let s of t){let n=String(_i(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class aa{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:te(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:te(m)});return{docs:p,prevDocs:g}}}function Dc(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var oa=new Set(["__proto__","constructor","prototype"]);function la(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(oa.has(r))continue;i[r]=la(t[r])}return i}class ca{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new aa(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return te({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return te(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(te)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Ue("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return te(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(te)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(oa.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=la(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=ws(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new j("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=As(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new We("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Dc(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new _t("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return te(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ne(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ne(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Cc(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Nc(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),$c(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),kc(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Ic(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ne(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=vs(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>te(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=vs(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>te(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return te(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return te(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(te)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(te)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ne(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ne(u,t));if(a.length===0)throw new _t("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
81
+ `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
82
+ `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Oe("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=ws(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return As(t,this._schema);default:throw new j("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ne(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ne(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ne(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ne(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ne(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ne(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Sc)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Oc(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class ur{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class da extends ur{constructor({dir:t,format:i="gz"}){super();this.dir=at.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!Y.existsSync(t))Y.mkdirSync(t,{recursive:!0})}_filePath(t){return at.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await Y.promises.readFile(i);if(this.format==="gz")r=bi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=at.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=bi.deflateSync(i);await Y.promises.writeFile(s,n)}else await Y.promises.writeFile(s,i,"utf8");await Y.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=at.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=bi.deflateSync(s);await Y.promises.writeFile(a,o)}else await Y.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await Y.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await Y.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await Y.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await Y.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return at.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(at.dirname(t)),await Y.promises.writeFile(t,i,"utf8")}async readRaw(t){return Y.promises.readFile(at.resolve(t),"utf8")}}class ua{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new j("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Es={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function xs(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function ki(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class si{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=ki(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?xs(s):Es}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=ki(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?xs(a):Es}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new j("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new j("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=ki(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Yt="_flush",Qt="migrations";class ha{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new We("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new We("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Yt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Yt])i[Yt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Qt);if(!r)return;let s=r[Yt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Qt);if(!r)r={_id:Qt},i.data.push(r),i.index.set(Qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Lc=0;class fa{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Lc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new $e("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new $e("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new $e("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class _a{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=na(i);let _=f.uniqueFields;if(r.length||_.length)h=new si(r,_)}else if(r.length)h=new si(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return bc(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class hr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var xe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class pa extends hr{constructor({apiKey:t=xe("OPENAI_API_KEY"),model:i=xe("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=xe("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=xe("OPENAI_EMBED_DIMENSIONS")!=null?Number(xe("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=xe("OPENAI_ORGANIZATION")??void 0,timeout:a=xe("OPENAI_EMBED_TIMEOUT")!=null?Number(xe("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(xe("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(xe("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var xt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ga extends hr{constructor({model:t=xt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=xt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=xt("OLLAMA_EMBED_TIMEOUT")!=null?Number(xt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(xt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(xt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class pi{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var fr=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
83
+
84
+ Rules:
85
+ - Return ONLY a valid JSON object, nothing else
86
+ - Use standard query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $regex
87
+ - For simple equality, use plain key-value pairs: {"field": "value"}
88
+ - For numeric comparisons use operators: {"age": {"$gt": 18}}
89
+ - For text search use $regex: {"name": {"$regex": "pattern"}}
90
+ - Return {} to match all documents
91
+ - No explanations, no markdown, no code fences`,_r="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",V=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ma extends pi{constructor({apiKey:t=V("OPENAI_API_KEY"),model:i=V("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=V("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=V("OPENAI_MAX_TOKENS")!=null?Number(V("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(V("OPENAI_TEMPERATURE")??0.3),topP:a=V("OPENAI_TOP_P")!=null?Number(V("OPENAI_TOP_P")):void 0,organization:o=V("OPENAI_ORGANIZATION")??void 0,timeout:c=V("OPENAI_TIMEOUT")!=null?Number(V("OPENAI_TIMEOUT")):void 0,retries:l=Number(V("OPENAI_RETRIES")??0),retryDelay:d=Number(V("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=V("OPENAI_SEED")!=null?Number(V("OPENAI_SEED")):void 0,generatePrompt:_=fr,summarizePrompt:p=_r}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
92
+ Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ce=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ya extends pi{constructor({apiKey:t=ce("ANTHROPIC_API_KEY"),model:i=ce("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=ce("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(ce("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(ce("ANTHROPIC_TEMPERATURE")??0.3),topP:o=ce("ANTHROPIC_TOP_P")!=null?Number(ce("ANTHROPIC_TOP_P")):void 0,topK:c=ce("ANTHROPIC_TOP_K")!=null?Number(ce("ANTHROPIC_TOP_K")):void 0,timeout:l=ce("ANTHROPIC_TIMEOUT")!=null?Number(ce("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(ce("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(ce("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=fr,summarizePrompt:p=_r}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
93
+ Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ye=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class wa extends pi{constructor({model:t=ye("OLLAMA_MODEL")??"llama3.2",host:i=ye("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(ye("OLLAMA_TEMPERATURE")??0.3),topP:s=ye("OLLAMA_TOP_P")!=null?Number(ye("OLLAMA_TOP_P")):void 0,topK:n=ye("OLLAMA_TOP_K")!=null?Number(ye("OLLAMA_TOP_K")):void 0,timeout:a=ye("OLLAMA_TIMEOUT")!=null?Number(ye("OLLAMA_TIMEOUT")):void 0,retries:o=Number(ye("OLLAMA_RETRIES")??0),retryDelay:c=Number(ye("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=fr,summarizePrompt:f=_r}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
94
+ Schema: ${JSON.stringify(t)}
95
+ Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
96
+
97
+ ${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function Pc({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new pa({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new ga({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Oe("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function Mc({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new ma({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new ya({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new wa({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Di="AES-GCM",Lt=12,Fe=32,jc=new TextEncoder,qc=new TextDecoder;class Aa extends ur{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Uc(i):Uint8Array.from(i),this._rawKey.length!==Fe)throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Fe} bytes (${Fe*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Di},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(Lt)),s=jc.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Di,iv:r,tagLength:128},i,s),a=new Uint8Array(Lt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),Lt),Fc(a)}async _decrypt(t){let i=await this._getKey(),r=Kc(t),s=r.slice(0,Lt),n=r.slice(Lt),a=await globalThis.crypto.subtle.decrypt({name:Di,iv:s,tagLength:128},i,n);return qc.decode(a)}}function Uc(t){if(t.length!==Fe*2)throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Fe*2} characters (${Fe} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Fe);for(let r=0;r<Fe;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function Fc(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function Kc(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var zc=4;class va{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
98
+ `)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
99
+ `),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/zc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Ea{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Bc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class xa{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Bc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Xc(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Vc(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Vc(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function Gc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Sa{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Ia{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class ba{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Ta{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function dt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var Ss=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function Hc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(dt(i.collection))??null;case"skalex_find":{let s=r.useCollection(dt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(dt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(dt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(dt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(dt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(dt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var pr="2.0",gr=-32700,Wc=-32600,Is=-32601,Jc=-32602,Yc=-32603;function St(t,i){return{jsonrpc:pr,id:t,result:i}}function Xe(t,i,r,s){return{jsonrpc:pr,id:t,error:{code:i,message:r}}}function Qc(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==pr)return{parseError:Xe(null,Wc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Xe(null,gr,"Parse error")}}}function Zc(t){return{content:[{type:"text",text:t}]}}function bs(t){return{content:[{type:"text",text:t}],isError:!0}}class Oa{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
100
+
101
+ `;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=Lo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
102
+ data: /message
103
+
104
+ `),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class Ra{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
105
+ `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
106
+ `))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var ed={name:"skalex",version:"4.0.0-alpha"},td="2024-11-05";class Ca{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Oa({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new Ra;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Qc(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(St(s,{protocolVersion:td,capabilities:{tools:{}},serverInfo:ed}));break;case"tools/list":this._send(St(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(St(s,{}));break;default:this._send(Xe(s,Is,`Method not found: ${n}`))}}catch(o){this._send(Xe(s,Yc,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Xe(t,Jc,"tools/call requires params.name"));return}let n=Ss.find((o)=>o.name===r);if(!n){this._send(Xe(t,Is,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(St(t,bs(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await Hc(r,s,this._db);this._send(St(t,Zc(JSON.stringify(o,null,2))))}catch(o){this._send(St(t,bs(o.message||String(o))))}}_visibleTools(){return Ss.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Zt="migrations",Ts=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Os=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class fe{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!fe._errorsAttached)fe.SkalexError=Ze,fe.ValidationError=j,fe.UniqueConstraintError=Ue,fe.TransactionError=$e,fe.PersistenceError=We,fe.AdapterError=Oe,fe.QueryError=_t,fe._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new da({dir:t,format:i});if(a)E=new Aa(E,a.key);if(this.fs=E,this._registry=new _a(ca),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new ua,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Ts,this._deserializer=m??Os,this._autoSave=w??!1,this._txManager=new fa,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??ms,this._embeddingAdapter=h??(n?Pc(n):null),this._aiAdapter=f??(n?Mc(n):null),this._persistence=new ha({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Ea(this),this._queryCache=new xa(c||{}),this._eventBus=new Sa,this._queryLog=o?new Ia(o):null,this._sessionStats=new ba,this._plugins=new Ta,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:na,buildIndex:this._registry.buildIndex,IndexEngine:si});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Oe("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new j("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new fe({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==ms?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Ts?this._serializer:void 0,deserializer:this._deserializer!==Os?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new We("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Oe("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Oe("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=Gc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Xc(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new va(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new Ca(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Zt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Zt);if(r)Object.assign(r,t);else{let s={_id:Zt,...t};i.data.push(s),i.index.set(Zt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Rc(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}class Na{}var id=new Map;function rd(t,i){id.set(t,i)}var Rs=()=>new Date().toISOString();function S(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class mr extends Na{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=ko(t.dataDir,".agent-db.lock")}static async create(t){if(!Oo(t.dataDir))Ro(t.dataDir,{recursive:!0});let i=new mr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=Co(this.lockPath,"wx",384),$o(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(No(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Dr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{To(this.lockFd)}catch{}this.lockFd=null}try{Dr(this.lockPath)}catch{}}async init(){this.db=new fe({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return S(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?S(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>S(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Rs()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return S(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?S(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?S(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>S(t))}async updateGitRepository(t,i){let r={lastScanned:Rs()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return S(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?S(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>S(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return S(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?S(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var $a=(t)=>mr.create(t);rd("skalex",$a);var sd=new Map;function ka(t,i){sd.set(t,i)}class Da{}ka("skalex",$a);var Cs=()=>new Date().toISOString();function I(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class yr extends Da{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=So(t.dataDir,".agent-db.lock")}static async create(t){if(!wo(t.dataDir))Ao(t.dataDir,{recursive:!0});let i=new yr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=vo(this.lockPath,"wx",384),xo(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(Eo(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{kr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{yo(this.lockFd)}catch{}this.lockFd=null}try{kr(this.lockPath)}catch{}}async init(){this.db=new he({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return I(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?I(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>I(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Cs()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return I(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?I(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?I(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>I(t))}async updateGitRepository(t,i){let r={lastScanned:Cs()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return I(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?I(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>I(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return I(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?I(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var La=(t)=>yr.create(t);ka("skalex",La);var nd=new Map;function Pa(t,i){nd.set(t,i)}class Ma{}Pa("skalex",La);var Ns=()=>new Date().toISOString();function R(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class wr extends Ma{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=po(t.dataDir,".agent-db.lock")}static async create(t){if(!co(t.dataDir))uo(t.dataDir,{recursive:!0});let i=new wr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=ho(this.lockPath,"wx",384),_o(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(fo(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{$r(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{lo(this.lockFd)}catch{}this.lockFd=null}try{$r(this.lockPath)}catch{}}async init(){this.db=new ue({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return R(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?R(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>R(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Ns()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return R(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?R(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?R(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>R(t))}async updateGitRepository(t,i){let r={lastScanned:Ns()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return R(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?R(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>R(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return R(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?R(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var ja=(t)=>wr.create(t);Pa("skalex",ja);var ad=new Map;function qa(t,i){ad.set(t,i)}class Ua{}qa("skalex",ja);var $s=()=>new Date().toISOString();function k(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class Ar extends Ua{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=no(t.dataDir,".agent-db.lock")}static async create(t){if(!eo(t.dataDir))to(t.dataDir,{recursive:!0});let i=new Ar(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=io(this.lockPath,"wx",384),so(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(ro(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Nr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{Za(this.lockFd)}catch{}this.lockFd=null}try{Nr(this.lockPath)}catch{}}async init(){this.db=new de({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return k(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?k(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>k(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:$s()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return k(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?k(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?k(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>k(t))}async updateGitRepository(t,i){let r={lastScanned:$s()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return k(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?k(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>k(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return k(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?k(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var Fa=(t)=>Ar.create(t);qa("skalex",Fa);var vr=new Map;function od(t,i){vr.set(t,i)}function ks(t){return vr.get(t)}function ld(){return Array.from(vr.keys())}async function cd(t){if(t.adapterFactory)return t.adapterFactory;let i=t.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(i.startsWith("custom:")){let s=i.slice(7);if(!s)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let n=await import(s),a=n.default??n.createAdapter;if(typeof a!=="function")throw Error(`Custom storage adapter at ${s} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return a}let r=ks(i);if(!r){let s={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[i];if(s)try{await import(s),r=ks(i)}catch{}}if(!r)throw Error(`Unknown storage adapter: "${i}". Registered adapters: ${ld().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${i})?`}`);return r}async function Jt(t){if(!t.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!t.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await cd(t))({dataDir:t.dbPath,encryptionKey:t.encryptionKey,adapterOptions:t.adapterOptions})}od("skalex",Fa);var dd="@vibecontrols/vibe-plugin-storage",yu=ud();function ud(){try{let t=Ei(Qa(import.meta.url));for(let i=0;i<10&&t&&t!==Ei(t);i++){let r=Ya(t,"package.json");if(Wa(r))try{let s=JSON.parse(Ja(r,"utf8"));if(s.name===dd&&typeof s.version==="string")return s.version}catch{}t=Ei(t)}}catch{}return"0.0.0"}import mi from"os";import{mkdirSync as Id}from"fs";import{join as bd}from"path";var Er=[0,5000,15000,30000,60000],hd=2000,fd=5000,_d=120000,Ka=10,pd=1048576;class xr extends Error{resetAt;resource;constructor(t,i,r){super(t);this.name="RateLimitError",this.resource=i,this.resetAt=r}}function Sr(t,i){if(!t?.length)return null;let r=t.find((a)=>a.extensions?.code==="RATE_LIMITED");if(!r)return null;let s=r.extensions?.resetAt,n=null;if(s){let a=new Date(s);if(!Number.isNaN(a.getTime()))n=a}return new xr(`${i} rate limited${n?` until ${n.toISOString()}`:""}`,i,n)}function gd(t){if(!t.resetAt)return 60000;let i=t.resetAt.getTime()-Date.now()+hd;return Math.min(Math.max(i,fd),_d)}async function md(t,i){let r=t.headers.get("content-length");if(r){let l=Number.parseInt(r,10);if(Number.isInteger(l)&&l>i)throw Error(`Gateway response is too large (${l} bytes)`)}if(!t.body)return"";let s=t.body.getReader(),n=[],a=0;try{while(!0){let{done:l,value:d}=await s.read();if(l)break;if(!d)continue;if(a+=d.byteLength,a>i)throw await s.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${i} bytes`);n.push(d)}}finally{s.releaseLock()}let o=new Uint8Array(a),c=0;for(let l of n)o.set(l,c),c+=l.byteLength;return new TextDecoder().decode(o)}async function Ir(t,i){let r=await md(t,pd),s;try{s=r?JSON.parse(r):{}}catch(n){let a=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} returned non-JSON response (${t.status} ${t.statusText})${a?`: ${a}`:""}`,{cause:n})}if(!t.ok){let n=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} failed (${t.status} ${t.statusText})${n?`: ${n}`:""}`)}return s}function br(t){return t.endsWith("/graphql")?t:`${t}/graphql`}function yd(t){let i;try{i=new URL(t).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(i==="localhost"||i==="127.0.0.1"||i==="::1"||i==="0.0.0.0"||i==="host.docker.internal")return!0;return i.endsWith(".localhost")||i.endsWith(".local")||i.endsWith(".local.burdenoff.com")}function Tr(t){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!yd(t))return{};return{tls:{rejectUnauthorized:!1}}}async function wd(t,i,r){let s=await fetch(br(t),{method:"POST",...Tr(t),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
107
+ authenticateApp(input: $input) { accessToken expiresIn }
108
+ }`,variables:{input:{clientId:i,clientSecret:r,scopes:[]}}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"authenticateApp"),a=Sr(n.errors,"authenticateApp");if(a)throw a;if(n.errors?.length){let c=n.errors.map((l)=>l.extensions?.code??"UNKNOWN").join(",");throw Error(`authenticateApp errors [${c}]: ${n.errors.map((l)=>l.message).join("; ")}`)}let o=n.data?.authenticateApp?.accessToken;if(!o)throw Error("authenticateApp returned no token");return o}async function Ad(t,i,r,s){let n=await fetch(br(t),{method:"POST",...Tr(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:`mutation IssueAgentWorkspaceToken($input: IssueWorkspaceTokenInput!) {
109
+ issueWorkspaceToken(input: $input) {
110
+ success
111
+ token
112
+ expiresAt
113
+ error { code message }
114
+ }
115
+ }`,variables:{input:{organizationId:s||r,workspaceId:r}}}),signal:AbortSignal.timeout(15000)}),a=await Ir(n,"issueWorkspaceToken"),o=Sr(a.errors,"issueWorkspaceToken");if(o)throw o;if(a.errors?.length)throw Error(`issueWorkspaceToken errors: ${a.errors.map((l)=>l.message).join("; ")}`);let c=a.data?.issueWorkspaceToken;if(!c?.success||!c.token){let l=c?.error?.code??"UNKNOWN",d=c?.error?.message??"no workspace token returned";throw Error(`issueWorkspaceToken failed [${l}]: ${d}`)}return c.token}async function vd(t){let i=await wd(t.globalGatewayUrl,t.clientId,t.clientSecret),r=await Ad(t.workspaceGatewayUrl,i,t.workspaceId,t.organizationId),s=await fetch(br(t.workspaceGatewayUrl),{method:"POST",...Tr(t.workspaceGatewayUrl),headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,"X-Workspace-Authorization":`Bearer ${r}`},body:JSON.stringify({query:`query FetchAgentEncryptionKey($workspaceId: ID!) {
116
+ vibecontrolsAgentEncryptionKey(workspaceId: $workspaceId)
117
+ }`,variables:{workspaceId:t.workspaceId}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"vibecontrolsAgentEncryptionKey"),a=Sr(n.errors,"vibecontrolsAgentEncryptionKey");if(a)throw a;if(n.errors?.length)throw Error(`vibecontrolsAgentEncryptionKey errors: ${n.errors.map((c)=>c.message).join("; ")}`);let o=n.data?.vibecontrolsAgentEncryptionKey;if(!o)throw Error("vibecontrolsAgentEncryptionKey returned empty");return o}async function Wt(t,i=Er.length,r={}){let s={...t,globalGatewayUrl:z(t.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:z(t.workspaceGatewayUrl,"workspaceGatewayUrl")},n=r.signal,a=()=>{if(n?.aborted)throw n.reason instanceof Error?n.reason:Error("encryption key fetch aborted")},o=(u)=>new Promise((f,h)=>{let _=setTimeout(()=>{if(n)n.removeEventListener("abort",p);f()},u),p=()=>{clearTimeout(_),h(n?.reason instanceof Error?n.reason:Error("encryption key fetch aborted"))};n?.addEventListener("abort",p,{once:!0})}),c,l=0,d=0;while(l<i){a();try{let u=await vd(s);return e().logger.info("finalizer","Storage encryption key fetched from backend",{attempt:l+1,rateLimitRetries:d}),u}catch(u){if(c=u,a(),u instanceof xr){if(d>=Ka){e().logger.error("finalizer","Rate-limit retries exhausted; giving up",{resource:u.resource,resetAt:u.resetAt?.toISOString()??null,rateLimitRetries:d});break}let _=gd(u);d+=1,e().logger.warn("finalizer",`Rate limited by ${u.resource}; waiting ${Math.round(_/1000)}s for window to clear (retry ${d}/${Ka})`,{resource:u.resource,resetAt:u.resetAt?.toISOString()??null,waitMs:_}),await o(_);continue}if(l+=1,l>=i){e().logger.error("finalizer","Failed to fetch storage encryption key from backend (final attempt)",{error:String(u),attempts:i});break}let h=Er[l]??Er.at(-1)??0;if(e().logger.warn("finalizer",`Storage key fetch attempt ${l}/${i} failed; retrying in ${Math.round(h/1000)}s`,{error:String(u)}),h>0)await o(h)}}throw c instanceof Error?c:Error(String(c??"encryption key fetch failed"))}async function Ed(t){let i=await xd(t);if(i)return i;return Sd(t.name)}async function xd(t){let i;try{i=await X({dir:t.dataDir,scope:t.name})}catch{return null}if(!i.clientId||!i.clientSecret||!i.globalGatewayUrl||!i.workspaceGatewayUrl||!i.workspaceId)return null;return{clientId:i.clientId,clientSecret:i.clientSecret,globalGatewayUrl:i.globalGatewayUrl,workspaceGatewayUrl:i.workspaceGatewayUrl,workspaceId:i.workspaceId,organizationId:i.organizationId}}function Sd(t){let i=t.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase(),r=(l)=>process.env[`VIBE_${i}_${l}`],s=r("CLIENT_ID"),n=r("CLIENT_SECRET"),a=r("GLOBAL_GATEWAY_URL"),o=r("WORKSPACE_GATEWAY_URL"),c=r("WORKSPACE_ID");if(!s||!n||!a||!o||!c)return null;return{clientId:s,clientSecret:n,globalGatewayUrl:a,workspaceGatewayUrl:o,workspaceId:c,organizationId:r("ORGANIZATION_ID")}}async function Ai(t){let i=await Ed(t);if(!i)return{ok:!1,error:`no creds for profile '${t.name}' (run gateway-auth against this profile or set VIBE_${t.name.toUpperCase()}_* env vars)`};t.setBootState("initializing");let r;try{let c=await Wt(i);r=await Jt({dbPath:t.dataDir,encryptionKey:c})}catch(c){return t.setBootState("awaiting-config"),{ok:!1,error:c instanceof Error?c.message:String(c)}}let s=new Te(r);await s.hydrateDefaultsFromDb();let n=new W(r);await n.loadCorePlugins();try{await n.loadAll()}catch(c){t.logger.warn("secondary-profile-attach","failed to load some external plugins for secondary profile",{error:c instanceof Error?c.message:String(c)})}let a={storage:{async get(c,l){return await r.getPluginState(c,l)??null},async set(c,l,d){await r.setPluginState(c,l,d)},async delete(c,l){return r.deletePluginState(c,l)},async list(c){return await r.getAllPluginState(c)},async deleteAll(c){return r.deleteAllPluginState(c)}},logger:t.logger,serviceRegistry:s,getProvider:(c)=>s.getProvider(c),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:0",getAgentVersion:()=>"0.0.0",broadcast:()=>{},workspaceQuery:async()=>({}),isGatewayConfigured:()=>!0,getAgentRecordId:async()=>await r.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await r.getConfig("gateway-auth:workspaceId")??null,getConfig:async(c)=>await r.getConfig(c)??void 0,getPluginRegistry:()=>"",getDataDir:()=>t.dataDir,cliContributors:new Ee,audit:{emit:(c,l)=>t.audit.emit("agent",c,l??{})},telemetry:{emit:()=>{}},os:b(),iframeBridge:ke()},o=new bt(s,n,r,{},a,async()=>{});s.registerService("agent","lifecycle",o),t.attachServices({db:r,serviceRegistry:s,pluginManager:n,lifecycle:o,hostServices:a});try{pt(t)}catch(c){t.logger.warn("secondary-profile-attach","failed to mount per-profile plugin routes",{error:c instanceof Error?c.message:String(c)})}try{await t.keyVault.bindApiKey(K())}catch{}return t.setBootState("ready"),{ok:!0}}var Tt="profile-reconciler",Td=60000,Od=5000,Rd=30000,Cd=15,Nd=200,$d=`
118
+ query VibecontrolsAgentProfiles($agentId: ID!) {
119
+ vibecontrolsAgentProfiles(agentId: $agentId) {
120
+ id
121
+ name
122
+ status
123
+ isDefault
124
+ }
125
+ }
126
+ `,kd=`
127
+ mutation UpdateVibecontrolsAgentProfile($id: ID!, $input: UpdateVibecontrolsAgentProfileInput!) {
128
+ updateVibecontrolsAgentProfile(id: $id, input: $input) {
129
+ id
130
+ status
131
+ }
132
+ }
133
+ `;function gi(t){return bd(C(),"agents",O(t))}async function Xa(t){try{let i=await X({dir:gi(t),scope:O(t)});return Boolean(i.clientId&&i.clientSecret)}catch{return!1}}async function Dd(t){for(let i=0;i<Cd;i++){if(await Xa(t))return!0;await new Promise((r)=>setTimeout(r,Nd))}return!1}async function Ld(t,i,r){let s,n=new Promise((a,o)=>{s=setTimeout(()=>o(Error(`${r} timed out after ${i}ms`)),i)});try{return await Promise.race([t,n])}finally{if(s)clearTimeout(s)}}var Ot=null,Or=!1;async function za(t,i){try{await T.workspaceQuery(kd,{id:t,input:{status:i}})}catch{}}async function Ba(t){if(!T.isConfigured()||Or)return;Or=!0;let i=e().logger;try{let r=await t.getConfig("gateway-auth:agentRecordId");if(!r)return;let s=await T.workspaceQuery($d,{agentId:r});if(s.errors?.length)return;let n=s.data?.vibecontrolsAgentProfiles??[];if(n.length===0)return;let a=e().name,o;try{o=await X({dir:gi(a),scope:a})}catch{o=void 0}for(let c of n){if(c.isDefault||c.name===a||c.name==="default")continue;let l=N.get(c.name);if(l&&l.getBootState()==="ready"){if(c.status!=="ready")await za(c.id,"ready");continue}if(o?.clientId&&o.clientSecret&&!await Xa(c.name))try{if(Id(gi(c.name),{recursive:!0}),M({globalGatewayUrl:o.globalGatewayUrl,workspaceGatewayUrl:o.workspaceGatewayUrl,workspaceId:o.workspaceId,organizationId:o.organizationId,clientId:o.clientId,clientSecret:o.clientSecret},{dir:gi(c.name),scope:O(c.name)}),!await Dd(c.name)){i.warn(Tt,`Seeded creds for profile '${c.name}' not yet readable; retrying next tick`);continue}}catch(d){i.warn(Tt,`Failed to seed config for profile '${c.name}'`,{error:d instanceof Error?d.message:String(d)});continue}i.info(Tt,`Reconciling desired profile '${c.name}' from control plane`);try{let d=it(c.name),u=await Ld(Ai(d),Rd,`attach '${c.name}'`),f=d.getBootState();await za(c.id,f),i.info(Tt,`Profile '${c.name}' reconciled`,{ok:u.ok,status:f,error:u.error})}catch(d){i.warn(Tt,`Failed to reconcile profile '${c.name}'`,{error:d instanceof Error?d.message:String(d)})}}}catch(r){e().logger.debug(Tt,`Reconcile pass failed: ${r instanceof Error?r.message:String(r)}`)}finally{Or=!1}}function Rt(t,i){if(Ot)return;let r=Number(process.env.VIBE_PROFILE_RECONCILE_MS),s=Number.isFinite(r)&&r>0?Math.max(r,Od):i??Td;Ba(t),Ot=setInterval(()=>{Ba(t)},s),Ot.unref?.()}function ci(){if(Ot)clearInterval(Ot),Ot=null}var et=10,Rr=3000,y="auto-report",Ha=`
134
+ mutation RegisterInstalledAgent($workspaceId: ID!, $input: RegisterInstalledAgentInput!) {
135
+ registerInstalledAgent(workspaceId: $workspaceId, input: $input) {
136
+ id
137
+ name
138
+ hostname
139
+ tunnelUrl
140
+ }
141
+ }
142
+ `,Mt=`
143
+ mutation UpdateVibecontrolsAgent($id: ID!, $input: UpdateVibecontrolsAgentInput!) {
144
+ updateVibecontrolsAgent(id: $id, input: $input) {
145
+ id
146
+ tunnelUrl
147
+ tunnelStatus
148
+ }
149
+ }
150
+ `,wi=`
151
+ query FindExistingAgent($workspaceId: ID!) {
152
+ vibecontrolsAgents(filter: { workspaceId: $workspaceId }) {
153
+ id
154
+ hostname
155
+ tunnelUrl
156
+ }
157
+ }
158
+ `,Pd=`
159
+ mutation AgentHeartbeat($id: ID!) {
160
+ vibecontrolsAgentHeartbeat(id: $id) {
161
+ id
162
+ isActive
163
+ lastHeartbeat
164
+ }
165
+ }
166
+ `,Md=`
167
+ mutation DeactivateVibecontrolsAgent($id: ID!) {
168
+ deactivateVibecontrolsAgent(id: $id) {
169
+ id
170
+ isActive
171
+ }
172
+ }
173
+ `;async function jd(t){if(process.env.AGENT_TUNNEL_URL){let i=It(process.env.AGENT_TUNNEL_URL);if(!i)return e().logger.warn(y,"Ignoring invalid AGENT_TUNNEL_URL"),null;return e().logger.debug(y,`Using AGENT_TUNNEL_URL from environment: ${i}`),i}for(let i=1;i<=et;i++){let r=[],s=t.getProvider("tunnel");if(s)r.push(s);for(let n of t.listProvidersForType("tunnel")){let a=t.getProviderByName("tunnel",n.pluginName);if(a&&!r.includes(a))r.push(a)}for(let n of r){if(!n.getActiveTunnelUrl)continue;let a=await n.getActiveTunnelUrl(),o=ii(a);if(o)return e().logger.debug(y,`Tunnel URL available on attempt ${i}: ${o}`),o;if(a)e().logger.warn(y,"Tunnel provider returned invalid URL",{url:a})}if(i<et)e().logger.debug(y,`Tunnel URL not ready, retrying in ${Rr/1000}s (attempt ${i}/${et})`),await new Promise((n)=>setTimeout(n,Rr))}return e().logger.warn(y,`Tunnel URL not available after ${et} attempts`),null}async function Cr(t,i){let r=await t.getConfig("gateway-auth:agentRecordId");if(r)return r;let s=await t.getConfig("gateway-auth:workspaceId");if(!s)return null;let n=await T.workspaceQuery(wi,{workspaceId:s});if(n.errors?.length)return e().logger.warn(y,"Failed to discover existing agent record",{errors:n.errors.map((c)=>c.message)}),null;let a=i.toLowerCase(),o=n.data?.vibecontrolsAgents?.find((c)=>c.hostname.toLowerCase()===a);if(!o)return null;return await t.setConfig("gateway-auth:agentRecordId",o.id),e().logger.info(y,"Recovered existing agent record ID",{agentRecordId:o.id,hostname:i}),o.id}async function qd(t,i){try{let r=await T.workspaceQuery(wi,{workspaceId:t});if(r.errors?.length)return!0;let s=r.data?.vibecontrolsAgents;if(!s)return!0;return s.some((n)=>n.id===i)}catch{return!0}}async function vi(t,i){if(!T.isConfigured())return;let r=await Cr(t,process.env.VIBE_AGENT_NAME||mi.hostname());if(!r)return;if(i!=="killed"){e().logger.debug(y,`Skipping '${i}' lifecycle sync \u2014 startup auto-report already refreshes the live agent record and the current backend schema has no dedicated lifecycle field.`);return}let s=await T.workspaceQuery(Md,{id:r});if(s.errors?.length)e().logger.warn(y,`Failed to report lifecycle state '${i}'`,{errors:s.errors.map((n)=>n.message)});else e().logger.info(y,`Reported lifecycle state: ${i}`)}async function Va(t,i,r){let s=r||T.getConfig()?.workspaceId||"";for(let n=1;n<=3;n++){await new Promise((l)=>setTimeout(l,1500));let c=(await T.workspaceQuery(wi,{workspaceId:s})).data?.vibecontrolsAgents?.find((l)=>l.id===t)?.tunnelUrl??null;if(c===i)return e().logger.info(y,`Verified: backend tunnelUrl matches (attempt ${n})`),!0;e().logger.warn(y,`Verification failed (attempt ${n}/3): backend has '${c}', expected '${i}' \u2014 retrying update`),await T.workspaceQuery(Mt,{id:t,input:{tunnelUrl:i||null,tunnelStatus:i?"CONNECTED":"DISCONNECTED"}})}return e().logger.error(y,"Failed to verify tunnel URL update after 3 attempts"),!1}async function Ga(t,i){try{let r=await T.workspaceQuery(Ha,{workspaceId:t,input:{name:i.hostname,hostname:i.hostname,platform:i.platform,architecture:i.arch,tunnelUrl:i.tunnelUrl||null,agentApiKey:i.apiKey}});if(r.errors?.length)e().logger.debug(y,"API key re-assertion returned errors (non-fatal)",{errors:r.errors.map((s)=>s.message)});else e().logger.debug(y,"Re-asserted agent API key to backend")}catch(r){e().logger.debug(y,`API key re-assertion failed (non-fatal): ${r instanceof Error?r.message:String(r)}`)}}async function yi(t){try{let i=await T.workspaceQuery(Pd,{id:t});if(i.errors?.length)e().logger.debug(y,"Heartbeat returned errors",{errors:i.errors.map((r)=>r.message)});else e().logger.debug(y,"Heartbeat sent successfully")}catch(i){e().logger.debug(y,`Heartbeat failed: ${i instanceof Error?i.message:String(i)}`)}}var Ud=`
174
+ mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
175
+ notifyVibecontrolsAgentPluginChange(agentId: $agentId)
176
+ }
177
+ `;async function Xt(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Ud,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Vt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await yi(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(wi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function ui(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function li(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||mi.hostname(),a=mi.platform(),o=mi.arch(),c=_e(),l=await jd(i),d=await Cr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await qd(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Ga(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await yi(d),gt=l,Pt(t,i),Rt(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Va(d,l,s),await Ga(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await yi(d),gt=l,Pt(t,i),Rt(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Cr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Ha,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Rr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Rt(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});if(await Va(d,l,s),await yi(d),gt=l,Pt(t,i),Rt(t),process.env.VIBE_BRIDGE_DISABLED!=="1")try{let{bridgeClient:f}=await import("./bridge-client-xvqy3n15.js"),h=process.env.VIBECONTROLS_PROFILE||"default";f.start(d,h)}catch(f){e().logger.warn(y,`bridge-client start failed: ${f instanceof Error?f.message:String(f)}`)}}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Rt(t)}catch{}}}var x="lifecycle";class bt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await vi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await vi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([vi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
178
+ export{Jt,Wt,bt,Ai,ci,Xt,ui,li};