trellis 3.2.0 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +61 -171
  3. package/dist/browser/index.d.ts +18 -0
  4. package/dist/browser/index.d.ts.map +1 -0
  5. package/dist/browser/index.js +95 -0
  6. package/dist/{chunk-3ETIIPPB.js → chunk-2W3MHTMG.js} +190 -27
  7. package/dist/{chunk-MBNBTJCR.js → chunk-6GEZ6DN5.js} +2 -2
  8. package/dist/chunk-7ZFRVCUE.js +211 -0
  9. package/dist/chunk-CAG4FULI.js +121 -0
  10. package/dist/{chunk-GD5QJXSS.js → chunk-FWRS4CSC.js} +2 -2
  11. package/dist/{chunk-36VSSTL7.js → chunk-GU374KWZ.js} +1 -1
  12. package/dist/{chunk-3GDRZTAW.js → chunk-H6JB3PZ3.js} +1 -1
  13. package/dist/{chunk-ZHVI7BQN.js → chunk-IZX2PLIB.js} +191 -28
  14. package/dist/chunk-J2TXUFCZ.js +289 -0
  15. package/dist/{chunk-BJ7EZ7FP.js → chunk-JHHEXEDM.js} +17 -0
  16. package/dist/{chunk-X762XWVC.js → chunk-KIJITUZB.js} +1 -1
  17. package/dist/{chunk-7WQGTFVJ.js → chunk-L5N5PR2S.js} +130 -75
  18. package/dist/{chunk-BXSTJVE3.js → chunk-N6MYZT4O.js} +2 -1
  19. package/dist/{chunk-KKDRMIV6.js → chunk-QB5ISE47.js} +1 -1
  20. package/dist/{chunk-HO4TURXW.js → chunk-S3XLFZ27.js} +28 -11
  21. package/dist/{chunk-BQBUVMRN.js → chunk-S6GBJ2ZB.js} +25 -14
  22. package/dist/{chunk-IUWVEEOX.js → chunk-SGMDTWJJ.js} +4 -0
  23. package/dist/{chunk-FZVCXDYW.js → chunk-UQISRW6T.js} +65 -12
  24. package/dist/{chunk-B3ZIFA2O.js → chunk-VBYUTRXX.js} +1 -1
  25. package/dist/cli/deploy-cli.d.ts +18 -0
  26. package/dist/cli/deploy-cli.d.ts.map +1 -0
  27. package/dist/cli/index.d.ts +1 -1
  28. package/dist/cli/index.d.ts.map +1 -1
  29. package/dist/cli/index.js +153 -100
  30. package/dist/client/index.browser.d.ts +29 -0
  31. package/dist/client/index.browser.d.ts.map +1 -0
  32. package/dist/client/index.browser.js +64 -0
  33. package/dist/client/index.js +10 -10
  34. package/dist/client/sdk.browser.d.ts +104 -0
  35. package/dist/client/sdk.browser.d.ts.map +1 -0
  36. package/dist/{sdk-LZ7W3EEY.js → client/sdk.browser.js} +2 -2
  37. package/dist/client/sdk.js +1 -1
  38. package/dist/core/index.js +6 -6
  39. package/dist/db/index.js +18 -18
  40. package/dist/db/inspector.js +6 -6
  41. package/dist/db/trellis.css +1 -1
  42. package/dist/decisions/index.js +2 -2
  43. package/dist/deploy-LQ7GUGJ5.js +9 -0
  44. package/dist/{deploy-66EC752W.js → deploy-YNVG5E4E.js} +1 -1
  45. package/dist/deploy-cli-24BCHAXY.js +67 -0
  46. package/dist/deploy-cli-C35HTITO.js +67 -0
  47. package/dist/embeddings/auto-embed.d.ts.map +1 -1
  48. package/dist/embeddings/index.js +1 -1
  49. package/dist/embeddings/store.d.ts.map +1 -1
  50. package/dist/engine.d.ts +27 -7
  51. package/dist/engine.d.ts.map +1 -1
  52. package/dist/index.js +6 -6
  53. package/dist/mcp/server.d.ts.map +1 -1
  54. package/dist/react/index.js +2 -2
  55. package/dist/react/schema-hooks.js +7 -7
  56. package/dist/{remote-manager-SG545WNY.js → remote-manager-ODE3T2KR.js} +5 -5
  57. package/dist/scaffold/seed.d.ts.map +1 -1
  58. package/dist/scaffold/write.d.ts +1 -1
  59. package/dist/scaffold/write.d.ts.map +1 -1
  60. package/dist/schema/index.js +4 -3
  61. package/dist/server/deploy-meta.d.ts +25 -0
  62. package/dist/server/deploy-meta.d.ts.map +1 -0
  63. package/dist/server/deploy.d.ts +7 -2
  64. package/dist/server/deploy.d.ts.map +1 -1
  65. package/dist/server/index.d.ts +5 -2
  66. package/dist/server/index.d.ts.map +1 -1
  67. package/dist/server/index.js +52 -18
  68. package/dist/server/realtime.d.ts +4 -1
  69. package/dist/server/realtime.d.ts.map +1 -1
  70. package/dist/server/server.d.ts +1 -0
  71. package/dist/server/server.d.ts.map +1 -1
  72. package/dist/server/sprites.d.ts +18 -1
  73. package/dist/server/sprites.d.ts.map +1 -1
  74. package/dist/server/tenancy.d.ts +4 -0
  75. package/dist/server/tenancy.d.ts.map +1 -1
  76. package/dist/server/usage-meter.d.ts +53 -0
  77. package/dist/server/usage-meter.d.ts.map +1 -0
  78. package/dist/{server-IGBIIJSF.js → server-MB3OPSPI.js} +6 -1
  79. package/dist/{server-BOH7M4TT.js → server-ZVWGLLRF.js} +7 -2
  80. package/dist/sprites-KQGTGM6W.js +27 -0
  81. package/dist/{tenancy-S676GLID.js → tenancy-NBLLGCNJ.js} +1 -1
  82. package/dist/{tenancy-OP34NFFS.js → tenancy-POMWQP6M.js} +5 -3
  83. package/dist/vcs/index.js +3 -3
  84. package/dist/vcs/types.d.ts +2 -0
  85. package/dist/vcs/types.d.ts.map +1 -1
  86. package/package.json +17 -6
  87. package/dist/better-sqlite-backend-PII64VE6.js +0 -159
  88. package/dist/better-sqlite-backend-VUBVQ7SN.js +0 -209
  89. package/dist/better-sqlite-backend-Y3AQN65E.js +0 -159
  90. package/dist/better-sqlite-backend-Y3M7DXOX.js +0 -159
  91. package/dist/boot-middleware-FJDGVUM4.js +0 -9
  92. package/dist/boot-middleware-MLJUTLUM.js +0 -9
  93. package/dist/boot-middleware-ZZPDZNYR.js +0 -9
  94. package/dist/chunk-276LKLZR.js +0 -359
  95. package/dist/chunk-2CX5UCRV.js +0 -111
  96. package/dist/chunk-2ESYSVXG.js +0 -48
  97. package/dist/chunk-2I5JU73Y.js +0 -340
  98. package/dist/chunk-2UNSRRNB.js +0 -171
  99. package/dist/chunk-335UEHQR.js +0 -907
  100. package/dist/chunk-4CF2L46N.js +0 -29
  101. package/dist/chunk-5CINODKT.js +0 -41
  102. package/dist/chunk-5ESGWJ5L.js +0 -45
  103. package/dist/chunk-5FGLQGMF.js +0 -1676
  104. package/dist/chunk-5IQZFITY.js +0 -357
  105. package/dist/chunk-5JWFAQDW.js +0 -150
  106. package/dist/chunk-62UHTVU3.js +0 -141
  107. package/dist/chunk-66UJQT2I.js +0 -35
  108. package/dist/chunk-6RNNVOAS.js +0 -355
  109. package/dist/chunk-6X23PZ6H.js +0 -969
  110. package/dist/chunk-7C7LL6MB.js +0 -315
  111. package/dist/chunk-7F4HM3JG.js +0 -394
  112. package/dist/chunk-7KJ7T4D3.js +0 -910
  113. package/dist/chunk-7QQQNUB5.js +0 -92
  114. package/dist/chunk-7QWJBS72.js +0 -946
  115. package/dist/chunk-7R36OZK3.js +0 -957
  116. package/dist/chunk-7UPKCOHE.js +0 -946
  117. package/dist/chunk-A3BONW34.js +0 -35
  118. package/dist/chunk-AHMDVHBL.js +0 -141
  119. package/dist/chunk-AW6A4OZY.js +0 -171
  120. package/dist/chunk-BJ5EKCJ5.js +0 -458
  121. package/dist/chunk-BRGYDO7D.js +0 -223
  122. package/dist/chunk-C5KPSEDN.js +0 -359
  123. package/dist/chunk-CCTNYTUC.js +0 -940
  124. package/dist/chunk-CYQ2OVD2.js +0 -35
  125. package/dist/chunk-DDAK7YOE.js +0 -299
  126. package/dist/chunk-DRILKBY6.js +0 -965
  127. package/dist/chunk-DXE24HNN.js +0 -45
  128. package/dist/chunk-E7ICUNW7.js +0 -945
  129. package/dist/chunk-EAL2PUOE.js +0 -10022
  130. package/dist/chunk-ELT7MLZB.js +0 -109
  131. package/dist/chunk-EWEIRF6G.js +0 -171
  132. package/dist/chunk-F5VDGQJC.js +0 -120
  133. package/dist/chunk-FCPL3IEQ.js +0 -98
  134. package/dist/chunk-FDPKYSV7.js +0 -96
  135. package/dist/chunk-FES3TC24.js +0 -171
  136. package/dist/chunk-FOWKR5TW.js +0 -129
  137. package/dist/chunk-G3XIHPSQ.js +0 -361
  138. package/dist/chunk-GKJLYLVU.js +0 -359
  139. package/dist/chunk-GNXHXNVQ.js +0 -113
  140. package/dist/chunk-GSR6ILTM.js +0 -277
  141. package/dist/chunk-GWRIMRSX.js +0 -45
  142. package/dist/chunk-H72UW2HJ.js +0 -45
  143. package/dist/chunk-HGI74PXB.js +0 -7417
  144. package/dist/chunk-HGRA37LO.js +0 -145
  145. package/dist/chunk-HXSRQO3L.js +0 -145
  146. package/dist/chunk-IG2X2BVO.js +0 -373
  147. package/dist/chunk-IIJVDD54.js +0 -373
  148. package/dist/chunk-IX4BBOIT.js +0 -394
  149. package/dist/chunk-IXU4RMQM.js +0 -349
  150. package/dist/chunk-J6OUIION.js +0 -857
  151. package/dist/chunk-K46RNFDE.js +0 -171
  152. package/dist/chunk-KAGU2XMY.js +0 -359
  153. package/dist/chunk-KCVYJNVX.js +0 -394
  154. package/dist/chunk-KYLIQ3YI.js +0 -399
  155. package/dist/chunk-KZYJJIRN.js +0 -946
  156. package/dist/chunk-LFOX744K.js +0 -96
  157. package/dist/chunk-LHOVJEWR.js +0 -7403
  158. package/dist/chunk-LOPXTPF3.js +0 -120
  159. package/dist/chunk-LZR3VIFU.js +0 -907
  160. package/dist/chunk-MCKGQKYU.js +0 -15
  161. package/dist/chunk-MU6EOS6F.js +0 -0
  162. package/dist/chunk-MWRQ2TXT.js +0 -357
  163. package/dist/chunk-NO73OK2I.js +0 -102
  164. package/dist/chunk-NPE2YJHK.js +0 -394
  165. package/dist/chunk-NSDXU6QX.js +0 -2213
  166. package/dist/chunk-NXIRDSZ6.js +0 -145
  167. package/dist/chunk-NZWFNHCS.js +0 -407
  168. package/dist/chunk-OB4CMMX6.js +0 -260
  169. package/dist/chunk-OBKU74FU.js +0 -7411
  170. package/dist/chunk-OQNDWRDE.js +0 -145
  171. package/dist/chunk-OVWAJMB6.js +0 -394
  172. package/dist/chunk-PDHLBTTD.js +0 -45
  173. package/dist/chunk-PEQNRKLG.js +0 -210
  174. package/dist/chunk-QERIS7QY.js +0 -7403
  175. package/dist/chunk-QHA2DM3C.js +0 -373
  176. package/dist/chunk-QLM4HSYC.js +0 -45
  177. package/dist/chunk-S2OT3TQJ.js +0 -283
  178. package/dist/chunk-S5PHSN5K.js +0 -907
  179. package/dist/chunk-SIAA4J6H.js +0 -21
  180. package/dist/chunk-SQBNLUIA.js +0 -171
  181. package/dist/chunk-STLN6A6B.js +0 -355
  182. package/dist/chunk-U7HV7GU2.js +0 -17
  183. package/dist/chunk-UGZHOGRA.js +0 -39
  184. package/dist/chunk-UICF66FS.js +0 -359
  185. package/dist/chunk-UK3EQREE.js +0 -1078
  186. package/dist/chunk-UPKPURVY.js +0 -394
  187. package/dist/chunk-URC74VCN.js +0 -959
  188. package/dist/chunk-V3G7Q3QQ.js +0 -102
  189. package/dist/chunk-VUJ6SA55.js +0 -303
  190. package/dist/chunk-VUJQLIML.js +0 -141
  191. package/dist/chunk-VWKLKLYB.js +0 -267
  192. package/dist/chunk-VYC3RZMK.js +0 -277
  193. package/dist/chunk-WMERMSWI.js +0 -154
  194. package/dist/chunk-WMR777PO.js +0 -2213
  195. package/dist/chunk-X46IECAC.js +0 -517
  196. package/dist/chunk-XEN3OEYY.js +0 -2234
  197. package/dist/chunk-XZQ66K7A.js +0 -124
  198. package/dist/chunk-YY3GF7DH.js +0 -7411
  199. package/dist/chunk-ZE5R3H4C.js +0 -907
  200. package/dist/chunk-ZMN5LUB7.js +0 -7411
  201. package/dist/chunk-ZUV4MD5U.js +0 -94
  202. package/dist/config-KMY6RRK3.js +0 -19
  203. package/dist/config-VDMK2DUJ.js +0 -19
  204. package/dist/deploy-SO7AFK6L.js +0 -9
  205. package/dist/engine-7GXBM4IT.js +0 -7
  206. package/dist/engine-NSR6BIF7.js +0 -7
  207. package/dist/factory-2P64OC7M.js +0 -34
  208. package/dist/factory-YP4ZZK5K.js +0 -34
  209. package/dist/import-AJLYHFIA.js +0 -10
  210. package/dist/launch-explorer-AI6L2AWJ.js +0 -91
  211. package/dist/query-GJL3CVGN.js +0 -31
  212. package/dist/query-MBJSK3EB.js +0 -31
  213. package/dist/query-TJHEVSKL.js +0 -31
  214. package/dist/query-WUIKOHPE.js +0 -524
  215. package/dist/remote-manager-BLJZ6KF6.js +0 -224
  216. package/dist/remote-manager-BPYE46SI.js +0 -223
  217. package/dist/remote-manager-FMESEAFA.js +0 -224
  218. package/dist/remote-manager-K2WZ5RHY.js +0 -223
  219. package/dist/remote-manager-SG5PQKCH.js +0 -224
  220. package/dist/remote-manager-WGP6MIQZ.js +0 -224
  221. package/dist/sdk-3KBB3E6V.js +0 -16
  222. package/dist/sdk-4ZQO6UTU.js +0 -16
  223. package/dist/sdk-6JA6GV3G.js +0 -16
  224. package/dist/sdk-6VTP5UTZ.js +0 -16
  225. package/dist/sdk-7VS6TYCD.js +0 -16
  226. package/dist/sdk-HQ3FTLRT.js +0 -16
  227. package/dist/sdk-HZ7NU3XE.js +0 -15
  228. package/dist/sdk-KBQE2OXT.js +0 -16
  229. package/dist/sdk-MSCDZ7JU.js +0 -15
  230. package/dist/sdk-WNZOGO3S.js +0 -15
  231. package/dist/sdk-YLV33ZCW.js +0 -9
  232. package/dist/sdk-ZSUD2LLJ.js +0 -16
  233. package/dist/server-AFXFFBWA.js +0 -11
  234. package/dist/server-AGHC4VUL.js +0 -11
  235. package/dist/server-DBUY2KY5.js +0 -11
  236. package/dist/server-GWBQJPRG.js +0 -11
  237. package/dist/server-JZZFULVU.js +0 -11
  238. package/dist/server-L5XAF4M5.js +0 -11
  239. package/dist/server-NYFUHANA.js +0 -12
  240. package/dist/server-OABUB2LO.js +0 -12
  241. package/dist/server-P2CKZWWV.js +0 -12
  242. package/dist/sprites-XVSMQLSI.js +0 -15
  243. package/dist/sql-wasm-FORCZFHZ.js +0 -2148
  244. package/dist/sql-wasm-JZH76RLO.js +0 -2148
  245. package/dist/sqljs-backend-CJQOIQYE.js +0 -266
  246. package/dist/sqljs-backend-KWXBUDUO.js +0 -266
  247. package/dist/state-demo.bundle.js +0 -1033
  248. package/dist/tenancy-CBWYEVUB.js +0 -11
  249. package/dist/tenancy-FO6WVYFN.js +0 -13
  250. package/dist/tenancy-FWDBESMX.js +0 -14
  251. package/dist/tenancy-HGPIS5QA.js +0 -13
  252. package/dist/tenancy-HXFALA37.js +0 -14
  253. package/dist/tenancy-V7ARWNNV.js +0 -14
  254. package/dist/tenancy-ZDN4GXK5.js +0 -13
  255. package/dist/tenancy-ZT5VMY7B.js +0 -14
  256. package/dist/vm-config-YZRJ3KUB.js +0 -21
  257. /package/dist/{chunk-2BRTCEHB.js → chunk-PZ4XYZ4J.js} +0 -0
  258. /package/dist/{chunk-EO3J7GRP.js → chunk-WXSWA3MV.js} +0 -0
