@eloxiv/cli 0.0.0-stage → 0.1.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 (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +110 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +50 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +35 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
@@ -0,0 +1,402 @@
1
+ /**
2
+ * The app's composition files, generated from the installed modules so that
3
+ * apps are assembled through the CLI rather than by hand:
4
+ * eloxiv.modules.ts module contracts (the action registry clients project from)
5
+ * eloxiv.server.ts server halves of the modules, the kernel modules they need, the connectors and the skills
6
+ * eloxiv.schema.ts the app's sync schema (the modules' generated tables) and named queries: what a server imports
7
+ * eloxiv.sync.ts those and the mutators: what a client imports (only it loads the modules' predictions)
8
+ *
9
+ * and each module's sync tables (`sync.gen.ts`, and `mutators.gen.ts` for a module with its own predictions),
10
+ * generated from its Drizzle tables and entities by importing its contract (`moduleSyncTables`, run by
11
+ * `eloxiv generate`).
12
+ */
13
+ import type { AnyAction, AnyEntity, AnyModuleContract } from "@eloxiv/contracts"
14
+ import { existsSync, readFileSync } from "node:fs"
15
+ import { posix, resolve } from "node:path"
16
+ import { pathToFileURL } from "node:url"
17
+ import type { EloxivMeta } from "./Registry.ts"
18
+ import { MODULE_SYNC_HEADER, MUTATORS_FILE, mutatorsSource, PREDICTIONS_FILE, syncSource } from "./SyncGen.ts"
19
+
20
+ export interface InstalledModule {
21
+ readonly name: string
22
+ readonly meta: EloxivMeta
23
+ }
24
+
25
+ /** An installed connector item (kind `connector`): its `server` export is a `ConnectorDefinition`. */
26
+ export interface InstalledConnector {
27
+ readonly name: string
28
+ readonly meta: EloxivMeta
29
+ }
30
+
31
+ /** Any other installed item (a UI item) that asks for kernel-provided modules (`meta.kernelModules`). */
32
+ export interface InstalledItem {
33
+ readonly name: string
34
+ readonly meta: EloxivMeta
35
+ }
36
+
37
+ const KERNEL_ORDER = ["inbox", "sharing", "connections", "search", "agent", "spaces", "devices"] as const
38
+ type KernelModule = (typeof KERNEL_ORDER)[number]
39
+
40
+ /** An installed skill item (kind `skill`): its `server` export is an `AppSkill` (`defineAppSkill`). */
41
+ export interface InstalledSkill {
42
+ readonly name: string
43
+ readonly meta: EloxivMeta
44
+ }
45
+
46
+ /**
47
+ * Whether a connector item provides kernel Connections (its `server` export is a `ConnectorDefinition`, composed into
48
+ * `KernelApp.connectors`). A model connector (one that provides `ModelProvider`) is not: the app adds it to
49
+ * `KernelApp.agent.providers` itself, as its `next` steps say.
50
+ */
51
+ export const isConnectionConnector = (meta: EloxivMeta): boolean =>
52
+ meta.kind === "connector" && meta.server !== undefined && !(meta.provides ?? []).includes("ModelProvider")
53
+
54
+ /** Whether a connector item is a model connector: its `server` export makes a ModelProvider (`ModelProviderFactory`). */
55
+ export const isModelConnector = (meta: EloxivMeta): boolean =>
56
+ meta.kind === "connector" && meta.server !== undefined && (meta.provides ?? []).includes("ModelProvider")
57
+
58
+ /**
59
+ * The kernel-provided modules the installed modules and UI items ask for, each once and in dependency order:
60
+ * sharing and the agent need the inbox (access requests reach managers as work items; an agent's consent-marked
61
+ * calls wait in it), and connectors need the connections module.
62
+ */
63
+ export const kernelModulesFor = (
64
+ modules: ReadonlyArray<InstalledModule>,
65
+ connectors: ReadonlyArray<InstalledConnector>,
66
+ requesting: ReadonlyArray<InstalledItem> = [],
67
+ ): ReadonlyArray<KernelModule> => {
68
+ const wanted = new Set([...modules, ...requesting].flatMap((m) => m.meta.kernelModules ?? []))
69
+ if (wanted.has("sharing") || wanted.has("agent") || wanted.has("devices")) wanted.add("inbox")
70
+ if (connectors.length > 0) wanted.add("connections")
71
+ return KERNEL_ORDER.filter((name) => wanted.has(name))
72
+ }
73
+
74
+ /** What each kernel-provided module set is in `eloxiv.server.ts`, and what it imports from `@eloxiv/kernel`. */
75
+ const KERNEL_EXPORTS = {
76
+ inbox: "...inboxModules",
77
+ sharing: "sharingModule",
78
+ connections: "connectionsModule",
79
+ search: "searchModule, ingestionModule",
80
+ agent: "agentModule",
81
+ spaces: "spacesModule",
82
+ devices: "devicesModule",
83
+ } as const
84
+ const KERNEL_IMPORTS = {
85
+ inbox: ["inboxModules"],
86
+ sharing: ["sharingModule"],
87
+ connections: ["connectionsModule"],
88
+ search: ["ingestionModule", "searchModule"],
89
+ agent: ["agentModule"],
90
+ spaces: ["spacesModule"],
91
+ devices: ["devicesModule"],
92
+ } as const
93
+
94
+ /**
95
+ * What each synced kernel-provided module adds to the app's sync schema, from `@eloxiv/client/sync`: its tables,
96
+ * its relationships and its named queries (sharing's grants are always there; connections and search sync nothing).
97
+ */
98
+ const KERNEL_SYNC: Partial<
99
+ Record<KernelModule, { readonly tables: string; readonly relationships?: string; readonly queries: string }>
100
+ > = {
101
+ inbox: { tables: "inboxTables", relationships: "inboxRelationships", queries: "inboxQueries" },
102
+ agent: { tables: "agentTables", relationships: "agentRelationships", queries: "agentQueries" },
103
+ spaces: { tables: "spacesTables", relationships: "spacesRelationships", queries: "spacesQueries" },
104
+ }
105
+
106
+ const HEADER = "// Generated by `eloxiv add`. Do not edit: run `eloxiv add <module>` to change it.\n"
107
+
108
+ export const identifier = (name: string) =>
109
+ name.replace(/[^a-zA-Z0-9]+(.)?/g, (_, c: string | undefined) => (c ?? "").toUpperCase())
110
+
111
+ const required = <A>(value: A | undefined, what: string): A => {
112
+ if (value === undefined) throw new Error(`Registry item metadata is missing ${what}`)
113
+ return value
114
+ }
115
+
116
+ export const modulesFile = (modules: ReadonlyArray<InstalledModule>) => {
117
+ const imports = modules.map((m) => {
118
+ const contract = required(m.meta.contract, `${m.name}.contract`)
119
+ return `import { ${contract.export} } from "${contract.file}"\n`
120
+ })
121
+ const list = modules.map((m) => m.meta.contract!.export).join(", ")
122
+ // With no modules, keep the element type (an empty tuple would type every module as never).
123
+ const declaration =
124
+ modules.length === 0
125
+ ? `import type { AnyModuleContract } from "@eloxiv/contracts"\n\n/** Module contracts installed in this app (none yet). */\nexport const contracts: ReadonlyArray<AnyModuleContract> = []\n`
126
+ : `\n/** Module contracts installed in this app: the action registry clients are projected from. */\nexport const contracts = [${list}] as const\n`
127
+ return `${HEADER}${imports.join("")}${declaration}`
128
+ }
129
+
130
+ export const serverFile = (
131
+ modules: ReadonlyArray<InstalledModule>,
132
+ connectors: ReadonlyArray<InstalledConnector> = [],
133
+ skills: ReadonlyArray<InstalledSkill> = [],
134
+ requesting: ReadonlyArray<InstalledItem> = [],
135
+ models: ReadonlyArray<InstalledConnector> = [],
136
+ ) => {
137
+ const kernel = kernelModulesFor(modules, connectors, [...requesting, ...models])
138
+ const types = [
139
+ ...(modules.length === 0 || kernel.length === 0 ? ["AnyKernelModule"] : []),
140
+ ...(skills.length === 0 ? ["AppSkill"] : []),
141
+ ...(connectors.length === 0 ? ["ConnectorDefinition"] : []),
142
+ ...(models.length === 0 ? ["ModelProviderFactory"] : []),
143
+ ]
144
+ const imports = [
145
+ ...(kernel.length === 0
146
+ ? []
147
+ : [
148
+ `import { ${kernel
149
+ .flatMap((k) => KERNEL_IMPORTS[k])
150
+ .sort()
151
+ .join(", ")} } from "@eloxiv/kernel"\n`,
152
+ ]),
153
+ ...(types.length === 0 ? [] : [`import type { ${types.join(", ")} } from "@eloxiv/kernel"\n`]),
154
+ ...modules.map((m) => {
155
+ const server = required(m.meta.server, `${m.name}.server`)
156
+ return `import { ${server.export} } from "${server.file}"\n`
157
+ }),
158
+ ...connectors.map((c) => {
159
+ const server = required(c.meta.server, `${c.name}.server`)
160
+ return `import { ${server.export} } from "${server.file}"\n`
161
+ }),
162
+ ...skills.map((s) => {
163
+ const server = required(s.meta.server, `${s.name}.server`)
164
+ return `import { ${server.export} } from "${server.file}"\n`
165
+ }),
166
+ ...models.map((m) => {
167
+ const server = required(m.meta.server, `${m.name}.server`)
168
+ return `import { ${server.export} } from "${server.file}"\n`
169
+ }),
170
+ ]
171
+ const list = modules.map((m) => m.meta.server!.export).join(", ")
172
+ const declaration =
173
+ modules.length === 0
174
+ ? `\n/** Server halves of the installed modules (none yet). */\nexport const modules: ReadonlyArray<AnyKernelModule> = []\n`
175
+ : `\n/** Server halves of the installed modules. */\nexport const modules = [${list}] as const\n`
176
+ const kernelDeclaration =
177
+ kernel.length === 0
178
+ ? `\n/** The kernel-provided modules the installed modules need (none). */\nexport const kernelModules: ReadonlyArray<AnyKernelModule> = []\n`
179
+ : `\n/** The kernel-provided modules the installed modules and UI items need (their \`kernelModules\`), each once. */\nexport const kernelModules = [${kernel.map((k) => KERNEL_EXPORTS[k]).join(", ")}] as const\n`
180
+ const connectorList = connectors.map((c) => c.meta.server!.export).join(", ")
181
+ const connectorDeclaration =
182
+ connectors.length === 0
183
+ ? `\n/** Installed connectors (none). */\nexport const connectors: ReadonlyArray<ConnectorDefinition> = []\n`
184
+ : `\n/** Installed connectors: the providers Connections can be made with (KernelApp.connectors). */\nexport const connectors = [${connectorList}] as const\n`
185
+ const skillList = skills.map((s) => s.meta.server!.export).join(", ")
186
+ const skillDeclaration =
187
+ skills.length === 0
188
+ ? `\n/** Installed skills (none). */\nexport const skills: ReadonlyArray<AppSkill> = []\n`
189
+ : `\n/** Installed skills: the app's own agent skills, beside the modules' (KernelApp.skills). */\nexport const skills = [${skillList}] as const\n`
190
+ const modelList = models.map((m) => m.meta.server!.export).join(", ")
191
+ const modelDeclaration =
192
+ models.length === 0
193
+ ? `\n/** Installed model connectors (none). */\nexport const modelProviders: ReadonlyArray<ModelProviderFactory> = []\n`
194
+ : `\n/** Installed model connectors: each makes a provider for the agent (KernelApp.agent.providers). */\nexport const modelProviders = [${modelList}] as const\n`
195
+ return `${HEADER}${imports.join("")}${declaration}${kernelDeclaration}${connectorDeclaration}${skillDeclaration}${modelDeclaration}`
196
+ }
197
+
198
+ /** Where a module's generated sync tables live: its `sync.tables`, else `sync.gen.ts` beside its queries. */
199
+ export const syncTablesFile = (meta: EloxivMeta): string | undefined => {
200
+ if (meta.sync === undefined) return undefined
201
+ return meta.sync.tables ?? meta.sync.file.replace(/[^/]*$/, "sync.gen.ts")
202
+ }
203
+
204
+ /**
205
+ * Where a synced module's generated files are, relative to the app, for generation and composition alike: its tables
206
+ * (`syncTablesFile`), its `predictions.ts` beside them, and its separate mutators file, `sync.mutators` or
207
+ * `mutators.gen.ts` beside the tables (older metadata names none). The mutators file exists exactly when generation
208
+ * puts the module's mutators apart (`moduleSyncTables`): always with a custom prediction.
209
+ */
210
+ export const syncLayout = (meta: EloxivMeta) => {
211
+ const tables = syncTablesFile(meta)
212
+ if (tables === undefined) return undefined
213
+ return {
214
+ tables,
215
+ predictions: tables.replace(/[^/]*$/, PREDICTIONS_FILE),
216
+ mutators: meta.sync?.mutators ?? tables.replace(/[^/]*$/, MUTATORS_FILE),
217
+ }
218
+ }
219
+
220
+ /** An import specifier for `target` from a file at `from` (both relative to the app). */
221
+ const importFrom = (from: string, target: string) => {
222
+ const relative = posix.relative(posix.dirname(from), target)
223
+ return relative.startsWith(".") ? relative : `./${relative}`
224
+ }
225
+
226
+ /**
227
+ * The app's sync schema and named queries (`eloxiv.schema.ts`): what the server imports. It never loads a module's
228
+ * mutators, so a module's predictions (client code, which may need a browser) never run in a server.
229
+ */
230
+ export const schemaFile = (
231
+ modules: ReadonlyArray<InstalledModule>,
232
+ connectors: ReadonlyArray<InstalledConnector> = [],
233
+ requesting: ReadonlyArray<InstalledItem> = [],
234
+ ) => {
235
+ const synced = modules.filter((m) => m.meta.sync !== undefined)
236
+ // With a synced kernel-provided module installed (the inbox, the agent, spaces), replicas hold each person's rows
237
+ // of it too: its work items and notifications, conversations, granted spaces.
238
+ const kernel = kernelModulesFor(modules, connectors, requesting).flatMap((k) => {
239
+ const sync = KERNEL_SYNC[k]
240
+ return sync === undefined ? [] : [sync]
241
+ })
242
+ const ids = synced.map((m) => identifier(m.name))
243
+ const imports = synced.map(
244
+ (m, i) =>
245
+ `import * as ${ids[i]}Tables from "${syncTablesFile(m.meta)}"\nimport * as ${ids[i]} from "${m.meta.sync!.file}"\n`,
246
+ )
247
+ const byModule = synced.map(
248
+ (m, i) => `${JSON.stringify(m.name).replace(/^"([a-zA-Z_$][\w$]*)"$/, "$1")}: ${ids[i]}.queries`,
249
+ )
250
+ const kernelSync = [
251
+ "shareGrant",
252
+ ...kernel.flatMap((k) => [k.tables, k.queries, ...(k.relationships === undefined ? [] : [k.relationships])]),
253
+ ]
254
+ .sort()
255
+ .join(", ")
256
+ return `${HEADER}import { createSchema, defineQueriesWithType } from "@eloxiv/client"
257
+ import { ${kernelSync} } from "@eloxiv/client/sync"
258
+ ${imports.join("")}
259
+ /**
260
+ * The app's sync schema: every installed module's generated tables (\`eloxiv generate\` writes them from the
261
+ * module's Drizzle tables and entities) and the kernel's sharing grants their \`shares\` relationships join.
262
+ * Typed precisely: \`connectSync({ schema, ... })\` is a \`SyncClient<AppSchema>\`.
263
+ */
264
+ export const schema = createSchema({
265
+ tables: [shareGrant${ids.map((id) => `, ...${id}Tables.tables`).join("")}${kernel.map((k) => `, ...${k.tables}`).join("")}],
266
+ relationships: [${[...ids.map((id) => `...${id}Tables.relationshipList`), ...kernel.flatMap((k) => (k.relationships === undefined ? [] : [`...${k.relationships}`]))].join(", ")}],
267
+ })
268
+ export type AppSchema = typeof schema
269
+
270
+ /**
271
+ * Named queries, namespaced by module (\`hello.greetings\`). The kernel infers each query's entity from the table
272
+ * it reads (and each \`related()\` or \`whereExists()\` child's from its own) and filters it by that entity's policy.
273
+ */
274
+ export const queries = defineQueriesWithType<AppSchema>()({ ${[...kernel.map((k) => `...${k.queries}`), ...byModule].join(", ")} })
275
+ `
276
+ }
277
+
278
+ /**
279
+ * The app's sync schema, named queries and mutators (`eloxiv.sync.ts`): what a client imports. The schema and queries
280
+ * are `eloxiv.schema.ts`'s; a module's mutators come from its separate mutators file (`syncLayout`) when it has one
281
+ * (`separate`: the app's composition asks whether that file exists, since generation writes it exactly when it puts
282
+ * them apart; without it, whether the metadata names one), else from its `sync.gen.ts`.
283
+ */
284
+ export const syncFile = (
285
+ modules: ReadonlyArray<InstalledModule>,
286
+ separate: (module: InstalledModule) => boolean = (m) => m.meta.sync?.mutators !== undefined,
287
+ ) => {
288
+ const synced = modules.filter((m) => m.meta.sync !== undefined)
289
+ const ids = synced.map((m) => identifier(m.name))
290
+ const apart = synced.map(separate)
291
+ const imports = synced.map((m, i) =>
292
+ apart[i]
293
+ ? `import * as ${ids[i]}Mutators from "${syncLayout(m.meta)!.mutators}"\n`
294
+ : `import * as ${ids[i]}Tables from "${syncTablesFile(m.meta)}"\n`,
295
+ )
296
+ const namespaces = synced.map((_, i) => `${ids[i]}${apart[i] ? "Mutators" : "Tables"}`)
297
+ return `${HEADER}import { defineMutators } from "@eloxiv/client"
298
+ import type { AppSchema } from "./eloxiv.schema.ts"
299
+ ${imports.join("")}
300
+ /** The app's sync schema and named queries (\`eloxiv.schema.ts\`, which a server imports without the mutators). */
301
+ export { queries, schema, type AppSchema } from "./eloxiv.schema.ts"
302
+
303
+ /**
304
+ * Optimistic writes, named by action (\`hello.greet\`): each module's mutators (\`eloxiv generate\` writes them from
305
+ * its actions' optimistic effects and its own predictions), for \`connectSync({ mutators })\` and
306
+ * \`write(replica, mutators.hello.greet(...))\`.
307
+ */
308
+ export const mutators = defineMutators<AppSchema>()(${namespaces.join(", ")})
309
+ `
310
+ }
311
+
312
+ /**
313
+ * Each installed module's generated sync tables: `[file, source]` for every module with sync, from its
314
+ * contract's entities, and its separate mutators file (`syncLayout`) when its mutators go apart: with a custom
315
+ * prediction, whatever its metadata says, or when its metadata names that file. The contract is imported (with its
316
+ * Drizzle tables) from the app, so the app's dependencies must be installed. Runs on Bun and Node.
317
+ */
318
+ export const moduleSyncTables = async (
319
+ dir: string,
320
+ modules: ReadonlyArray<InstalledModule>,
321
+ ): Promise<ReadonlyArray<readonly [string, string]>> => {
322
+ const files: Array<readonly [string, string]> = []
323
+ for (const module of modules) {
324
+ const tables = syncTablesFile(module.meta)
325
+ if (tables === undefined) continue
326
+ const contract = required(module.meta.contract, `${module.name}.contract`)
327
+ const loaded = (await import(pathToFileURL(resolve(dir, contract.file)).href)) as Record<string, unknown>
328
+ const exported = loaded[contract.export] as AnyModuleContract | undefined
329
+ if (exported?.entities === undefined || exported.actions === undefined) {
330
+ throw new Error(`${contract.file} does not export the module contract ${contract.export}`)
331
+ }
332
+ // An action predicting a change of its own needs the module's predictions, which the generated file imports.
333
+ const custom = Object.values(exported.actions as Readonly<Record<string, AnyAction>>).filter(
334
+ (action) => action.optimistic?.kind === "custom",
335
+ )
336
+ const layout = syncLayout(module.meta)!
337
+ const predictions = posix.normalize(layout.predictions)
338
+ // A custom prediction always puts the module's mutators (and its predictions' import) apart, so a server importing
339
+ // the tables never loads them; a module whose metadata names its mutators file keeps them there too.
340
+ const separate = custom.length > 0 || module.meta.sync?.mutators !== undefined
341
+ if (custom.length > 0 && !existsSync(resolve(dir, predictions))) {
342
+ throw new Error(
343
+ `${custom.map((a) => a.name).join(", ")} declare${custom.length === 1 ? "s" : ""} a custom prediction (optimistic.custom()), but ${predictions} is missing. Create it and export a prediction function for each action using its local name`,
344
+ )
345
+ }
346
+ // Each generated file's imports, relative to where it is written.
347
+ const options = {
348
+ header: MODULE_SYNC_HEADER,
349
+ kind: "module" as const,
350
+ optimistic: {
351
+ contract: exported,
352
+ from: importFrom(tables, contract.file),
353
+ exportName: contract.export,
354
+ separate,
355
+ mutatorsImports: {
356
+ contract: importFrom(layout.mutators, contract.file),
357
+ tables: importFrom(layout.mutators, tables),
358
+ predictions: importFrom(layout.mutators, layout.predictions),
359
+ },
360
+ },
361
+ }
362
+ const entities = Object.values(exported.entities) as ReadonlyArray<AnyEntity>
363
+ files.push([tables, syncSource(entities, options)])
364
+ const mutators = mutatorsSource(entities, options)
365
+ if (mutators !== undefined) files.push([layout.mutators, mutators])
366
+ }
367
+ return files
368
+ }
369
+
370
+ /**
371
+ * The separate mutators files generation no longer writes: a module's generated one (its header says so) whose
372
+ * mutators went back into `sync.gen.ts`, or that has none left. `eloxiv generate` removes them, so the composition,
373
+ * which imports a module's mutators file when it exists, never imports a stale one. Relative to the app.
374
+ */
375
+ export const staleMutatorsFiles = (
376
+ dir: string,
377
+ modules: ReadonlyArray<InstalledModule>,
378
+ generated: ReadonlyArray<readonly [string, string]>,
379
+ ): ReadonlyArray<string> => {
380
+ const written = new Set(generated.map(([file]) => posix.normalize(file)))
381
+ return modules.flatMap((module) => {
382
+ const layout = syncLayout(module.meta)
383
+ if (layout === undefined || written.has(posix.normalize(layout.mutators))) return []
384
+ const file = resolve(dir, layout.mutators)
385
+ if (!existsSync(file)) return []
386
+ return readFileSync(file, "utf8").startsWith(MODULE_SYNC_HEADER) ? [layout.mutators] : []
387
+ })
388
+ }
389
+
390
+ export const compositionFiles = (
391
+ modules: ReadonlyArray<InstalledModule>,
392
+ connectors: ReadonlyArray<InstalledConnector> = [],
393
+ skills: ReadonlyArray<InstalledSkill> = [],
394
+ requesting: ReadonlyArray<InstalledItem> = [],
395
+ models: ReadonlyArray<InstalledConnector> = [],
396
+ separate?: (module: InstalledModule) => boolean,
397
+ ): ReadonlyArray<readonly [string, string]> => [
398
+ ["eloxiv.modules.ts", modulesFile(modules)],
399
+ ["eloxiv.server.ts", serverFile(modules, connectors, skills, requesting, models)],
400
+ ["eloxiv.schema.ts", schemaFile(modules, connectors, [...requesting, ...models])],
401
+ ["eloxiv.sync.ts", syncFile(modules, separate)],
402
+ ]