@axiom-lattice/lattice-cli 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.
@@ -0,0 +1,15 @@
1
+
2
+ > @axiom-lattice/lattice-cli@0.1.1 build /home/runner/work/agentic/agentic/packages/lattice-cli
3
+ > tsup src/cli.ts --format esm --dts --sourcemap
4
+
5
+ CLI Building entry: src/cli.ts
6
+ CLI Using tsconfig: tsconfig.json
7
+ CLI tsup v8.5.0
8
+ CLI Target: es2020
9
+ ESM Build start
10
+ ESM dist/cli.js 9.82 KB
11
+ ESM dist/cli.js.map 18.15 KB
12
+ ESM ⚡️ Build success in 85ms
13
+ DTS Build start
14
+ DTS ⚡️ Build success in 12995ms
15
+ DTS dist/cli.d.ts 20.00 B
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @axiom-lattice/lattice-cli
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b4bdb6c: up new
8
+ - Updated dependencies [b4bdb6c]
9
+ - @axiom-lattice/local-stores@1.0.2
10
+ - @axiom-lattice/protocols@2.1.42
11
+ - @axiom-lattice/gateway@2.1.92
12
+ - @axiom-lattice/core@2.1.80
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server.ts
4
+ import { LatticeGateway } from "@axiom-lattice/gateway";
5
+ import {
6
+ configureStores,
7
+ sandboxLatticeManager,
8
+ createSandboxProvider
9
+ } from "@axiom-lattice/core";
10
+ import {
11
+ createLocalStoreConfig,
12
+ closeDatabase,
13
+ initDatabase
14
+ } from "@axiom-lattice/local-stores";
15
+ import { LoggerType } from "@axiom-lattice/protocols";
16
+ import * as fs from "fs";
17
+ import * as path from "path";
18
+ import { fileURLToPath } from "url";
19
+ var __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+ function resolveWebDir() {
21
+ const repoRoot = path.resolve(__dirname, "..", "..", "..", "apps", "cli-web", "dist");
22
+ if (fs.existsSync(repoRoot)) return repoRoot;
23
+ return null;
24
+ }
25
+ async function createStoresFallback(db) {
26
+ const mod = await import("@axiom-lattice/local-stores");
27
+ return {
28
+ thread: new mod.LocalThreadStore(db),
29
+ assistant: new mod.LocalAssistantStore(db),
30
+ workspace: new mod.LocalWorkspaceStore(db),
31
+ project: new mod.LocalProjectStore(db),
32
+ user: new mod.LocalUserStore(db),
33
+ tenant: new mod.LocalTenantStore(db),
34
+ userTenantLink: new mod.LocalUserTenantLinkStore(db),
35
+ database: new mod.LocalDatabaseConfigStore(db),
36
+ metrics: new mod.LocalMetricsServerConfigStore(db),
37
+ mcp: new mod.LocalMcpServerConfigStore(db),
38
+ workflowTracking: new mod.LocalWorkflowTrackingStore(db),
39
+ eval: new mod.LocalEvalStore(db),
40
+ channelBinding: new mod.LocalChannelBindingStore(db),
41
+ channelInstallation: new mod.LocalChannelInstallationStore(db),
42
+ a2aApiKey: new mod.LocalA2AApiKeyStore(db),
43
+ threadMessageQueue: new mod.LocalThreadMessageQueueStore(db),
44
+ skill: new mod.LocalSkillStore(db),
45
+ schedule: new mod.LocalScheduleStorage(db)
46
+ };
47
+ }
48
+ async function startServer(options) {
49
+ console.log(`
50
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
51
+ \u2551 Lattice Local Server \u2551
52
+ \u2551 Version: 0.1.0 \u2551
53
+ \u2551 Sandbox: local \u2551
54
+ \u2551 Stores: sqlite (sql.js) \u2551
55
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
56
+ `);
57
+ console.log(`[store] Initializing local stores at ${options.dbPath} ...`);
58
+ let stores;
59
+ let checkpoint = void 0;
60
+ try {
61
+ const result = await createLocalStoreConfig({ dbPath: options.dbPath });
62
+ stores = result;
63
+ } catch (e) {
64
+ const msg = e instanceof Error ? e.message : String(e);
65
+ if (msg.includes("better_sqlite3") || msg.includes("bindings")) {
66
+ console.log("[store] better-sqlite3 unavailable, skipping checkpoint saver");
67
+ const db = await initDatabase({ dbPath: options.dbPath });
68
+ stores = await createStoresFallback(db);
69
+ } else {
70
+ throw e;
71
+ }
72
+ }
73
+ const schedule = stores.schedule;
74
+ checkpoint = stores.checkpoint;
75
+ delete stores.schedule;
76
+ delete stores.checkpoint;
77
+ await configureStores(stores, { autoDisposeStores: true });
78
+ if (schedule) {
79
+ try {
80
+ const { registerScheduleLattice } = await import("@axiom-lattice/core");
81
+ registerScheduleLattice("default", {
82
+ name: "Default Scheduler",
83
+ description: "Local schedule storage",
84
+ type: "postgres",
85
+ storage: schedule
86
+ });
87
+ } catch {
88
+ }
89
+ }
90
+ if (checkpoint) {
91
+ try {
92
+ const { MemoryLatticeManager, registerCheckpointSaver } = await import("@axiom-lattice/core");
93
+ MemoryLatticeManager.getInstance().removeCheckpointSaver("default");
94
+ registerCheckpointSaver("default", checkpoint);
95
+ console.log("[store] Checkpoint saver registered");
96
+ } catch (e) {
97
+ console.log("[store] Checkpoint saver skipped:", e instanceof Error ? e.message : e);
98
+ }
99
+ }
100
+ console.log("[store] Local SQLite stores ready");
101
+ try {
102
+ const { getStoreLattice } = await import("@axiom-lattice/core");
103
+ const tenantId = "default";
104
+ const tenantStore = getStoreLattice("default", "tenant").store;
105
+ const existingTenant = await tenantStore.getTenantById(tenantId).catch(() => null);
106
+ if (!existingTenant) {
107
+ await tenantStore.createTenant(tenantId, { name: "Default" });
108
+ }
109
+ const userId = "local";
110
+ const userStore = getStoreLattice("default", "user").store;
111
+ const existingUser = await userStore.getUserById(userId).catch(() => null);
112
+ if (!existingUser) {
113
+ await userStore.createUser(userId, { name: "Local User", email: "local@local" });
114
+ }
115
+ const wsStore = getStoreLattice("default", "workspace").store;
116
+ const pjStore = getStoreLattice("default", "project").store;
117
+ const wss = await wsStore.getAllWorkspaces(tenantId);
118
+ if (wss.length === 0) {
119
+ const wsId = crypto.randomUUID();
120
+ await wsStore.createWorkspace(tenantId, wsId, { name: "Default", storageType: "sandbox" });
121
+ await pjStore.createProject(tenantId, wsId, crypto.randomUUID(), { name: "Default Project" });
122
+ }
123
+ const asStore = getStoreLattice("default", "assistant").store;
124
+ const existingAssistant = await asStore.getAssistantById(tenantId, "default-assistant").catch(() => null);
125
+ if (!existingAssistant) {
126
+ await asStore.createAssistant(tenantId, "default-assistant", {
127
+ name: "Default Assistant",
128
+ graphDefinition: {
129
+ key: "default-assistant",
130
+ type: "react",
131
+ prompt: "You are a helpful assistant.",
132
+ modelKey: "default",
133
+ tools: []
134
+ }
135
+ });
136
+ }
137
+ console.log("[store] Seeded tenant, user, workspace, project, and assistant");
138
+ } catch (e) {
139
+ console.log("[store] Seed skipped:", e instanceof Error ? e.message : e);
140
+ }
141
+ console.log(`[sandbox] Initializing local sandbox at ${options.sandboxBasePath} ...`);
142
+ const sandboxProvider = createSandboxProvider({
143
+ type: "local",
144
+ localSandboxBasePath: options.sandboxBasePath
145
+ });
146
+ sandboxLatticeManager.registerLattice("default", sandboxProvider);
147
+ console.log("[sandbox] Local sandbox provider registered");
148
+ await LatticeGateway.configureSwagger(LatticeGateway.app);
149
+ console.log(`[web] API docs: http://localhost:${options.port}/api-docs`);
150
+ if (options.serveWeb) {
151
+ const webDir = resolveWebDir();
152
+ if (webDir) {
153
+ console.log(`[web] Serving chat UI from ${webDir}`);
154
+ LatticeGateway.app.setNotFoundHandler((req, reply) => {
155
+ if ((req.url || "/").startsWith("/api")) {
156
+ return reply.status(404).send({ success: false, error: "Not found" });
157
+ }
158
+ return reply.type("text/html").send(fs.readFileSync(path.join(webDir, "index.html"), "utf-8"));
159
+ });
160
+ LatticeGateway.app.get("/assets/*", (req, reply) => {
161
+ const p = (req.url || "").split("?")[0].replace(/^\/+/, "");
162
+ const filePath = path.join(webDir, p);
163
+ if (!fs.existsSync(filePath)) return reply.status(404).send("Not found");
164
+ const ext = path.extname(filePath);
165
+ const ct = { ".js": "application/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".json": "application/json" };
166
+ return reply.type(ct[ext] || "application/octet-stream").send(fs.readFileSync(filePath));
167
+ });
168
+ console.log(`[web] Chat UI: http://localhost:${options.port}`);
169
+ } else {
170
+ console.log("[web] Web UI files not found (build apps/cli-web first: cd apps/cli-web && pnpm build)");
171
+ }
172
+ }
173
+ const DEFAULT_LOGGER_CONFIG = {
174
+ name: "default",
175
+ description: "Lattice CLI local server",
176
+ type: LoggerType.PINO,
177
+ serviceName: "lattice/cli",
178
+ loggerName: "lattice/cli"
179
+ };
180
+ LatticeGateway.startAsHttpEndpoint({
181
+ port: options.port,
182
+ queueServiceConfig: { type: "memory", defaultStartPollingQueue: true },
183
+ loggerConfig: DEFAULT_LOGGER_CONFIG
184
+ });
185
+ const shutdown = async () => {
186
+ console.log("\n[shutdown] Closing database and stopping server...");
187
+ closeDatabase();
188
+ await LatticeGateway.app.close();
189
+ process.exit(0);
190
+ };
191
+ process.on("SIGINT", shutdown);
192
+ process.on("SIGTERM", shutdown);
193
+ }
194
+
195
+ // src/cli.ts
196
+ import * as os from "os";
197
+ import * as path2 from "path";
198
+ function printHelp() {
199
+ console.log(`
200
+ lattice \u2014 Axiom Lattice local development server
201
+
202
+ Usage:
203
+ lattice [options]
204
+
205
+ Options:
206
+ --port, -p <number> Server port (default: 4001)
207
+ --db-path <path> SQLite database path (default: ~/.axiom/lattice.db)
208
+ --sandbox-path <path> Sandbox base directory (default: ~/.axiom-local-sandbox)
209
+ --web, -w Serve the chat web UI at /
210
+ --help, -h Show this help
211
+
212
+ Examples:
213
+ lattice Start API-only on port 4001
214
+ lattice --web Start with chat UI
215
+ lattice -p 3000 --web Custom port with web UI
216
+ lattice --db-path ./dev.db Custom database path
217
+ `);
218
+ }
219
+ function parseArgs() {
220
+ const args = process.argv.slice(2);
221
+ if (args.includes("--help") || args.includes("-h")) {
222
+ printHelp();
223
+ return null;
224
+ }
225
+ const getArg = (flag) => {
226
+ const idx = args.findIndex((a) => a === flag);
227
+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : void 0;
228
+ };
229
+ const hasFlag = (flag) => args.includes(flag);
230
+ const portStr = getArg("--port") ?? getArg("-p");
231
+ const port = portStr ? parseInt(portStr, 10) : 4001;
232
+ return {
233
+ port,
234
+ dbPath: getArg("--db-path") ?? path2.join(os.homedir(), ".axiom", "lattice.db"),
235
+ sandboxBasePath: getArg("--sandbox-path") ?? path2.join(os.homedir(), ".axiom-local-sandbox"),
236
+ serveWeb: hasFlag("--web") || hasFlag("-w")
237
+ };
238
+ }
239
+ async function main() {
240
+ const options = parseArgs();
241
+ if (!options) return;
242
+ try {
243
+ await startServer(options);
244
+ } catch (err) {
245
+ console.error("Failed to start server:", err);
246
+ process.exit(1);
247
+ }
248
+ }
249
+ main();
250
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/cli.ts"],"sourcesContent":["import { LatticeGateway } from \"@axiom-lattice/gateway\";\nimport {\n configureStores,\n sandboxLatticeManager,\n createSandboxProvider,\n} from \"@axiom-lattice/core\";\nimport {\n createLocalStoreConfig,\n closeDatabase,\n initDatabase,\n} from \"@axiom-lattice/local-stores\";\nimport { LoggerType } from \"@axiom-lattice/protocols\";\nimport type { LoggerConfig } from \"@axiom-lattice/protocols\";\nimport type { DatabaseWrapper } from \"@axiom-lattice/local-stores\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nexport interface LatticeCliOptions {\n port: number;\n dbPath: string;\n sandboxBasePath: string;\n serveWeb: boolean;\n}\n\nfunction resolveWebDir(): string | null {\n // Look for apps/cli-web/dist (Vite build output)\n const repoRoot = path.resolve(__dirname, \"..\", \"..\", \"..\", \"apps\", \"cli-web\", \"dist\");\n if (fs.existsSync(repoRoot)) return repoRoot;\n return null;\n}\n\n/**\n * Fallback: create all local stores manually without checkpoint saver.\n * Used when createLocalStoreConfig fails due to better-sqlite3 not being available.\n */\nasync function createStoresFallback(\n db: DatabaseWrapper\n): Promise<Record<string, unknown>> {\n const mod = await import(\"@axiom-lattice/local-stores\");\n return {\n thread: new mod.LocalThreadStore(db),\n assistant: new mod.LocalAssistantStore(db),\n workspace: new mod.LocalWorkspaceStore(db),\n project: new mod.LocalProjectStore(db),\n user: new mod.LocalUserStore(db),\n tenant: new mod.LocalTenantStore(db),\n userTenantLink: new mod.LocalUserTenantLinkStore(db),\n database: new mod.LocalDatabaseConfigStore(db),\n metrics: new mod.LocalMetricsServerConfigStore(db),\n mcp: new mod.LocalMcpServerConfigStore(db),\n workflowTracking: new mod.LocalWorkflowTrackingStore(db),\n eval: new mod.LocalEvalStore(db),\n channelBinding: new mod.LocalChannelBindingStore(db),\n channelInstallation: new mod.LocalChannelInstallationStore(db),\n a2aApiKey: new mod.LocalA2AApiKeyStore(db),\n threadMessageQueue: new mod.LocalThreadMessageQueueStore(db),\n skill: new mod.LocalSkillStore(db),\n schedule: new mod.LocalScheduleStorage(db),\n };\n}\n\nexport async function startServer(options: LatticeCliOptions): Promise<void> {\n console.log(`\n╔═══════════════════════════════════════════╗\n║ Lattice Local Server ║\n║ Version: 0.1.0 ║\n║ Sandbox: local ║\n║ Stores: sqlite (sql.js) ║\n╚═══════════════════════════════════════════╝\n`);\n\n // 1. Initialize local SQLite stores\n console.log(`[store] Initializing local stores at ${options.dbPath} ...`);\n\n let stores: Record<string, unknown>;\n let checkpoint: unknown = undefined;\n\n try {\n const result = await createLocalStoreConfig({ dbPath: options.dbPath });\n stores = result as unknown as Record<string, unknown>;\n } catch (e: unknown) {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.includes(\"better_sqlite3\") || msg.includes(\"bindings\")) {\n console.log(\"[store] better-sqlite3 unavailable, skipping checkpoint saver\");\n const db = await initDatabase({ dbPath: options.dbPath });\n stores = await createStoresFallback(db);\n } else {\n throw e;\n }\n }\n\n // Extract special keys\n const schedule = stores.schedule;\n checkpoint = stores.checkpoint;\n delete stores.schedule;\n delete stores.checkpoint;\n\n await configureStores(stores as Parameters<typeof configureStores>[0], { autoDisposeStores: true });\n\n // Register schedule storage\n if (schedule) {\n try {\n const { registerScheduleLattice } = await import(\"@axiom-lattice/core\");\n registerScheduleLattice(\"default\", {\n name: \"Default Scheduler\",\n description: \"Local schedule storage\",\n type: \"postgres\" as never,\n storage: schedule as never,\n });\n } catch { /* non-critical */ }\n }\n\n // Register checkpoint saver\n if (checkpoint) {\n try {\n const { MemoryLatticeManager, registerCheckpointSaver } = await import(\"@axiom-lattice/core\");\n MemoryLatticeManager.getInstance().removeCheckpointSaver(\"default\");\n registerCheckpointSaver(\"default\", checkpoint as Parameters<typeof registerCheckpointSaver>[1]);\n console.log(\"[store] Checkpoint saver registered\");\n } catch (e) {\n console.log(\"[store] Checkpoint saver skipped:\", e instanceof Error ? e.message : e);\n }\n }\n\n console.log(\"[store] Local SQLite stores ready\");\n\n // Seed default tenant, workspace, and project so the UI works out of the box\n try {\n const { getStoreLattice } = await import(\"@axiom-lattice/core\");\n\n const tenantId = \"default\";\n\n // Ensure default tenant exists\n const tenantStore = getStoreLattice(\"default\", \"tenant\").store as {\n getTenantById(id: string): Promise<unknown>;\n createTenant(id: string, data: { name: string }): Promise<unknown>;\n };\n const existingTenant = await tenantStore.getTenantById(tenantId).catch(() => null);\n if (!existingTenant) {\n await tenantStore.createTenant(tenantId, { name: \"Default\" });\n }\n\n // Ensure default user exists (onboarding will update the name)\n const userId = \"local\";\n const userStore = getStoreLattice(\"default\", \"user\").store as {\n getUserById(id: string): Promise<unknown>;\n createUser(id: string, data: { name: string; email: string }): Promise<unknown>;\n };\n const existingUser = await userStore.getUserById(userId).catch(() => null);\n if (!existingUser) {\n await userStore.createUser(userId, { name: \"Local User\", email: \"local@local\" });\n }\n\n // Ensure default workspace + project exist\n const wsStore = getStoreLattice(\"default\", \"workspace\").store as {\n getAllWorkspaces(tenantId: string): Promise<{ id: string }[]>;\n createWorkspace(tenantId: string, id: string, data: { name: string; storageType: string }): Promise<unknown>;\n };\n const pjStore = getStoreLattice(\"default\", \"project\").store as {\n getProjectsByWorkspace(tenantId: string, workspaceId: string): Promise<{ id: string }[]>;\n createProject(tenantId: string, workspaceId: string, id: string, data: { name: string }): Promise<unknown>;\n };\n const wss = await wsStore.getAllWorkspaces(tenantId);\n if (wss.length === 0) {\n const wsId = crypto.randomUUID();\n await wsStore.createWorkspace(tenantId, wsId, { name: \"Default\", storageType: \"sandbox\" });\n await pjStore.createProject(tenantId, wsId, crypto.randomUUID(), { name: \"Default Project\" });\n }\n\n // Ensure default assistant exists (model must be registered first via onboarding)\n const asStore = getStoreLattice(\"default\", \"assistant\").store as {\n getAssistantById(tenantId: string, id: string): Promise<unknown>;\n createAssistant(tenantId: string, id: string, data: { name: string; graphDefinition: unknown }): Promise<unknown>;\n };\n const existingAssistant = await asStore.getAssistantById(tenantId, \"default-assistant\").catch(() => null);\n if (!existingAssistant) {\n await asStore.createAssistant(tenantId, \"default-assistant\", {\n name: \"Default Assistant\",\n graphDefinition: {\n key: \"default-assistant\",\n type: \"react\",\n prompt: \"You are a helpful assistant.\",\n modelKey: \"default\",\n tools: [],\n },\n });\n }\n console.log(\"[store] Seeded tenant, user, workspace, project, and assistant\");\n } catch (e) {\n console.log(\"[store] Seed skipped:\", e instanceof Error ? e.message : e);\n }\n\n // 2. Register local sandbox provider\n console.log(`[sandbox] Initializing local sandbox at ${options.sandboxBasePath} ...`);\n const sandboxProvider = createSandboxProvider({\n type: \"local\",\n localSandboxBasePath: options.sandboxBasePath,\n });\n sandboxLatticeManager.registerLattice(\"default\", sandboxProvider);\n console.log(\"[sandbox] Local sandbox provider registered\");\n\n // 3. Swagger setup\n await LatticeGateway.configureSwagger(LatticeGateway.app);\n console.log(`[web] API docs: http://localhost:${options.port}/api-docs`);\n\n // 4. Serve web UI if requested\n if (options.serveWeb) {\n const webDir = resolveWebDir();\n if (webDir) {\n console.log(`[web] Serving chat UI from ${webDir}`);\n\n // SPA fallback: serve index.html for paths without an extension\n LatticeGateway.app.setNotFoundHandler((req, reply) => {\n if ((req.url || \"/\").startsWith(\"/api\")) {\n return reply.status(404).send({ success: false, error: \"Not found\" });\n }\n return reply.type(\"text/html\").send(fs.readFileSync(path.join(webDir, \"index.html\"), \"utf-8\"));\n });\n\n // Serve static assets\n LatticeGateway.app.get(\"/assets/*\", (req, reply) => {\n const p = (req.url || \"\").split(\"?\")[0].replace(/^\\/+/, \"\");\n const filePath = path.join(webDir, p);\n if (!fs.existsSync(filePath)) return reply.status(404).send(\"Not found\");\n const ext = path.extname(filePath);\n const ct: Record<string, string> = { \".js\": \"application/javascript\", \".css\": \"text/css\", \".svg\": \"image/svg+xml\", \".png\": \"image/png\", \".ico\": \"image/x-icon\", \".json\": \"application/json\" };\n return reply.type(ct[ext] || \"application/octet-stream\").send(fs.readFileSync(filePath));\n });\n\n console.log(`[web] Chat UI: http://localhost:${options.port}`);\n } else {\n console.log(\"[web] Web UI files not found (build apps/cli-web first: cd apps/cli-web && pnpm build)\");\n }\n }\n\n // 5. Start gateway\n const DEFAULT_LOGGER_CONFIG: LoggerConfig = {\n name: \"default\",\n description: \"Lattice CLI local server\",\n type: LoggerType.PINO,\n serviceName: \"lattice/cli\",\n loggerName: \"lattice/cli\",\n };\n\n LatticeGateway.startAsHttpEndpoint({\n port: options.port,\n queueServiceConfig: { type: \"memory\", defaultStartPollingQueue: true },\n loggerConfig: DEFAULT_LOGGER_CONFIG,\n });\n\n // Graceful shutdown\n const shutdown = async () => {\n console.log(\"\\n[shutdown] Closing database and stopping server...\");\n closeDatabase();\n await LatticeGateway.app.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n","#!/usr/bin/env node\nimport { startServer, type LatticeCliOptions } from \"./server.js\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nfunction printHelp(): void {\n console.log(`\nlattice — Axiom Lattice local development server\n\nUsage:\n lattice [options]\n\nOptions:\n --port, -p <number> Server port (default: 4001)\n --db-path <path> SQLite database path (default: ~/.axiom/lattice.db)\n --sandbox-path <path> Sandbox base directory (default: ~/.axiom-local-sandbox)\n --web, -w Serve the chat web UI at /\n --help, -h Show this help\n\nExamples:\n lattice Start API-only on port 4001\n lattice --web Start with chat UI\n lattice -p 3000 --web Custom port with web UI\n lattice --db-path ./dev.db Custom database path\n`);\n}\n\nfunction parseArgs(): LatticeCliOptions | null {\n const args = process.argv.slice(2);\n\n if (args.includes(\"--help\") || args.includes(\"-h\")) {\n printHelp();\n return null;\n }\n\n const getArg = (flag: string): string | undefined => {\n const idx = args.findIndex((a) => a === flag);\n return idx !== -1 && args[idx + 1] ? args[idx + 1] : undefined;\n };\n\n const hasFlag = (flag: string): boolean => args.includes(flag);\n\n const portStr = getArg(\"--port\") ?? getArg(\"-p\");\n const port = portStr ? parseInt(portStr, 10) : 4001;\n\n return {\n port,\n dbPath: getArg(\"--db-path\") ?? path.join(os.homedir(), \".axiom\", \"lattice.db\"),\n sandboxBasePath: getArg(\"--sandbox-path\") ?? path.join(os.homedir(), \".axiom-local-sandbox\"),\n serveWeb: hasFlag(\"--web\") || hasFlag(\"-w\"),\n };\n}\n\nasync function main(): Promise<void> {\n const options = parseArgs();\n if (!options) return; // help printed\n\n try {\n await startServer(options);\n } catch (err) {\n console.error(\"Failed to start server:\", err);\n process.exit(1);\n }\n}\n\nmain();\n"],"mappings":";;;AAAA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAG3B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,qBAAqB;AAE9B,IAAM,YAAiB,aAAQ,cAAc,YAAY,GAAG,CAAC;AAS7D,SAAS,gBAA+B;AAEtC,QAAM,WAAgB,aAAQ,WAAW,MAAM,MAAM,MAAM,QAAQ,WAAW,MAAM;AACpF,MAAO,cAAW,QAAQ,EAAG,QAAO;AACpC,SAAO;AACT;AAMA,eAAe,qBACb,IACkC;AAClC,QAAM,MAAM,MAAM,OAAO,6BAA6B;AACtD,SAAO;AAAA,IACL,QAAQ,IAAI,IAAI,iBAAiB,EAAE;AAAA,IACnC,WAAW,IAAI,IAAI,oBAAoB,EAAE;AAAA,IACzC,WAAW,IAAI,IAAI,oBAAoB,EAAE;AAAA,IACzC,SAAS,IAAI,IAAI,kBAAkB,EAAE;AAAA,IACrC,MAAM,IAAI,IAAI,eAAe,EAAE;AAAA,IAC/B,QAAQ,IAAI,IAAI,iBAAiB,EAAE;AAAA,IACnC,gBAAgB,IAAI,IAAI,yBAAyB,EAAE;AAAA,IACnD,UAAU,IAAI,IAAI,yBAAyB,EAAE;AAAA,IAC7C,SAAS,IAAI,IAAI,8BAA8B,EAAE;AAAA,IACjD,KAAK,IAAI,IAAI,0BAA0B,EAAE;AAAA,IACzC,kBAAkB,IAAI,IAAI,2BAA2B,EAAE;AAAA,IACvD,MAAM,IAAI,IAAI,eAAe,EAAE;AAAA,IAC/B,gBAAgB,IAAI,IAAI,yBAAyB,EAAE;AAAA,IACnD,qBAAqB,IAAI,IAAI,8BAA8B,EAAE;AAAA,IAC7D,WAAW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;AAClD,cAAU;AACV,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,CAAC,SAAqC;AACnD,UAAM,MAAM,KAAK,UAAU,CAAC,MAAM,MAAM,IAAI;AAC5C,WAAO,QAAQ,MAAM,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI;AAAA,EACvD;AAEA,QAAM,UAAU,CAAC,SAA0B,KAAK,SAAS,IAAI;AAE7D,QAAM,UAAU,OAAO,QAAQ,KAAK,OAAO,IAAI;AAC/C,QAAM,OAAO,UAAU,SAAS,SAAS,EAAE,IAAI;AAE/C,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,OAAO,WAAW,KAAU,WAAQ,WAAQ,GAAG,UAAU,YAAY;AAAA,IAC7E,iBAAiB,OAAO,gBAAgB,KAAU,WAAQ,WAAQ,GAAG,sBAAsB;AAAA,IAC3F,UAAU,QAAQ,OAAO,KAAK,QAAQ,IAAI;AAAA,EAC5C;AACF;AAEA,eAAe,OAAsB;AACnC,QAAM,UAAU,UAAU;AAC1B,MAAI,CAAC,QAAS;AAEd,MAAI;AACF,UAAM,YAAY,OAAO;AAAA,EAC3B,SAAS,KAAK;AACZ,YAAQ,MAAM,2BAA2B,GAAG;AAC5C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;","names":["path"]}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@axiom-lattice/lattice-cli",
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "main": "dist/cli.js",
6
+ "bin": {
7
+ "lattice": "./dist/cli.js"
8
+ },
9
+ "dependencies": {
10
+ "@axiom-lattice/core": "2.1.80",
11
+ "@axiom-lattice/gateway": "2.1.92",
12
+ "@axiom-lattice/local-stores": "1.0.2",
13
+ "@axiom-lattice/protocols": "2.1.42"
14
+ },
15
+ "devDependencies": {
16
+ "@types/node": "^20.17.23",
17
+ "rimraf": "^5.0.5",
18
+ "tsup": "^8.5.0",
19
+ "typescript": "^5.8.2"
20
+ },
21
+ "scripts": {
22
+ "build": "tsup src/cli.ts --format esm --dts --sourcemap",
23
+ "start": "node dist/cli.js",
24
+ "dev": "tsup src/cli.ts --format esm --dts --watch --onSuccess \"node dist/cli.js\"",
25
+ "lint": "tsc --noEmit",
26
+ "clean": "rimraf dist"
27
+ }
28
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { startServer, type LatticeCliOptions } from "./server.js";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+
6
+ function printHelp(): void {
7
+ console.log(`
8
+ lattice — Axiom Lattice local development server
9
+
10
+ Usage:
11
+ lattice [options]
12
+
13
+ Options:
14
+ --port, -p <number> Server port (default: 4001)
15
+ --db-path <path> SQLite database path (default: ~/.axiom/lattice.db)
16
+ --sandbox-path <path> Sandbox base directory (default: ~/.axiom-local-sandbox)
17
+ --web, -w Serve the chat web UI at /
18
+ --help, -h Show this help
19
+
20
+ Examples:
21
+ lattice Start API-only on port 4001
22
+ lattice --web Start with chat UI
23
+ lattice -p 3000 --web Custom port with web UI
24
+ lattice --db-path ./dev.db Custom database path
25
+ `);
26
+ }
27
+
28
+ function parseArgs(): LatticeCliOptions | null {
29
+ const args = process.argv.slice(2);
30
+
31
+ if (args.includes("--help") || args.includes("-h")) {
32
+ printHelp();
33
+ return null;
34
+ }
35
+
36
+ const getArg = (flag: string): string | undefined => {
37
+ const idx = args.findIndex((a) => a === flag);
38
+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : undefined;
39
+ };
40
+
41
+ const hasFlag = (flag: string): boolean => args.includes(flag);
42
+
43
+ const portStr = getArg("--port") ?? getArg("-p");
44
+ const port = portStr ? parseInt(portStr, 10) : 4001;
45
+
46
+ return {
47
+ port,
48
+ dbPath: getArg("--db-path") ?? path.join(os.homedir(), ".axiom", "lattice.db"),
49
+ sandboxBasePath: getArg("--sandbox-path") ?? path.join(os.homedir(), ".axiom-local-sandbox"),
50
+ serveWeb: hasFlag("--web") || hasFlag("-w"),
51
+ };
52
+ }
53
+
54
+ async function main(): Promise<void> {
55
+ const options = parseArgs();
56
+ if (!options) return; // help printed
57
+
58
+ try {
59
+ await startServer(options);
60
+ } catch (err) {
61
+ console.error("Failed to start server:", err);
62
+ process.exit(1);
63
+ }
64
+ }
65
+
66
+ main();
package/src/server.ts ADDED
@@ -0,0 +1,264 @@
1
+ import { LatticeGateway } from "@axiom-lattice/gateway";
2
+ import {
3
+ configureStores,
4
+ sandboxLatticeManager,
5
+ createSandboxProvider,
6
+ } from "@axiom-lattice/core";
7
+ import {
8
+ createLocalStoreConfig,
9
+ closeDatabase,
10
+ initDatabase,
11
+ } from "@axiom-lattice/local-stores";
12
+ import { LoggerType } from "@axiom-lattice/protocols";
13
+ import type { LoggerConfig } from "@axiom-lattice/protocols";
14
+ import type { DatabaseWrapper } from "@axiom-lattice/local-stores";
15
+ import * as fs from "node:fs";
16
+ import * as path from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+
21
+ export interface LatticeCliOptions {
22
+ port: number;
23
+ dbPath: string;
24
+ sandboxBasePath: string;
25
+ serveWeb: boolean;
26
+ }
27
+
28
+ function resolveWebDir(): string | null {
29
+ // Look for apps/cli-web/dist (Vite build output)
30
+ const repoRoot = path.resolve(__dirname, "..", "..", "..", "apps", "cli-web", "dist");
31
+ if (fs.existsSync(repoRoot)) return repoRoot;
32
+ return null;
33
+ }
34
+
35
+ /**
36
+ * Fallback: create all local stores manually without checkpoint saver.
37
+ * Used when createLocalStoreConfig fails due to better-sqlite3 not being available.
38
+ */
39
+ async function createStoresFallback(
40
+ db: DatabaseWrapper
41
+ ): Promise<Record<string, unknown>> {
42
+ const mod = await import("@axiom-lattice/local-stores");
43
+ return {
44
+ thread: new mod.LocalThreadStore(db),
45
+ assistant: new mod.LocalAssistantStore(db),
46
+ workspace: new mod.LocalWorkspaceStore(db),
47
+ project: new mod.LocalProjectStore(db),
48
+ user: new mod.LocalUserStore(db),
49
+ tenant: new mod.LocalTenantStore(db),
50
+ userTenantLink: new mod.LocalUserTenantLinkStore(db),
51
+ database: new mod.LocalDatabaseConfigStore(db),
52
+ metrics: new mod.LocalMetricsServerConfigStore(db),
53
+ mcp: new mod.LocalMcpServerConfigStore(db),
54
+ workflowTracking: new mod.LocalWorkflowTrackingStore(db),
55
+ eval: new mod.LocalEvalStore(db),
56
+ channelBinding: new mod.LocalChannelBindingStore(db),
57
+ channelInstallation: new mod.LocalChannelInstallationStore(db),
58
+ a2aApiKey: new mod.LocalA2AApiKeyStore(db),
59
+ threadMessageQueue: new mod.LocalThreadMessageQueueStore(db),
60
+ skill: new mod.LocalSkillStore(db),
61
+ schedule: new mod.LocalScheduleStorage(db),
62
+ };
63
+ }
64
+
65
+ export async function startServer(options: LatticeCliOptions): Promise<void> {
66
+ console.log(`
67
+ ╔═══════════════════════════════════════════╗
68
+ ║ Lattice Local Server ║
69
+ ║ Version: 0.1.0 ║
70
+ ║ Sandbox: local ║
71
+ ║ Stores: sqlite (sql.js) ║
72
+ ╚═══════════════════════════════════════════╝
73
+ `);
74
+
75
+ // 1. Initialize local SQLite stores
76
+ console.log(`[store] Initializing local stores at ${options.dbPath} ...`);
77
+
78
+ let stores: Record<string, unknown>;
79
+ let checkpoint: unknown = undefined;
80
+
81
+ try {
82
+ const result = await createLocalStoreConfig({ dbPath: options.dbPath });
83
+ stores = result as unknown as Record<string, unknown>;
84
+ } catch (e: unknown) {
85
+ const msg = e instanceof Error ? e.message : String(e);
86
+ if (msg.includes("better_sqlite3") || msg.includes("bindings")) {
87
+ console.log("[store] better-sqlite3 unavailable, skipping checkpoint saver");
88
+ const db = await initDatabase({ dbPath: options.dbPath });
89
+ stores = await createStoresFallback(db);
90
+ } else {
91
+ throw e;
92
+ }
93
+ }
94
+
95
+ // Extract special keys
96
+ const schedule = stores.schedule;
97
+ checkpoint = stores.checkpoint;
98
+ delete stores.schedule;
99
+ delete stores.checkpoint;
100
+
101
+ await configureStores(stores as Parameters<typeof configureStores>[0], { autoDisposeStores: true });
102
+
103
+ // Register schedule storage
104
+ if (schedule) {
105
+ try {
106
+ const { registerScheduleLattice } = await import("@axiom-lattice/core");
107
+ registerScheduleLattice("default", {
108
+ name: "Default Scheduler",
109
+ description: "Local schedule storage",
110
+ type: "postgres" as never,
111
+ storage: schedule as never,
112
+ });
113
+ } catch { /* non-critical */ }
114
+ }
115
+
116
+ // Register checkpoint saver
117
+ if (checkpoint) {
118
+ try {
119
+ const { MemoryLatticeManager, registerCheckpointSaver } = await import("@axiom-lattice/core");
120
+ MemoryLatticeManager.getInstance().removeCheckpointSaver("default");
121
+ registerCheckpointSaver("default", checkpoint as Parameters<typeof registerCheckpointSaver>[1]);
122
+ console.log("[store] Checkpoint saver registered");
123
+ } catch (e) {
124
+ console.log("[store] Checkpoint saver skipped:", e instanceof Error ? e.message : e);
125
+ }
126
+ }
127
+
128
+ console.log("[store] Local SQLite stores ready");
129
+
130
+ // Seed default tenant, workspace, and project so the UI works out of the box
131
+ try {
132
+ const { getStoreLattice } = await import("@axiom-lattice/core");
133
+
134
+ const tenantId = "default";
135
+
136
+ // Ensure default tenant exists
137
+ const tenantStore = getStoreLattice("default", "tenant").store as {
138
+ getTenantById(id: string): Promise<unknown>;
139
+ createTenant(id: string, data: { name: string }): Promise<unknown>;
140
+ };
141
+ const existingTenant = await tenantStore.getTenantById(tenantId).catch(() => null);
142
+ if (!existingTenant) {
143
+ await tenantStore.createTenant(tenantId, { name: "Default" });
144
+ }
145
+
146
+ // Ensure default user exists (onboarding will update the name)
147
+ const userId = "local";
148
+ const userStore = getStoreLattice("default", "user").store as {
149
+ getUserById(id: string): Promise<unknown>;
150
+ createUser(id: string, data: { name: string; email: string }): Promise<unknown>;
151
+ };
152
+ const existingUser = await userStore.getUserById(userId).catch(() => null);
153
+ if (!existingUser) {
154
+ await userStore.createUser(userId, { name: "Local User", email: "local@local" });
155
+ }
156
+
157
+ // Ensure default workspace + project exist
158
+ const wsStore = getStoreLattice("default", "workspace").store as {
159
+ getAllWorkspaces(tenantId: string): Promise<{ id: string }[]>;
160
+ createWorkspace(tenantId: string, id: string, data: { name: string; storageType: string }): Promise<unknown>;
161
+ };
162
+ const pjStore = getStoreLattice("default", "project").store as {
163
+ getProjectsByWorkspace(tenantId: string, workspaceId: string): Promise<{ id: string }[]>;
164
+ createProject(tenantId: string, workspaceId: string, id: string, data: { name: string }): Promise<unknown>;
165
+ };
166
+ const wss = await wsStore.getAllWorkspaces(tenantId);
167
+ if (wss.length === 0) {
168
+ const wsId = crypto.randomUUID();
169
+ await wsStore.createWorkspace(tenantId, wsId, { name: "Default", storageType: "sandbox" });
170
+ await pjStore.createProject(tenantId, wsId, crypto.randomUUID(), { name: "Default Project" });
171
+ }
172
+
173
+ // Ensure default assistant exists (model must be registered first via onboarding)
174
+ const asStore = getStoreLattice("default", "assistant").store as {
175
+ getAssistantById(tenantId: string, id: string): Promise<unknown>;
176
+ createAssistant(tenantId: string, id: string, data: { name: string; graphDefinition: unknown }): Promise<unknown>;
177
+ };
178
+ const existingAssistant = await asStore.getAssistantById(tenantId, "default-assistant").catch(() => null);
179
+ if (!existingAssistant) {
180
+ await asStore.createAssistant(tenantId, "default-assistant", {
181
+ name: "Default Assistant",
182
+ graphDefinition: {
183
+ key: "default-assistant",
184
+ type: "react",
185
+ prompt: "You are a helpful assistant.",
186
+ modelKey: "default",
187
+ tools: [],
188
+ },
189
+ });
190
+ }
191
+ console.log("[store] Seeded tenant, user, workspace, project, and assistant");
192
+ } catch (e) {
193
+ console.log("[store] Seed skipped:", e instanceof Error ? e.message : e);
194
+ }
195
+
196
+ // 2. Register local sandbox provider
197
+ console.log(`[sandbox] Initializing local sandbox at ${options.sandboxBasePath} ...`);
198
+ const sandboxProvider = createSandboxProvider({
199
+ type: "local",
200
+ localSandboxBasePath: options.sandboxBasePath,
201
+ });
202
+ sandboxLatticeManager.registerLattice("default", sandboxProvider);
203
+ console.log("[sandbox] Local sandbox provider registered");
204
+
205
+ // 3. Swagger setup
206
+ await LatticeGateway.configureSwagger(LatticeGateway.app);
207
+ console.log(`[web] API docs: http://localhost:${options.port}/api-docs`);
208
+
209
+ // 4. Serve web UI if requested
210
+ if (options.serveWeb) {
211
+ const webDir = resolveWebDir();
212
+ if (webDir) {
213
+ console.log(`[web] Serving chat UI from ${webDir}`);
214
+
215
+ // SPA fallback: serve index.html for paths without an extension
216
+ LatticeGateway.app.setNotFoundHandler((req, reply) => {
217
+ if ((req.url || "/").startsWith("/api")) {
218
+ return reply.status(404).send({ success: false, error: "Not found" });
219
+ }
220
+ return reply.type("text/html").send(fs.readFileSync(path.join(webDir, "index.html"), "utf-8"));
221
+ });
222
+
223
+ // Serve static assets
224
+ LatticeGateway.app.get("/assets/*", (req, reply) => {
225
+ const p = (req.url || "").split("?")[0].replace(/^\/+/, "");
226
+ const filePath = path.join(webDir, p);
227
+ if (!fs.existsSync(filePath)) return reply.status(404).send("Not found");
228
+ const ext = path.extname(filePath);
229
+ const ct: Record<string, string> = { ".js": "application/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".json": "application/json" };
230
+ return reply.type(ct[ext] || "application/octet-stream").send(fs.readFileSync(filePath));
231
+ });
232
+
233
+ console.log(`[web] Chat UI: http://localhost:${options.port}`);
234
+ } else {
235
+ console.log("[web] Web UI files not found (build apps/cli-web first: cd apps/cli-web && pnpm build)");
236
+ }
237
+ }
238
+
239
+ // 5. Start gateway
240
+ const DEFAULT_LOGGER_CONFIG: LoggerConfig = {
241
+ name: "default",
242
+ description: "Lattice CLI local server",
243
+ type: LoggerType.PINO,
244
+ serviceName: "lattice/cli",
245
+ loggerName: "lattice/cli",
246
+ };
247
+
248
+ LatticeGateway.startAsHttpEndpoint({
249
+ port: options.port,
250
+ queueServiceConfig: { type: "memory", defaultStartPollingQueue: true },
251
+ loggerConfig: DEFAULT_LOGGER_CONFIG,
252
+ });
253
+
254
+ // Graceful shutdown
255
+ const shutdown = async () => {
256
+ console.log("\n[shutdown] Closing database and stopping server...");
257
+ closeDatabase();
258
+ await LatticeGateway.app.close();
259
+ process.exit(0);
260
+ };
261
+
262
+ process.on("SIGINT", shutdown);
263
+ process.on("SIGTERM", shutdown);
264
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "preserve",
5
+ "lib": ["ES2020"],
6
+ "outDir": "./dist",
7
+ "rootDir": "./src",
8
+ "strict": true,
9
+ "moduleResolution": "Bundler",
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "resolveJsonModule": true,
14
+ "declaration": true,
15
+ "declarationMap": true,
16
+ "sourceMap": true,
17
+ "types": ["node"]
18
+ },
19
+ "include": ["src/cli.ts", "src/server.ts"],
20
+ "exclude": ["node_modules", "dist", "web"]
21
+ }