@@ -1,1676 +0,0 @@
1
- import {
2
- EAVStore
3
- } from "./chunk-IXU4RMQM.js";
4
- import {
5
- QueryEngine
6
- } from "./chunk-6CTA6MCE.js";
7
- import {
8
- __require
9
- } from "./chunk-SIAA4J6H.js";
10
-
11
- // src/server/tenancy.ts
12
- import { existsSync, mkdirSync } from "fs";
13
- import { join, resolve } from "path";
14
-
15
- // src/core/ontology/core-ontology.ts
16
- var VERSION = "1.0.0";
17
- function f(name, valueType, opts) {
18
- return { name, valueType, ...opts };
19
- }
20
- var thing = {
21
- "@id": "core:Thing",
22
- "@type": "trellis:Schema",
23
- version: VERSION,
24
- tier: "core",
25
- label: "Thing",
26
- icon: "lucide:box",
27
- fields: [
28
- f("id", "title", { required: true }),
29
- f("createdAt", "date"),
30
- f("updatedAt", "date"),
31
- f("createdBy", "relation", {
32
- relation: { targetSchema: "core:Member", cardinality: "one" }
33
- }),
34
- f("tags", "multi_select")
35
- ]
36
- };
37
- var record = {
38
- "@id": "core:Record",
39
- "@type": "trellis:Schema",
40
- version: VERSION,
41
- tier: "core",
42
- subClassOf: "core:Thing",
43
- label: "Record",
44
- icon: "lucide:file",
45
- fields: [
46
- f("title", "title", { required: true }),
47
- f("description", "rich_text"),
48
- f("status", "select"),
49
- f("tags", "multi_select")
50
- ]
51
- };
52
- var document = {
53
- "@id": "core:Document",
54
- "@type": "trellis:Schema",
55
- version: VERSION,
56
- tier: "core",
57
- subClassOf: "core:Record",
58
- label: "Document",
59
- icon: "lucide:file-text",
60
- fields: [
61
- f("content", "rich_text"),
62
- f("mimeType", "rich_text"),
63
- f("fileUrl", "url")
64
- ]
65
- };
66
- var event = {
67
- "@id": "core:Event",
68
- "@type": "trellis:Schema",
69
- version: VERSION,
70
- tier: "core",
71
- subClassOf: "core:Record",
72
- label: "Event",
73
- icon: "lucide:calendar",
74
- fields: [
75
- f("startDate", "date"),
76
- f("endDate", "date"),
77
- f("location", "rich_text"),
78
- f("allDay", "checkbox")
79
- ]
80
- };
81
- var collection = {
82
- "@id": "core:Collection",
83
- "@type": "trellis:Schema",
84
- version: VERSION,
85
- tier: "core",
86
- subClassOf: "core:Thing",
87
- label: "Collection",
88
- icon: "lucide:database",
89
- fields: [
90
- f("title", "title", { required: true }),
91
- f("description", "rich_text"),
92
- f("icon", "rich_text"),
93
- f("schema", "rich_text"),
94
- f("recordType", "relation", {
95
- relation: { targetSchema: "core:Record", cardinality: "one" }
96
- })
97
- ]
98
- };
99
- var tag = {
100
- "@id": "core:Tag",
101
- "@type": "trellis:Schema",
102
- version: VERSION,
103
- tier: "core",
104
- subClassOf: "core:Thing",
105
- label: "Tag",
106
- icon: "lucide:tag",
107
- fields: [
108
- f("name", "title", { required: true }),
109
- f("slug", "rich_text"),
110
- f("color", "rich_text"),
111
- f("icon", "rich_text"),
112
- f("parentTag", "relation", {
113
- relation: { targetSchema: "core:Tag", cardinality: "one" }
114
- })
115
- ]
116
- };
117
- var workspace = {
118
- "@id": "core:Workspace",
119
- "@type": "trellis:Schema",
120
- version: VERSION,
121
- tier: "core",
122
- subClassOf: "core:Thing",
123
- label: "Workspace",
124
- icon: "lucide:building-2",
125
- fields: [
126
- f("name", "title", { required: true }),
127
- f("slug", "rich_text"),
128
- f("avatar", "files"),
129
- f("plan", "select")
130
- ]
131
- };
132
- var app = {
133
- "@id": "core:App",
134
- "@type": "trellis:Schema",
135
- version: VERSION,
136
- tier: "core",
137
- subClassOf: "core:Thing",
138
- label: "App",
139
- icon: "lucide:layout-grid",
140
- fields: [
141
- f("name", "title", { required: true }),
142
- f("slug", "rich_text"),
143
- f("icon", "rich_text"),
144
- f("color", "rich_text"),
145
- f("description", "rich_text"),
146
- f("ontologies", "multi_select")
147
- ]
148
- };
149
- var member = {
150
- "@id": "core:Member",
151
- "@type": "trellis:Schema",
152
- version: VERSION,
153
- tier: "core",
154
- subClassOf: "core:Thing",
155
- label: "Member",
156
- icon: "lucide:user",
157
- fields: [
158
- f("name", "title", { required: true }),
159
- f("email", "email"),
160
- f("avatar", "files"),
161
- f("role", "select", {
162
- required: true,
163
- selectOptions: ["owner", "admin", "member", "guest"],
164
- defaultValue: "member"
165
- }),
166
- f("status", "select", {
167
- required: true,
168
- selectOptions: ["pending", "active", "suspended"],
169
- defaultValue: "pending"
170
- }),
171
- f("orgId", "relation", {
172
- required: true,
173
- relation: { targetSchema: "core:Workspace", cardinality: "one" }
174
- }),
175
- f("userId", "relation", {
176
- relation: { targetSchema: "core:Person", cardinality: "one" }
177
- }),
178
- f("invitedAt", "date"),
179
- f("joinedAt", "date")
180
- ]
181
- };
182
- var notification = {
183
- "@id": "core:Notification",
184
- "@type": "trellis:Schema",
185
- version: VERSION,
186
- tier: "core",
187
- subClassOf: "core:Thing",
188
- label: "Notification",
189
- icon: "lucide:bell",
190
- fields: [
191
- f("recipientId", "relation", {
192
- required: true,
193
- relation: { targetSchema: "core:Person", cardinality: "one" }
194
- }),
195
- f("orgId", "relation", {
196
- relation: { targetSchema: "core:Workspace", cardinality: "one" }
197
- }),
198
- f("orgName", "rich_text"),
199
- f("type", "select", {
200
- required: true,
201
- selectOptions: [
202
- "invite_accepted",
203
- "invite_sent",
204
- "member_joined",
205
- "member_removed",
206
- "role_changed",
207
- "mention",
208
- "comment",
209
- "entity_updated",
210
- "system"
211
- ]
212
- }),
213
- f("title", "title", { required: true }),
214
- f("message", "rich_text", { required: true }),
215
- f("actionUrl", "url"),
216
- f("icon", "rich_text"),
217
- f("variant", "select", {
218
- selectOptions: ["default", "success", "warning", "destructive", "info"]
219
- }),
220
- f("isRead", "checkbox", { defaultValue: false }),
221
- f("actorId", "relation", {
222
- relation: { targetSchema: "core:Person", cardinality: "one" }
223
- }),
224
- f("actorName", "rich_text"),
225
- f("metadata", "rich_text"),
226
- f("createdAt", "date", { required: true })
227
- ]
228
- };
229
- var share = {
230
- "@id": "core:Share",
231
- "@type": "trellis:Schema",
232
- version: VERSION,
233
- tier: "core",
234
- subClassOf: "core:Thing",
235
- label: "Share",
236
- icon: "lucide:share-2",
237
- fields: [
238
- f("entityId", "relation", { required: true }),
239
- f("entityType", "select", { selectOptions: ["entity", "collection"] }),
240
- f("userId", "relation", {
241
- required: true,
242
- relation: { targetSchema: "core:Person", cardinality: "one" }
243
- }),
244
- f("orgId", "relation", {
245
- relation: { targetSchema: "core:Workspace", cardinality: "one" }
246
- }),
247
- f("permission", "select", {
248
- required: true,
249
- selectOptions: ["view", "comment", "edit"],
250
- defaultValue: "view"
251
- }),
252
- f("sharedBy", "relation", {
253
- relation: { targetSchema: "core:Person", cardinality: "one" }
254
- }),
255
- f("createdAt", "date", { required: true })
256
- ]
257
- };
258
- var person = {
259
- "@id": "core:Person",
260
- "@type": "trellis:Schema",
261
- version: VERSION,
262
- tier: "core",
263
- subClassOf: "core:Thing",
264
- label: "Person",
265
- icon: "lucide:user",
266
- fields: [f("name", "title", { required: true })]
267
- };
268
- var workflow = {
269
- "@id": "core:Workflow",
270
- "@type": "trellis:Schema",
271
- version: VERSION,
272
- tier: "core",
273
- subClassOf: "core:Thing",
274
- label: "Workflow",
275
- icon: "lucide:git-branch",
276
- fields: [
277
- f("name", "title", { required: true }),
278
- f("trigger", "rich_text"),
279
- f("steps", "multi_select"),
280
- f("active", "checkbox")
281
- ]
282
- };
283
- var CORE_ONTOLOGY = [
284
- thing,
285
- record,
286
- document,
287
- event,
288
- collection,
289
- tag,
290
- workspace,
291
- app,
292
- member,
293
- notification,
294
- share,
295
- person,
296
- workflow
297
- ];
298
-
299
- // src/core/kernel/trellis-kernel.ts
300
- async function hashOp(kind, timestamp, agentId, previousHash, payload) {
301
- const data = `${kind}|${timestamp}|${agentId}|${previousHash ?? ""}|${payload}`;
302
- const buf = new TextEncoder().encode(data);
303
- const hashBuf = await crypto.subtle.digest("SHA-256", buf);
304
- const hex = Array.from(new Uint8Array(hashBuf)).map((b) => b.toString(16).padStart(2, "0")).join("");
305
- return `trellis:op:${hex}`;
306
- }
307
- var TrellisKernel = class {
308
- store;
309
- backend;
310
- middleware;
311
- agentId;
312
- snapshotThreshold;
313
- opsSinceSnapshot = 0;
314
- _booted = false;
315
- ontologies = /* @__PURE__ */ new Map();
316
- workspaceConfig = null;
317
- autoReplay = true;
318
- constructor(config) {
319
- this.store = new EAVStore();
320
- this.backend = config.backend;
321
- this.agentId = config.agentId;
322
- this.middleware = config.middleware ?? [];
323
- this.snapshotThreshold = config.snapshotThreshold ?? 0;
324
- this.autoReplay = config.autoReplay ?? true;
325
- for (const schema of CORE_ONTOLOGY) {
326
- this.ontologies.set(schema["@id"], schema);
327
- }
328
- }
329
- // -------------------------------------------------------------------------
330
- // Lifecycle
331
- // -------------------------------------------------------------------------
332
- /**
333
- * Initialize the backend and replay persisted state.
334
- * Loads latest snapshot if available, then replays ops after it.
335
- */
336
- boot() {
337
- this.backend.init();
338
- if (!this.autoReplay) {
339
- this._booted = true;
340
- return { opsReplayed: 0, fromSnapshot: false };
341
- }
342
- let opsReplayed = 0;
343
- let fromSnapshot = false;
344
- const snapshot = this.backend.loadLatestSnapshot();
345
- if (snapshot) {
346
- this.store.restore(snapshot.data);
347
- fromSnapshot = true;
348
- const recentOps = this.backend.readAfter(snapshot.lastOpHash);
349
- for (const op of recentOps) {
350
- this._replayOp(op);
351
- opsReplayed++;
352
- }
353
- } else {
354
- const allOps = this.backend.readAll();
355
- for (const op of allOps) {
356
- this._replayOp(op);
357
- opsReplayed++;
358
- }
359
- }
360
- this._booted = true;
361
- return { opsReplayed, fromSnapshot };
362
- }
363
- /**
364
- * Close the backend connection.
365
- */
366
- close() {
367
- this.backend.close?.();
368
- this._booted = false;
369
- }
370
- isBooted() {
371
- return this._booted;
372
- }
373
- // -------------------------------------------------------------------------
374
- // Mutations
375
- // -------------------------------------------------------------------------
376
- /**
377
- * Apply a mutation to the graph. Creates an op, runs it through middleware,
378
- * decomposes into EAV primitives, persists, and returns the result.
379
- */
380
- async mutate(kind, payload, ctx) {
381
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
382
- const lastOp = this.backend.getLastOp();
383
- const agentId = ctx?.agentId ?? this.agentId;
384
- const payloadStr = JSON.stringify(payload);
385
- const hash = await hashOp(
386
- kind,
387
- timestamp,
388
- agentId,
389
- lastOp?.hash,
390
- payloadStr
391
- );
392
- const op = {
393
- hash,
394
- kind,
395
- timestamp,
396
- agentId,
397
- previousHash: lastOp?.hash,
398
- facts: [...payload.facts ?? []],
399
- links: [...payload.links ?? []],
400
- deleteFacts: payload.deleteFacts?.length ? [...payload.deleteFacts] : void 0,
401
- deleteLinks: payload.deleteLinks?.length ? [...payload.deleteLinks] : void 0
402
- };
403
- const extOp = op;
404
- if (payload.meta) {
405
- for (const [k, v] of Object.entries(payload.meta)) {
406
- extOp[k] = v;
407
- }
408
- }
409
- const mwCtx = { agentId, ...ctx };
410
- await this._runMiddleware(op, mwCtx);
411
- let factsAdded = 0;
412
- let factsDeleted = 0;
413
- let linksAdded = 0;
414
- let linksDeleted = 0;
415
- if (payload.deleteFacts && payload.deleteFacts.length > 0) {
416
- this.store.deleteFacts(payload.deleteFacts);
417
- factsDeleted = payload.deleteFacts.length;
418
- }
419
- if (payload.deleteLinks && payload.deleteLinks.length > 0) {
420
- this.store.deleteLinks(payload.deleteLinks);
421
- linksDeleted = payload.deleteLinks.length;
422
- }
423
- if (payload.facts && payload.facts.length > 0) {
424
- this.store.addFacts(payload.facts);
425
- factsAdded = payload.facts.length;
426
- }
427
- if (payload.links && payload.links.length > 0) {
428
- this.store.addLinks(payload.links);
429
- linksAdded = payload.links.length;
430
- }
431
- this.backend.append(op);
432
- this.opsSinceSnapshot++;
433
- if (this.snapshotThreshold > 0 && this.opsSinceSnapshot >= this.snapshotThreshold) {
434
- this.checkpoint();
435
- }
436
- return {
437
- op,
438
- factsDelta: { added: factsAdded, deleted: factsDeleted },
439
- linksDelta: { added: linksAdded, deleted: linksDeleted }
440
- };
441
- }
442
- /**
443
- * Create a snapshot of the current store state.
444
- */
445
- checkpoint() {
446
- const lastOp = this.backend.getLastOp();
447
- if (!lastOp) return;
448
- this.backend.saveSnapshot(lastOp.hash, this.store.snapshot());
449
- this.opsSinceSnapshot = 0;
450
- }
451
- // -------------------------------------------------------------------------
452
- // Queries
453
- // -------------------------------------------------------------------------
454
- /**
455
- * Get the underlying EAV store for direct queries.
456
- */
457
- getStore() {
458
- return this.store;
459
- }
460
- /**
461
- * Get the persistence backend.
462
- */
463
- getBackend() {
464
- return this.backend;
465
- }
466
- /**
467
- * Get the agent ID.
468
- */
469
- getAgentId() {
470
- return this.agentId;
471
- }
472
- /**
473
- * Read all persisted ops.
474
- */
475
- readAllOps() {
476
- return this.backend.readAll();
477
- }
478
- /**
479
- * Get the last persisted op.
480
- */
481
- getLastOp() {
482
- return this.backend.getLastOp();
483
- }
484
- /**
485
- * Create a QueryEngine bound to this kernel's store.
486
- */
487
- createQueryEngine() {
488
- return new QueryEngine(this.store);
489
- }
490
- /**
491
- * Execute an EQL-S query, routing through middleware handleQuery hooks.
492
- * If no middleware intercepts, the query runs directly against the store.
493
- */
494
- async query(q) {
495
- const engine = new QueryEngine(this.store);
496
- const ctx = {
497
- agentId: this.agentId,
498
- store: this.store
499
- };
500
- const chain = this.middleware.filter((m) => m.handleQuery);
501
- if (chain.length === 0) {
502
- return engine.execute(q);
503
- }
504
- let result;
505
- let idx = 0;
506
- const next = (query, context) => {
507
- if (idx < chain.length) {
508
- const mw = chain[idx++];
509
- return mw.handleQuery(query, context, next);
510
- }
511
- result = engine.execute(query);
512
- return result;
513
- };
514
- result = next(q, ctx);
515
- return result;
516
- }
517
- /**
518
- * Time-travel: reconstruct the store state at a specific op hash.
519
- * Returns a new EAVStore with state replayed up to (and including) that op.
520
- */
521
- timeTravel(opHash) {
522
- const ops = this.backend.readUntil(opHash);
523
- const snapshot = new EAVStore();
524
- for (const op of ops) {
525
- if (op.deleteFacts && op.deleteFacts.length > 0) {
526
- snapshot.deleteFacts(op.deleteFacts);
527
- }
528
- if (op.deleteLinks && op.deleteLinks.length > 0) {
529
- snapshot.deleteLinks(op.deleteLinks);
530
- }
531
- if (op.facts && op.facts.length > 0) {
532
- snapshot.addFacts(op.facts);
533
- }
534
- if (op.links && op.links.length > 0) {
535
- snapshot.addLinks(op.links);
536
- }
537
- }
538
- return snapshot;
539
- }
540
- // -------------------------------------------------------------------------
541
- // Entity CRUD (high-level graph operations)
542
- // -------------------------------------------------------------------------
543
- /**
544
- * Create a new entity with the given type and attributes.
545
- * Returns the entity ID.
546
- */
547
- async createEntity(entityId, type, attributes = {}, links) {
548
- const facts = [
549
- { e: entityId, a: "type", v: type },
550
- { e: entityId, a: "createdAt", v: (/* @__PURE__ */ new Date()).toISOString() }
551
- ];
552
- for (const [attr, value] of Object.entries(attributes)) {
553
- facts.push({ e: entityId, a: attr, v: value });
554
- }
555
- const linkRecords = (links ?? []).map((l) => ({
556
- e1: entityId,
557
- a: l.attribute,
558
- e2: l.targetEntityId
559
- }));
560
- return this.mutate("addFacts", {
561
- facts,
562
- links: linkRecords.length > 0 ? linkRecords : void 0
563
- });
564
- }
565
- /**
566
- * Get an entity by ID, returning all its facts and links.
567
- */
568
- getEntity(entityId) {
569
- const facts = this.store.getFactsByEntity(entityId);
570
- if (facts.length === 0) return null;
571
- const typeFact = facts.find((f2) => f2.a === "type");
572
- return {
573
- id: entityId,
574
- type: typeFact?.v ?? "unknown",
575
- facts,
576
- links: this.store.getLinksByEntity(entityId)
577
- };
578
- }
579
- /**
580
- * Update an entity's attributes. Deletes old values and adds new ones.
581
- */
582
- async updateEntity(entityId, updates) {
583
- const existingFacts = this.store.getFactsByEntity(entityId);
584
- const deleteFacts = [];
585
- const addFacts = [];
586
- for (const [attr, newValue] of Object.entries(updates)) {
587
- const existing = existingFacts.filter((f2) => f2.a === attr);
588
- deleteFacts.push(...existing);
589
- addFacts.push({ e: entityId, a: attr, v: newValue });
590
- }
591
- const updatedAtFacts = existingFacts.filter((f2) => f2.a === "updatedAt");
592
- deleteFacts.push(...updatedAtFacts);
593
- addFacts.push({ e: entityId, a: "updatedAt", v: (/* @__PURE__ */ new Date()).toISOString() });
594
- return this.mutate("addFacts", {
595
- facts: addFacts,
596
- deleteFacts
597
- });
598
- }
599
- /**
600
- * Delete an entity and all its facts and links.
601
- */
602
- async deleteEntity(entityId) {
603
- const facts = this.store.getFactsByEntity(entityId);
604
- const links = this.store.getLinksByEntity(entityId);
605
- return this.mutate("deleteFacts", {
606
- deleteFacts: facts,
607
- deleteLinks: links
608
- });
609
- }
610
- /**
611
- * List entities by type, with optional attribute filters.
612
- */
613
- listEntities(type, filters) {
614
- let entityIds;
615
- if (type) {
616
- const typeFacts = this.store.getFactsByValue("type", type);
617
- entityIds = new Set(typeFacts.map((f2) => f2.e));
618
- } else {
619
- const allTypeFacts = this.store.getFactsByAttribute("type");
620
- entityIds = new Set(allTypeFacts.map((f2) => f2.e));
621
- }
622
- if (filters) {
623
- for (const [attr, value] of Object.entries(filters)) {
624
- const matchingFacts = this.store.getFactsByValue(attr, value);
625
- const matchingEntities = new Set(matchingFacts.map((f2) => f2.e));
626
- for (const id of entityIds) {
627
- if (!matchingEntities.has(id)) {
628
- entityIds.delete(id);
629
- }
630
- }
631
- }
632
- }
633
- return Array.from(entityIds).map((id) => this.getEntity(id)).filter(Boolean);
634
- }
635
- /**
636
- * Add a link between two entities.
637
- */
638
- async addLink(sourceId, attribute, targetId) {
639
- return this.mutate("addLinks", {
640
- links: [{ e1: sourceId, a: attribute, e2: targetId }]
641
- });
642
- }
643
- /**
644
- * Remove a link between two entities.
645
- */
646
- async removeLink(sourceId, attribute, targetId) {
647
- return this.mutate("deleteLinks", {
648
- deleteLinks: [{ e1: sourceId, a: attribute, e2: targetId }]
649
- });
650
- }
651
- /**
652
- * Add a fact to an entity.
653
- */
654
- async addFact(entityId, attribute, value) {
655
- return this.mutate("addFacts", {
656
- facts: [{ e: entityId, a: attribute, v: value }]
657
- });
658
- }
659
- /**
660
- * Remove a fact from an entity.
661
- */
662
- async removeFact(entityId, attribute, value) {
663
- return this.mutate("deleteFacts", {
664
- deleteFacts: [{ e: entityId, a: attribute, v: value }]
665
- });
666
- }
667
- // -------------------------------------------------------------------------
668
- // Ontology CRUD
669
- // -------------------------------------------------------------------------
670
- /**
671
- * Get an ontology schema by ID.
672
- */
673
- getOntology(id) {
674
- return this.ontologies.get(id);
675
- }
676
- /**
677
- * List all ontologies.
678
- */
679
- listOntologies() {
680
- return Array.from(this.ontologies.values());
681
- }
682
- /**
683
- * Create a new ontology schema.
684
- */
685
- createOntology(schema) {
686
- const tier = schema.tier ?? "user";
687
- if (tier === "core") {
688
- throw new Error("Cannot modify core ontologies");
689
- }
690
- if (this.ontologies.has(schema["@id"])) {
691
- throw new Error(`Ontology ${schema["@id"]} already exists`);
692
- }
693
- this.ontologies.set(schema["@id"], schema);
694
- const fact = {
695
- e: schema["@id"],
696
- a: "schema",
697
- v: JSON.stringify(schema)
698
- };
699
- this.store.addFacts([fact]);
700
- }
701
- /**
702
- * Update an existing ontology schema.
703
- */
704
- updateOntology(id, updates) {
705
- const existing = this.ontologies.get(id);
706
- if (!existing) {
707
- throw new Error(`Ontology ${id} not found`);
708
- }
709
- const tier = existing.tier ?? "user";
710
- if (tier === "core") {
711
- throw new Error("Cannot modify core ontologies");
712
- }
713
- const updated = { ...existing, ...updates };
714
- this.ontologies.set(id, updated);
715
- const existingFacts = this.store.getFactsByEntity(id);
716
- const schemaFacts = existingFacts.filter((f2) => f2.a === "schema");
717
- const deleteFacts = [...schemaFacts];
718
- const addFacts = [
719
- {
720
- e: id,
721
- a: "schema",
722
- v: JSON.stringify(updated)
723
- }
724
- ];
725
- this.store.deleteFacts(deleteFacts);
726
- this.store.addFacts(addFacts);
727
- }
728
- /**
729
- * Delete an ontology schema.
730
- */
731
- deleteOntology(id) {
732
- const existing = this.ontologies.get(id);
733
- if (!existing) {
734
- throw new Error(`Ontology ${id} not found`);
735
- }
736
- const tier = existing.tier ?? "user";
737
- if (tier === "core") {
738
- throw new Error("Cannot delete core ontologies");
739
- }
740
- this.ontologies.delete(id);
741
- const facts = this.store.getFactsByEntity(id);
742
- this.store.deleteFacts(facts);
743
- }
744
- // -------------------------------------------------------------------------
745
- // Workspace
746
- // -------------------------------------------------------------------------
747
- /**
748
- * Boot the kernel with a workspace configuration.
749
- * Loads ontologies, projections, and seed data.
750
- */
751
- bootWorkspace(config) {
752
- this.workspaceConfig = config;
753
- if (config.workspace.ontologies) {
754
- for (const [id, schema] of Object.entries(config.workspace.ontologies)) {
755
- if (!this.ontologies.has(id)) {
756
- this.ontologies.set(id, schema);
757
- }
758
- }
759
- }
760
- if (config.workspace.graph?.nodes) {
761
- for (const node of config.workspace.graph.nodes) {
762
- const n = node;
763
- if (n.id && n.type) {
764
- const facts = [
765
- { e: String(n.id), a: "type", v: String(n.type) }
766
- ];
767
- for (const [key, value] of Object.entries(n)) {
768
- if (key !== "id" && key !== "type") {
769
- facts.push({ e: String(n.id), a: key, v: value });
770
- }
771
- }
772
- this.store.addFacts(facts);
773
- }
774
- }
775
- }
776
- if (config.workspace.graph?.edges) {
777
- for (const edge of config.workspace.graph.edges) {
778
- const e = edge;
779
- if (e.source && e.target && e.relation) {
780
- this.store.addLinks([
781
- {
782
- e1: String(e.source),
783
- a: String(e.relation),
784
- e2: String(e.target)
785
- }
786
- ]);
787
- }
788
- }
789
- }
790
- this.boot();
791
- }
792
- /**
793
- * Export the current workspace configuration.
794
- */
795
- exportWorkspace() {
796
- const ontologies = {};
797
- for (const [id, schema] of this.ontologies) {
798
- if (schema.tier !== "core") {
799
- ontologies[id] = schema;
800
- }
801
- }
802
- const allFacts = this.store.getAllFacts();
803
- const nodes = [];
804
- const entityIds = new Set(allFacts.map((f2) => f2.e));
805
- for (const id of entityIds) {
806
- const facts = this.store.getFactsByEntity(id);
807
- const typeFact = facts.find((f2) => f2.a === "type");
808
- const node = { id };
809
- if (typeFact) {
810
- node.type = typeFact.v;
811
- }
812
- for (const fact of facts) {
813
- if (fact.a !== "type") {
814
- node[fact.a] = fact.v;
815
- }
816
- }
817
- nodes.push(node);
818
- }
819
- const allLinks = this.store.getAllLinks();
820
- const edges = allLinks.map((l) => ({
821
- source: l.e1,
822
- relation: l.a,
823
- target: l.e2
824
- }));
825
- return {
826
- workspace: {
827
- name: this.workspaceConfig?.workspace.name,
828
- description: this.workspaceConfig?.workspace.description,
829
- ontologies: Object.keys(ontologies).length > 0 ? ontologies : void 0,
830
- graph: { nodes, edges },
831
- projections: this.workspaceConfig?.workspace.projections,
832
- routes: this.workspaceConfig?.workspace.routes,
833
- app: this.workspaceConfig?.workspace.app
834
- }
835
- };
836
- }
837
- // -------------------------------------------------------------------------
838
- // TQL Compatibility Aliases
839
- // -------------------------------------------------------------------------
840
- /**
841
- * Create a node (alias for createEntity with schema validation).
842
- */
843
- async createNode(id, data, type, _ctx) {
844
- return this.createEntity(id, type, data);
845
- }
846
- /**
847
- * Update a node (alias for updateEntity with schema validation).
848
- */
849
- async updateNode(id, data, type, _ctx) {
850
- return this.updateEntity(id, data);
851
- }
852
- /**
853
- * Delete a node (alias for deleteEntity).
854
- */
855
- async deleteNode(id, _ctx) {
856
- return this.deleteEntity(id);
857
- }
858
- /**
859
- * Link two nodes (alias for addLink).
860
- */
861
- async link(e1, a, e2, _ctx) {
862
- return this.addLink(e1, a, e2);
863
- }
864
- /**
865
- * Unlink two nodes (alias for removeLink).
866
- */
867
- async unlink(e1, a, e2, _ctx) {
868
- return this.removeLink(e1, a, e2);
869
- }
870
- // -------------------------------------------------------------------------
871
- // Middleware
872
- // -------------------------------------------------------------------------
873
- addMiddleware(mw) {
874
- this.middleware.push(mw);
875
- }
876
- removeMiddleware(name) {
877
- this.middleware = this.middleware.filter((m) => m.name !== name);
878
- }
879
- // -------------------------------------------------------------------------
880
- // Internal
881
- // -------------------------------------------------------------------------
882
- async _runMiddleware(op, ctx) {
883
- const chain = [...this.middleware];
884
- let idx = 0;
885
- const next = async (op2, ctx2) => {
886
- const mw = chain[idx++];
887
- if (mw?.handleOp) {
888
- await mw.handleOp(op2, ctx2, next);
889
- }
890
- };
891
- if (chain.length > 0) {
892
- await next(op, ctx);
893
- }
894
- }
895
- _replayOp(op) {
896
- if (op.deleteFacts && op.deleteFacts.length > 0) {
897
- this.store.deleteFacts(op.deleteFacts);
898
- }
899
- if (op.deleteLinks && op.deleteLinks.length > 0) {
900
- this.store.deleteLinks(op.deleteLinks);
901
- }
902
- if (op.facts && op.facts.length > 0) {
903
- this.store.addFacts(op.facts);
904
- }
905
- if (op.links && op.links.length > 0) {
906
- this.store.addLinks(op.links);
907
- }
908
- }
909
- };
910
-
911
- // src/core/computation/expr-evaluator.ts
912
- var ExprEvaluator = class {
913
- functions;
914
- constructor() {
915
- this.functions = /* @__PURE__ */ new Map([
916
- ["$if", this.if.bind(this)],
917
- ["$round", this.round.bind(this)],
918
- ["$concat", this.concat.bind(this)],
919
- ["$len", this.len.bind(this)],
920
- ["$lower", this.lower.bind(this)],
921
- ["$upper", this.upper.bind(this)],
922
- ["$trim", this.trim.bind(this)],
923
- ["$now", this.now.bind(this)],
924
- ["$uuid", this.uuid.bind(this)],
925
- ["$add", this.add.bind(this)],
926
- ["$sub", this.sub.bind(this)],
927
- ["$mul", this.mul.bind(this)],
928
- ["$div", this.div.bind(this)],
929
- ["$mod", this.mod.bind(this)],
930
- ["$eq", this.eq.bind(this)],
931
- ["$ne", this.ne.bind(this)],
932
- ["$gt", this.gt.bind(this)],
933
- ["$gte", this.gte.bind(this)],
934
- ["$lt", this.lt.bind(this)],
935
- ["$lte", this.lte.bind(this)],
936
- ["$and", this.and.bind(this)],
937
- ["$or", this.or.bind(this)],
938
- ["$not", this.not.bind(this)],
939
- ["$coalesce", this.coalesce.bind(this)],
940
- ["$contains", this.contains.bind(this)],
941
- ["$startsWith", this.startsWith.bind(this)],
942
- ["$endsWith", this.endsWith.bind(this)]
943
- ]);
944
- }
945
- /**
946
- * Evaluate an expression string against a context.
947
- */
948
- eval(expr, context) {
949
- const trimmed = expr.trim();
950
- const fnMatch = trimmed.match(/^(\$\w+)\((.*)\)$/s);
951
- if (fnMatch) {
952
- const fnName = fnMatch[1];
953
- const argsStr = fnMatch[2];
954
- const fn = this.functions.get(fnName);
955
- if (!fn) {
956
- throw new Error(`Unknown function: ${fnName}`);
957
- }
958
- return this.evalFunction(fn, argsStr, context);
959
- }
960
- if (trimmed.startsWith("$")) {
961
- const field = trimmed.slice(1);
962
- return context[field];
963
- }
964
- if (trimmed === "true") return true;
965
- if (trimmed === "false") return false;
966
- if (trimmed === "null") return null;
967
- const num = Number(trimmed);
968
- if (!isNaN(num) && trimmed !== "") return num;
969
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
970
- return trimmed.slice(1, -1);
971
- }
972
- return trimmed;
973
- }
974
- evalFunction(fn, argsStr, context) {
975
- const args = this.parseArgs(argsStr, context);
976
- return fn(...args);
977
- }
978
- parseArgs(argsStr, context) {
979
- const args = [];
980
- let depth = 0;
981
- let current = "";
982
- for (let i = 0; i < argsStr.length; i++) {
983
- const char = argsStr[i];
984
- if (char === "(" || char === "[" || char === "{") depth++;
985
- else if (char === ")" || char === "]" || char === "}") depth--;
986
- else if (char === "," && depth === 0) {
987
- args.push(this.eval(current.trim(), context));
988
- current = "";
989
- continue;
990
- }
991
- current += char;
992
- }
993
- if (current.trim()) {
994
- args.push(this.eval(current.trim(), context));
995
- }
996
- return args;
997
- }
998
- // Built-in functions
999
- if(cond, trueVal, falseVal) {
1000
- return cond ? trueVal : falseVal;
1001
- }
1002
- round(value, decimals = 0) {
1003
- const n = Number(value);
1004
- const factor = Math.pow(10, Number(decimals));
1005
- return Math.round(n * factor) / factor;
1006
- }
1007
- concat(...args) {
1008
- return args.map((a) => String(a ?? "")).join("");
1009
- }
1010
- len(value) {
1011
- if (typeof value === "string") return value.length;
1012
- if (Array.isArray(value)) return value.length;
1013
- return 0;
1014
- }
1015
- lower(value) {
1016
- return String(value ?? "").toLowerCase();
1017
- }
1018
- upper(value) {
1019
- return String(value ?? "").toUpperCase();
1020
- }
1021
- trim(value) {
1022
- return String(value ?? "").trim();
1023
- }
1024
- now() {
1025
- return (/* @__PURE__ */ new Date()).toISOString();
1026
- }
1027
- uuid() {
1028
- return crypto.randomUUID();
1029
- }
1030
- add(...args) {
1031
- return args.reduce((sum, a) => sum + Number(a), 0);
1032
- }
1033
- sub(a, b) {
1034
- return Number(a) - Number(b);
1035
- }
1036
- mul(...args) {
1037
- return args.reduce((prod, a) => prod * Number(a), 1);
1038
- }
1039
- div(a, b) {
1040
- return Number(a) / Number(b);
1041
- }
1042
- mod(a, b) {
1043
- return Number(a) % Number(b);
1044
- }
1045
- eq(a, b) {
1046
- return a === b;
1047
- }
1048
- ne(a, b) {
1049
- return a !== b;
1050
- }
1051
- gt(a, b) {
1052
- return Number(a) > Number(b);
1053
- }
1054
- gte(a, b) {
1055
- return Number(a) >= Number(b);
1056
- }
1057
- lt(a, b) {
1058
- return Number(a) < Number(b);
1059
- }
1060
- lte(a, b) {
1061
- return Number(a) <= Number(b);
1062
- }
1063
- and(...args) {
1064
- return args.every(Boolean);
1065
- }
1066
- or(...args) {
1067
- return args.some(Boolean);
1068
- }
1069
- not(value) {
1070
- return !value;
1071
- }
1072
- coalesce(...args) {
1073
- for (const arg of args) {
1074
- if (arg !== null && arg !== void 0) return arg;
1075
- }
1076
- return null;
1077
- }
1078
- contains(haystack, needle) {
1079
- return String(haystack ?? "").includes(String(needle ?? ""));
1080
- }
1081
- startsWith(str, prefix) {
1082
- return String(str ?? "").startsWith(String(prefix ?? ""));
1083
- }
1084
- endsWith(str, suffix) {
1085
- return String(str ?? "").endsWith(String(suffix ?? ""));
1086
- }
1087
- };
1088
- function evalExpr(expr, context) {
1089
- const result = new ExprEvaluator().eval(expr, context);
1090
- if (result === null || result === void 0) return "";
1091
- if (typeof result === "boolean") return result ? "true" : "false";
1092
- if (typeof result === "number") return result;
1093
- if (typeof result === "string") return result;
1094
- if (typeof result === "object") return JSON.stringify(result);
1095
- return String(result);
1096
- }
1097
-
1098
- // src/core/computation/rollup.ts
1099
- function collectRollupRelatedIds(rollup, ctx) {
1100
- if (rollup.joinEntity) {
1101
- const { type, foreignKey } = rollup.joinEntity;
1102
- const facts = ctx.store.getFactsByAttribute(foreignKey);
1103
- const ids = [];
1104
- for (const fact of facts) {
1105
- if (fact.v !== ctx.entityId) continue;
1106
- const typeFacts = ctx.store.getFactsByEntity(fact.e);
1107
- const entityType = typeFacts.find((f2) => f2.a === "type")?.v;
1108
- if (entityType === type) ids.push(fact.e);
1109
- }
1110
- return ids;
1111
- }
1112
- const linkAttr = resolveLinkAttribute(rollup.relationProperty, ctx.schema);
1113
- const links = ctx.store.getLinksByEntityAndAttribute(ctx.entityId, linkAttr);
1114
- if (links.length > 0) return links.map((l) => l.e2);
1115
- return [];
1116
- }
1117
- function resolveLinkAttribute(relationProperty, schema) {
1118
- const field = schema?.fields.find((f2) => f2.name === relationProperty);
1119
- if (field?.valueType === "relation") return relationProperty;
1120
- return relationProperty;
1121
- }
1122
- function readTargetValue(store, entityId, targetProperty) {
1123
- if (targetProperty === "id") return entityId;
1124
- const facts = store.getFactsByEntity(entityId);
1125
- return facts.find((f2) => f2.a === targetProperty)?.v;
1126
- }
1127
- function toNumbers(values) {
1128
- const nums = [];
1129
- for (const v of values) {
1130
- if (typeof v === "number" && Number.isFinite(v)) nums.push(v);
1131
- }
1132
- return nums;
1133
- }
1134
- function evaluateRollup(rollup, ctx) {
1135
- const related = collectRollupRelatedIds(rollup, ctx);
1136
- if (rollup.aggregation === "count") {
1137
- return related.length;
1138
- }
1139
- const values = related.map((id) => readTargetValue(ctx.store, id, rollup.targetProperty)).filter((v) => v !== void 0);
1140
- const nums = toNumbers(values);
1141
- if (nums.length === 0) return 0;
1142
- switch (rollup.aggregation) {
1143
- case "sum":
1144
- return nums.reduce((a, b) => a + b, 0);
1145
- case "avg":
1146
- return nums.reduce((a, b) => a + b, 0) / nums.length;
1147
- case "min":
1148
- return Math.min(...nums);
1149
- case "max":
1150
- return Math.max(...nums);
1151
- case "median": {
1152
- const sorted = [...nums].sort((a, b) => a - b);
1153
- const mid = Math.floor(sorted.length / 2);
1154
- return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
1155
- }
1156
- case "mode": {
1157
- const freq = /* @__PURE__ */ new Map();
1158
- for (const n of nums) freq.set(n, (freq.get(n) ?? 0) + 1);
1159
- let best = nums[0];
1160
- let bestCount = 0;
1161
- for (const [n, c] of freq) {
1162
- if (c > bestCount) {
1163
- best = n;
1164
- bestCount = c;
1165
- }
1166
- }
1167
- return best;
1168
- }
1169
- default:
1170
- return 0;
1171
- }
1172
- }
1173
- function projectRelationFields(binding, schema, store, entityId) {
1174
- for (const field of schema.fields) {
1175
- if (field.valueType !== "relation" || field.name in binding) continue;
1176
- const links = store.getLinksByEntityAndAttribute(entityId, field.name);
1177
- if (links.length === 0) continue;
1178
- const cardinality = field.relation?.cardinality ?? "many";
1179
- if (cardinality === "one") {
1180
- binding[field.name] = links[0].e2;
1181
- } else {
1182
- binding[field.name] = links.map((l) => l.e2).join(",");
1183
- }
1184
- }
1185
- }
1186
-
1187
- // src/core/kernel/logic-middleware.ts
1188
- function createLogicMiddleware(config) {
1189
- return {
1190
- name: "logic-computation",
1191
- handleQuery(query, ctx, next) {
1192
- const result = next(query);
1193
- if (result && Array.isArray(result.bindings)) {
1194
- const store = resolveStore(config, ctx);
1195
- for (const binding of result.bindings) {
1196
- enrichBinding(binding, config, store);
1197
- }
1198
- }
1199
- return result;
1200
- }
1201
- };
1202
- }
1203
- function resolveStore(config, ctx) {
1204
- if (config.getStore) return config.getStore();
1205
- return ctx.store;
1206
- }
1207
- function enrichBinding(binding, config, store) {
1208
- const row = binding;
1209
- const type = resolveEntityType(binding, config);
1210
- if (!type) return;
1211
- const schema = config.ontologies.get(type);
1212
- if (!schema) return;
1213
- const entityId = findEntityId(binding);
1214
- if (store && entityId) {
1215
- projectRelationFields(binding, schema, store, entityId);
1216
- }
1217
- for (const field of schema.fields) {
1218
- if (!(field.computed || field.formula || field.rollup || field.aiGenerated))
1219
- continue;
1220
- const fieldName = field.name;
1221
- if (fieldName in binding) continue;
1222
- if (field.formula) {
1223
- binding[fieldName] = evalExpr(field.formula, row);
1224
- }
1225
- if (field.rollup && store && entityId) {
1226
- binding[fieldName] = evaluateRollup(field.rollup, {
1227
- store,
1228
- entityId,
1229
- schema,
1230
- getEntityType: config.getEntityType
1231
- });
1232
- }
1233
- if (field.aiGenerated && config.generateAiField) {
1234
- const prompt = field.aiGenerated.prompt.replace(
1235
- /\{\{(\w+)\}\}/g,
1236
- (_, key) => String(row[key] ?? "")
1237
- );
1238
- config.generateAiField(prompt, row).then((value) => {
1239
- binding[fieldName] = value;
1240
- }).catch(() => {
1241
- binding[fieldName] = "";
1242
- });
1243
- }
1244
- }
1245
- }
1246
- function resolveEntityType(binding, config) {
1247
- const explicit = binding.type;
1248
- if (typeof explicit === "string" && explicit.length > 0) return explicit;
1249
- const entityId = findEntityId(binding);
1250
- if (entityId && config.getEntityType) {
1251
- return config.getEntityType(entityId);
1252
- }
1253
- return void 0;
1254
- }
1255
- function findEntityId(binding) {
1256
- for (const value of Object.values(binding)) {
1257
- if (typeof value === "string" && value.includes(":")) return value;
1258
- }
1259
- return void 0;
1260
- }
1261
-
1262
- // src/core/kernel/boot-middleware.ts
1263
- function buildOntologyIndex(schemas) {
1264
- const map = /* @__PURE__ */ new Map();
1265
- for (const schema of schemas) {
1266
- map.set(schema["@id"], schema);
1267
- const short = schema["@id"].includes(":") ? schema["@id"].split(":").pop() : schema["@id"];
1268
- if (short) {
1269
- map.set(short, schema);
1270
- map.set(short.toLowerCase(), schema);
1271
- }
1272
- if (schema.label) {
1273
- map.set(schema.label, schema);
1274
- map.set(schema.label.toLowerCase(), schema);
1275
- }
1276
- }
1277
- return map;
1278
- }
1279
- function attachStandardMiddleware(kernel) {
1280
- kernel.removeMiddleware("logic-computation");
1281
- const ontologies = buildOntologyIndex(kernel.listOntologies());
1282
- kernel.addMiddleware(
1283
- createLogicMiddleware({
1284
- ontologies,
1285
- getStore: () => kernel.getStore(),
1286
- getEntityType: (entityId) => kernel.getEntity(entityId)?.type
1287
- })
1288
- );
1289
- }
1290
-
1291
- // src/core/persist/sqlite-backend.ts
1292
- var _DatabaseCtor = null;
1293
- function loadDatabaseCtor() {
1294
- if (_DatabaseCtor) return _DatabaseCtor;
1295
- try {
1296
- const { createRequire } = __require("module");
1297
- const requireCJS = createRequire(import.meta.url);
1298
- _DatabaseCtor = requireCJS("bun:sqlite").Database;
1299
- return _DatabaseCtor;
1300
- } catch {
1301
- throw new Error(
1302
- "SqliteKernelBackend requires the Bun runtime (built-in `bun:sqlite`). In Node / WebContainer use `createKernelBackend()` from `trellis/core` \u2014 it auto-selects better-sqlite3 or sql.js."
1303
- );
1304
- }
1305
- }
1306
- var SCHEMA_SQL = `
1307
- CREATE TABLE IF NOT EXISTS ops (
1308
- hash TEXT PRIMARY KEY,
1309
- kind TEXT NOT NULL,
1310
- timestamp TEXT NOT NULL,
1311
- agent_id TEXT NOT NULL,
1312
- previous_hash TEXT,
1313
- payload TEXT NOT NULL
1314
- );
1315
-
1316
- CREATE TABLE IF NOT EXISTS snapshots (
1317
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1318
- last_op_hash TEXT NOT NULL,
1319
- data TEXT NOT NULL,
1320
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
1321
- );
1322
-
1323
- CREATE TABLE IF NOT EXISTS blobs (
1324
- hash TEXT PRIMARY KEY,
1325
- content BLOB NOT NULL
1326
- );
1327
-
1328
- CREATE INDEX IF NOT EXISTS idx_ops_kind ON ops(kind);
1329
- CREATE INDEX IF NOT EXISTS idx_ops_timestamp ON ops(timestamp);
1330
- CREATE INDEX IF NOT EXISTS idx_ops_agent ON ops(agent_id);
1331
- CREATE INDEX IF NOT EXISTS idx_ops_previous ON ops(previous_hash);
1332
- CREATE INDEX IF NOT EXISTS idx_snapshots_op ON snapshots(last_op_hash);
1333
- `;
1334
- var SqliteKernelBackend = class {
1335
- constructor(dbPath) {
1336
- this.dbPath = dbPath;
1337
- const DatabaseCtor = loadDatabaseCtor();
1338
- this.db = new DatabaseCtor(dbPath);
1339
- }
1340
- db;
1341
- _stmts = null;
1342
- init() {
1343
- this.db.exec("PRAGMA journal_mode=WAL;");
1344
- this.db.exec("PRAGMA foreign_keys=ON;");
1345
- this.db.exec("PRAGMA synchronous=NORMAL;");
1346
- this.db.exec(SCHEMA_SQL);
1347
- this._prepareStatements();
1348
- }
1349
- _prepareStatements() {
1350
- this._stmts = {
1351
- insert: this.db.prepare(`
1352
- INSERT OR IGNORE INTO ops (hash, kind, timestamp, agent_id, previous_hash, payload)
1353
- VALUES ($hash, $kind, $timestamp, $agentId, $previousHash, $payload)
1354
- `),
1355
- readAll: this.db.prepare(`
1356
- SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1357
- FROM ops ORDER BY rowid ASC
1358
- `),
1359
- readUntil: this.db.prepare(`
1360
- SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1361
- FROM ops WHERE rowid <= (SELECT rowid FROM ops WHERE hash = $hash)
1362
- ORDER BY rowid ASC
1363
- `),
1364
- readAfter: this.db.prepare(`
1365
- SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1366
- FROM ops WHERE rowid > (SELECT rowid FROM ops WHERE hash = $hash)
1367
- ORDER BY rowid ASC
1368
- `),
1369
- getByHash: this.db.prepare(`
1370
- SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1371
- FROM ops WHERE hash = $hash
1372
- `),
1373
- getLast: this.db.prepare(`
1374
- SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1375
- FROM ops ORDER BY rowid DESC LIMIT 1
1376
- `),
1377
- count: this.db.prepare("SELECT COUNT(*) as cnt FROM ops"),
1378
- saveSnapshot: this.db.prepare(`
1379
- INSERT INTO snapshots (last_op_hash, data)
1380
- VALUES ($lastOpHash, $data)
1381
- `),
1382
- loadSnapshot: this.db.prepare(`
1383
- SELECT last_op_hash, data FROM snapshots
1384
- ORDER BY id DESC LIMIT 1
1385
- `),
1386
- putBlob: this.db.prepare(`
1387
- INSERT OR IGNORE INTO blobs (hash, content) VALUES ($hash, $content)
1388
- `),
1389
- getBlob: this.db.prepare(`
1390
- SELECT content FROM blobs WHERE hash = $hash
1391
- `),
1392
- hasBlob: this.db.prepare(`
1393
- SELECT 1 FROM blobs WHERE hash = $hash
1394
- `)
1395
- };
1396
- }
1397
- // -------------------------------------------------------------------------
1398
- // Op operations
1399
- // -------------------------------------------------------------------------
1400
- append(op) {
1401
- const payload = JSON.stringify({
1402
- facts: op.facts,
1403
- links: op.links,
1404
- ...op.deleteFacts?.length ? { deleteFacts: op.deleteFacts } : {},
1405
- ...op.deleteLinks?.length ? { deleteLinks: op.deleteLinks } : {},
1406
- ...op.vcs ? { vcs: op.vcs } : {},
1407
- ...op.signature ? { signature: op.signature } : {}
1408
- });
1409
- this._stmts.insert.run({
1410
- $hash: op.hash,
1411
- $kind: op.kind,
1412
- $timestamp: op.timestamp,
1413
- $agentId: op.agentId,
1414
- $previousHash: op.previousHash ?? null,
1415
- $payload: payload
1416
- });
1417
- }
1418
- appendBatch(ops) {
1419
- if (ops.length === 0) return;
1420
- this.db.transaction(() => {
1421
- for (const op of ops) {
1422
- this.append(op);
1423
- }
1424
- })();
1425
- }
1426
- readAll() {
1427
- const rows = this._stmts.readAll.all();
1428
- return rows.map(rowToOp);
1429
- }
1430
- readUntil(hash) {
1431
- const rows = this._stmts.readUntil.all({ $hash: hash });
1432
- return rows.map(rowToOp);
1433
- }
1434
- readAfter(hash) {
1435
- const rows = this._stmts.readAfter.all({ $hash: hash });
1436
- return rows.map(rowToOp);
1437
- }
1438
- readUntilTimestamp(isoTimestamp) {
1439
- const rows = this.db.prepare(
1440
- `SELECT hash, kind, timestamp, agent_id, previous_hash, payload
1441
- FROM ops WHERE timestamp <= $ts ORDER BY rowid ASC`
1442
- ).all({ $ts: isoTimestamp });
1443
- return rows.map(rowToOp);
1444
- }
1445
- getLastOp() {
1446
- const row = this._stmts.getLast.get();
1447
- return row ? rowToOp(row) : void 0;
1448
- }
1449
- getByHash(hash) {
1450
- return this.getOpByHash(hash);
1451
- }
1452
- getOpCount() {
1453
- return this.count();
1454
- }
1455
- getOpByHash(hash) {
1456
- const row = this._stmts.getByHash.get({ $hash: hash });
1457
- return row ? rowToOp(row) : void 0;
1458
- }
1459
- count() {
1460
- const row = this._stmts.count.get();
1461
- return row?.cnt ?? 0;
1462
- }
1463
- /**
1464
- * Find the common ancestor op of two op hashes by walking
1465
- * previousHash chains until they converge.
1466
- */
1467
- findCommonAncestor(hashA, hashB) {
1468
- const ancestorsA = /* @__PURE__ */ new Set();
1469
- let cursor = hashA;
1470
- while (cursor) {
1471
- ancestorsA.add(cursor);
1472
- const op = this.getOpByHash(cursor);
1473
- cursor = op?.previousHash;
1474
- }
1475
- cursor = hashB;
1476
- while (cursor) {
1477
- if (ancestorsA.has(cursor)) {
1478
- return this.getOpByHash(cursor);
1479
- }
1480
- const op = this.getOpByHash(cursor);
1481
- cursor = op?.previousHash;
1482
- }
1483
- return void 0;
1484
- }
1485
- // -------------------------------------------------------------------------
1486
- // Snapshot operations
1487
- // -------------------------------------------------------------------------
1488
- saveSnapshot(lastOpHash, data) {
1489
- this._stmts.saveSnapshot.run({
1490
- $lastOpHash: lastOpHash,
1491
- $data: JSON.stringify(data)
1492
- });
1493
- }
1494
- loadLatestSnapshot() {
1495
- const row = this._stmts.loadSnapshot.get();
1496
- if (!row) return void 0;
1497
- return {
1498
- lastOpHash: row.last_op_hash,
1499
- data: JSON.parse(row.data)
1500
- };
1501
- }
1502
- // -------------------------------------------------------------------------
1503
- // Blob operations
1504
- // -------------------------------------------------------------------------
1505
- putBlob(hash, content) {
1506
- this._stmts.putBlob.run({
1507
- $hash: hash,
1508
- $content: Buffer.from(content)
1509
- });
1510
- }
1511
- getBlob(hash) {
1512
- const row = this._stmts.getBlob.get({ $hash: hash });
1513
- if (!row) return void 0;
1514
- return new Uint8Array(row.content);
1515
- }
1516
- hasBlob(hash) {
1517
- return !!this._stmts.hasBlob.get({ $hash: hash });
1518
- }
1519
- // -------------------------------------------------------------------------
1520
- // Lifecycle
1521
- // -------------------------------------------------------------------------
1522
- close() {
1523
- this.db.close();
1524
- }
1525
- };
1526
- function rowToOp(row) {
1527
- const payload = JSON.parse(row.payload);
1528
- const op = {
1529
- hash: row.hash,
1530
- kind: row.kind,
1531
- timestamp: row.timestamp,
1532
- agentId: row.agent_id
1533
- };
1534
- if (row.previous_hash) op.previousHash = row.previous_hash;
1535
- if (payload.facts) op.facts = payload.facts;
1536
- if (payload.links) op.links = payload.links;
1537
- if (payload.deleteFacts) op.deleteFacts = payload.deleteFacts;
1538
- if (payload.deleteLinks) op.deleteLinks = payload.deleteLinks;
1539
- if (payload.vcs) op.vcs = payload.vcs;
1540
- if (payload.signature) op.signature = payload.signature;
1541
- return op;
1542
- }
1543
-
1544
- // src/server/tenancy.ts
1545
- var DEFAULT_TENANT = "default";
1546
- var TENANTS_DIR = "tenants";
1547
- var TenantPool = class {
1548
- pool = /* @__PURE__ */ new Map();
1549
- dbPath;
1550
- agentId;
1551
- backendOpts;
1552
- constructor(dbPath, agentIdOrOpts = "trellis-db") {
1553
- this.dbPath = resolve(dbPath);
1554
- if (typeof agentIdOrOpts === "string") {
1555
- this.agentId = agentIdOrOpts;
1556
- this.backendOpts = void 0;
1557
- } else {
1558
- this.agentId = agentIdOrOpts.agentId ?? "trellis-db";
1559
- this.backendOpts = agentIdOrOpts.backend;
1560
- }
1561
- this._ensureDirs();
1562
- }
1563
- // -------------------------------------------------------------------------
1564
- // Public API
1565
- // -------------------------------------------------------------------------
1566
- /**
1567
- * Get (or create) the kernel for a tenant.
1568
- * Pass `null` or `undefined` to get the default tenant.
1569
- *
1570
- * Uses the synchronous bun:sqlite backend. To use an async backend
1571
- * (better-sqlite3, sql.js) call `preload(tenantId)` first; subsequent
1572
- * `get()` calls will return the preloaded kernel from the pool.
1573
- */
1574
- get(tenantId) {
1575
- const id = tenantId ?? DEFAULT_TENANT;
1576
- if (!this.pool.has(id)) {
1577
- this.pool.set(id, this._createKernelSync(id));
1578
- }
1579
- return this.pool.get(id);
1580
- }
1581
- /**
1582
- * Pre-create a tenant's kernel using the runtime-selected backend.
1583
- * Required when running with an async-only backend (sql.js / WebContainer
1584
- * / browser). Idempotent — safe to call multiple times.
1585
- *
1586
- * After `preload()`, subsequent `get(tenantId)` returns the same kernel
1587
- * synchronously from the pool.
1588
- */
1589
- async preload(tenantId) {
1590
- const id = tenantId ?? DEFAULT_TENANT;
1591
- const cached = this.pool.get(id);
1592
- if (cached) return cached;
1593
- const kernel = await this._createKernelAsync(id);
1594
- this.pool.set(id, kernel);
1595
- return kernel;
1596
- }
1597
- /**
1598
- * Check whether a tenant has been initialized (kernel created).
1599
- */
1600
- has(tenantId) {
1601
- return this.pool.has(tenantId);
1602
- }
1603
- /**
1604
- * List all active tenant IDs (those with open kernels).
1605
- */
1606
- activeTenants() {
1607
- return Array.from(this.pool.keys());
1608
- }
1609
- /**
1610
- * Close a specific tenant's kernel and remove it from the pool.
1611
- */
1612
- close(tenantId) {
1613
- const kernel = this.pool.get(tenantId);
1614
- if (kernel) {
1615
- kernel.close();
1616
- this.pool.delete(tenantId);
1617
- }
1618
- }
1619
- /**
1620
- * Close all kernels and clear the pool.
1621
- */
1622
- closeAll() {
1623
- for (const kernel of this.pool.values()) {
1624
- kernel.close();
1625
- }
1626
- this.pool.clear();
1627
- }
1628
- /**
1629
- * Return the SQLite file path for a given tenant.
1630
- */
1631
- dbFilePath(tenantId) {
1632
- const id = tenantId ?? DEFAULT_TENANT;
1633
- if (id === DEFAULT_TENANT) {
1634
- return join(this.dbPath, "default.sqlite");
1635
- }
1636
- return join(this.dbPath, TENANTS_DIR, `${id}.sqlite`);
1637
- }
1638
- // -------------------------------------------------------------------------
1639
- // Private
1640
- // -------------------------------------------------------------------------
1641
- _createKernelSync(tenantId) {
1642
- const sqlitePath = this.dbFilePath(tenantId);
1643
- const backend = new SqliteKernelBackend(sqlitePath);
1644
- return this._wrapKernel(backend);
1645
- }
1646
- async _createKernelAsync(tenantId) {
1647
- const sqlitePath = this.dbFilePath(tenantId);
1648
- const { createKernelBackend } = await import("./factory-YP4ZZK5K.js");
1649
- const backend = await createKernelBackend(sqlitePath, this.backendOpts);
1650
- return this._wrapKernel(backend);
1651
- }
1652
- _wrapKernel(backend) {
1653
- const kernel = new TrellisKernel({
1654
- backend,
1655
- agentId: this.agentId,
1656
- snapshotThreshold: 1e3
1657
- });
1658
- kernel.boot();
1659
- attachStandardMiddleware(kernel);
1660
- return kernel;
1661
- }
1662
- _ensureDirs() {
1663
- if (!existsSync(this.dbPath)) {
1664
- mkdirSync(this.dbPath, { recursive: true });
1665
- }
1666
- const tenantsPath = join(this.dbPath, TENANTS_DIR);
1667
- if (!existsSync(tenantsPath)) {
1668
- mkdirSync(tenantsPath, { recursive: true });
1669
- }
1670
- }
1671
- };
1672
-
1673
- export {
1674
- DEFAULT_TENANT,
1675
- TenantPool
1676
- };