@dbx-tools/cli 0.9.60 → 0.9.64

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 (43) hide show
  1. package/README.md +175 -81
  2. package/bin/dbx-genie.ts +10 -0
  3. package/index.ts +13 -1
  4. package/lib/bin/dbx-genie.d.ts +2 -0
  5. package/lib/bin/dbx-genie.js +10 -0
  6. package/lib/index.d.ts +13 -1
  7. package/lib/index.js +10 -2
  8. package/lib/src/auth/cli.js +13 -2
  9. package/lib/src/auth/options.d.ts +4 -0
  10. package/lib/src/auth/options.js +5 -1
  11. package/lib/src/cli.js +19 -4
  12. package/lib/src/genie-code/cli.d.ts +19 -0
  13. package/lib/src/genie-code/cli.js +36 -0
  14. package/lib/src/genie-code/config.d.ts +38 -0
  15. package/lib/src/genie-code/config.js +108 -0
  16. package/lib/src/genie-code/install.d.ts +21 -0
  17. package/lib/src/genie-code/install.js +69 -0
  18. package/lib/src/genie-code/options.d.ts +7 -0
  19. package/lib/src/genie-code/options.js +7 -0
  20. package/lib/src/genie-code/runner.d.ts +21 -0
  21. package/lib/src/genie-code/runner.js +90 -0
  22. package/lib/src/genie-code/runtime.d.ts +49 -0
  23. package/lib/src/genie-code/runtime.js +169 -0
  24. package/lib/src/graphiti/cli.js +2 -2
  25. package/lib/src/lakebase-proxy/cli.js +2 -2
  26. package/lib/src/model-gateway/cli.js +3 -3
  27. package/lib/src/model-gateway/server.d.ts +3 -0
  28. package/lib/src/model-gateway/server.js +39 -6
  29. package/lib/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +40 -18
  31. package/src/auth/cli.ts +11 -1
  32. package/src/auth/options.ts +4 -0
  33. package/src/cli.ts +17 -6
  34. package/src/genie-code/cli.ts +58 -0
  35. package/src/genie-code/config.ts +157 -0
  36. package/src/genie-code/install.ts +103 -0
  37. package/src/genie-code/options.ts +14 -0
  38. package/src/genie-code/runner.ts +106 -0
  39. package/src/genie-code/runtime.ts +231 -0
  40. package/src/graphiti/cli.ts +1 -1
  41. package/src/lakebase-proxy/cli.ts +1 -1
  42. package/src/model-gateway/cli.ts +6 -2
  43. package/src/model-gateway/server.ts +40 -5
@@ -0,0 +1,14 @@
1
+ /**
2
+ * CLI projection of the shared managed Genie Code options.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ export {
8
+ GenieCodeOptionsSchema as GenieCodeCliOptionsSchema,
9
+ resolveGenieCodeOptions as resolveGenieCodeCliOptions,
10
+ } from "@dbx-tools/shared-genie-code/options";
11
+ export type {
12
+ GenieCodeOptions as GenieCodeCliOptions,
13
+ ResolvedGenieCodeOptions as ResolvedGenieCodeCliOptions,
14
+ } from "@dbx-tools/shared-genie-code/options";
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Internal readiness gate and interactive Genie Code child process.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { AppKitChildProcess } from "@dbx-tools/appkit/child-process";
8
+ import { asyncUtils, log } from "@dbx-tools/shared-core";
9
+ import { GenieCodeRunnerOptionsSchema } from "@dbx-tools/shared-genie-code/options";
10
+
11
+ /** Private environment field carrying serialized runner options. */
12
+ const RUNNER_OPTIONS_ENV = "DBX_TOOLS_GENIE_RUNNER_OPTIONS";
13
+ const logger = log.logger("genie-code:runner");
14
+
15
+ /** Parse the serialized runner boundary from its private environment field. */
16
+ export function genieCodeRunnerOptions(environment: NodeJS.ProcessEnv = process.env) {
17
+ const serialized = environment[RUNNER_OPTIONS_ENV];
18
+ if (!serialized) throw new Error(`${RUNNER_OPTIONS_ENV} is required`);
19
+ return GenieCodeRunnerOptionsSchema.parse(JSON.parse(serialized));
20
+ }
21
+
22
+ /** Wait until the guarded model-gateway health route accepts the runner token. */
23
+ export async function waitForGenieCodeGateway(
24
+ healthUrl: string,
25
+ bearerToken: string,
26
+ timeoutMs: number,
27
+ ): Promise<void> {
28
+ for await (const ready of asyncUtils.poll(
29
+ async ({ signal }) => {
30
+ try {
31
+ const response = await fetch(healthUrl, {
32
+ headers: { authorization: `Bearer ${bearerToken}` },
33
+ signal,
34
+ });
35
+ return response.ok;
36
+ } catch {
37
+ return false;
38
+ }
39
+ },
40
+ {
41
+ intervalMs: 200,
42
+ timeoutMs,
43
+ predicate: (ready) => !ready,
44
+ },
45
+ )) {
46
+ if (ready) return;
47
+ }
48
+ }
49
+
50
+ /** Run Genie Code with inherited terminal streams after its gateway is ready. */
51
+ export async function runGenieCodeChild(
52
+ environment: NodeJS.ProcessEnv = process.env,
53
+ ): Promise<void> {
54
+ const options = genieCodeRunnerOptions(environment);
55
+ logger.info("waiting for model gateway", {
56
+ gateway: options.gatewayHealthUrl,
57
+ timeoutMs: options.startupTimeoutMs,
58
+ });
59
+ await waitForGenieCodeGateway(
60
+ options.gatewayHealthUrl,
61
+ options.bearerToken,
62
+ options.startupTimeoutMs,
63
+ );
64
+ logger.info("model gateway ready; starting Genie Code", {
65
+ executable: options.executable,
66
+ home: options.home,
67
+ });
68
+ const child = new AppKitChildProcess(
69
+ [
70
+ options.executable,
71
+ [...options.arguments],
72
+ {
73
+ cwd: process.cwd(),
74
+ env: {
75
+ ...environment,
76
+ GENIE_HOME: options.home,
77
+ },
78
+ stdin: "inherit",
79
+ stdout: "inherit",
80
+ stderr: "inherit",
81
+ },
82
+ ],
83
+ {
84
+ gracefulTimeoutMs: 5_000,
85
+ forceTimeoutMs: 1_000,
86
+ },
87
+ );
88
+ const running = child.start();
89
+ const shutdown = () => {
90
+ void child.shutdown();
91
+ };
92
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
93
+ process.once(signal, shutdown);
94
+ }
95
+ try {
96
+ const result = await running;
97
+ if (result.exitCode !== 0) process.exitCode = result.exitCode;
98
+ } finally {
99
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
100
+ process.off(signal, shutdown);
101
+ }
102
+ await child.shutdown();
103
+ }
104
+ }
105
+
106
+ export { RUNNER_OPTIONS_ENV };
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Supervise Genie Code and its authenticated local model gateway.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { randomBytes } from "node:crypto";
8
+ import { rm } from "node:fs/promises";
9
+ import { delimiter, dirname } from "node:path";
10
+ import { DatabricksModelRegistry, models } from "@dbx-tools/appkit-model-gateway";
11
+ import * as auth from "@dbx-tools/auth";
12
+ import { resolveServicePackageBin } from "@dbx-tools/cli-service/definition";
13
+ import type { BinContext } from "@dbx-tools/core/bin";
14
+ import { workspaceClient } from "@dbx-tools/databricks";
15
+ import { log } from "@dbx-tools/shared-core";
16
+ import {
17
+ resolveGenieCodeOptions,
18
+ type GenieCodeOptions,
19
+ type GenieCodeRunnerOptions,
20
+ } from "@dbx-tools/shared-genie-code/options";
21
+ import type { ModelClass } from "@dbx-tools/shared-model/contracts";
22
+ import concurrently from "concurrently";
23
+ import getPort from "get-port";
24
+
25
+ import { writeGenieCodeConfig, type GenieCodeHome } from "./config.ts";
26
+ import { installGenieCode } from "./install.ts";
27
+ import { RUNNER_OPTIONS_ENV } from "./runner.ts";
28
+
29
+ const logger = log.logger("genie-code");
30
+
31
+ /** Injectable owners used to prepare and supervise managed Genie Code. */
32
+ export interface GenieCodeRuntimeDependencies {
33
+ createAuthClient: typeof auth.client.createAuthClient;
34
+ install: typeof installGenieCode;
35
+ port(options: { host: string; port?: number }): Promise<number>;
36
+ resolveBin(packageReference: string, binName: string): string;
37
+ resolveCodexModel(
38
+ model: string | undefined,
39
+ profile: string,
40
+ modelClass?: ModelClass,
41
+ ): Promise<string>;
42
+ supervise: typeof concurrently;
43
+ token(): string;
44
+ writeConfig: typeof writeGenieCodeConfig;
45
+ }
46
+
47
+ const DEFAULT_DEPENDENCIES: GenieCodeRuntimeDependencies = {
48
+ createAuthClient: auth.client.createAuthClient,
49
+ install: installGenieCode,
50
+ port: ({ host, port }) => getPort({ host, ...(port ? { port } : {}) }),
51
+ resolveBin: resolveServicePackageBin,
52
+ resolveCodexModel,
53
+ supervise: concurrently,
54
+ token: () => randomBytes(32).toString("base64url"),
55
+ writeConfig: writeGenieCodeConfig,
56
+ };
57
+
58
+ /** Resolve a Genie `--model` value to the Codex catalogue slug the gateway publishes. */
59
+ async function resolveCodexModel(
60
+ model: string | undefined,
61
+ profile: string,
62
+ modelClass?: ModelClass,
63
+ ): Promise<string> {
64
+ const client = await workspaceClient.createWorkspaceClient({ profile });
65
+ const target = await new DatabricksModelRegistry({ client }).resolve(model, {
66
+ requiresTools: true,
67
+ ...(modelClass ? { modelClass } : {}),
68
+ });
69
+ if (!target) {
70
+ throw new Error(
71
+ model ? `Genie Code model not found: ${model}` : "No tool-capable chat model is available",
72
+ );
73
+ }
74
+ return models.codexModelSlug(target);
75
+ }
76
+
77
+ /** Inputs accepted by managed Genie Code preparation and execution. */
78
+ export interface RunGenieCodeOptions {
79
+ cwd?: string;
80
+ dependencies?: Partial<GenieCodeRuntimeDependencies>;
81
+ genieArgs?: readonly string[];
82
+ options?: GenieCodeOptions;
83
+ }
84
+
85
+ /** Resolved installation, auth, listener, and home for one invocation. */
86
+ export interface PreparedGenieCodeRuntime {
87
+ bearerToken: string;
88
+ gatewayBaseUrl: string;
89
+ gatewayHealthUrl: string;
90
+ gatewayListen: string;
91
+ gatewayPort: number;
92
+ home: GenieCodeHome;
93
+ installation: BinContext;
94
+ model: string;
95
+ profile: string;
96
+ }
97
+
98
+ /** Resolve auth, installation, listener, and configuration before spawning children. */
99
+ export async function prepareGenieCodeRuntime(
100
+ input: RunGenieCodeOptions = {},
101
+ ): Promise<PreparedGenieCodeRuntime> {
102
+ const dependencies = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
103
+ const options = resolveGenieCodeOptions(input.options);
104
+ logger.info("resolving Databricks authentication", {
105
+ requestedProfile: options.profile,
106
+ });
107
+ const authClient = await dependencies.createAuthClient(
108
+ options.profile ? { profile: options.profile } : {},
109
+ );
110
+ const profile = authClient.profile;
111
+ if (!profile) {
112
+ throw new Error("Genie Code requires a configured Databricks profile");
113
+ }
114
+ logger.info("preparing Genie Code runtime", {
115
+ profile,
116
+ model: options.model,
117
+ modelClass: options.modelClass,
118
+ });
119
+ const installation = await dependencies.install();
120
+ const host = options.gatewayListen.host;
121
+ const requestedPort = options.gatewayListen.port;
122
+ const gatewayPort = await dependencies.port({
123
+ host,
124
+ ...(requestedPort > 0 ? { port: requestedPort } : {}),
125
+ });
126
+ if (requestedPort > 0 && gatewayPort !== requestedPort) {
127
+ throw new Error(`Genie Code gateway port ${requestedPort} is already in use`);
128
+ }
129
+ const model = await dependencies.resolveCodexModel(options.model, profile, options.modelClass);
130
+ logger.info("resolved Genie Code model", {
131
+ requested: options.model,
132
+ modelClass: options.modelClass,
133
+ model,
134
+ });
135
+ const urlHost = host.includes(":") ? `[${host}]` : host;
136
+ const gatewayBaseUrl = `http://${urlHost}:${gatewayPort}/v1`;
137
+ const gatewayHealthUrl = `http://${urlHost}:${gatewayPort}/api/healthz`;
138
+ const gatewayListen = `tcp://${urlHost}:${gatewayPort}`;
139
+ const bearerToken = dependencies.token();
140
+ const home = await dependencies.writeConfig({
141
+ bearerToken,
142
+ gatewayBaseUrl,
143
+ model,
144
+ profile,
145
+ projectDirectory: input.cwd ?? process.cwd(),
146
+ });
147
+ return {
148
+ bearerToken,
149
+ gatewayBaseUrl,
150
+ gatewayHealthUrl,
151
+ gatewayListen,
152
+ gatewayPort,
153
+ home,
154
+ installation,
155
+ model,
156
+ profile,
157
+ };
158
+ }
159
+
160
+ function shellExecutable(path: string): string {
161
+ if (process.platform === "win32") return `"${path.replaceAll('"', '""')}"`;
162
+ return `'${path.replaceAll("'", "'\\''")}'`;
163
+ }
164
+
165
+ function childPath(...paths: string[]): string {
166
+ return [...new Set([...paths.map(dirname), process.env.PATH].filter(Boolean))].join(delimiter);
167
+ }
168
+
169
+ /** Run Genie Code and the model gateway until either process exits. */
170
+ export async function runGenieCode(input: RunGenieCodeOptions = {}): Promise<void> {
171
+ const dependencies = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
172
+ const prepared = await prepareGenieCodeRuntime({
173
+ ...input,
174
+ dependencies,
175
+ });
176
+ const gatewayBin = dependencies.resolveBin(import.meta.url, "dbx-model-gateway");
177
+ const runnerBin = dependencies.resolveBin(import.meta.url, "dbx-genie");
178
+ const path = childPath(gatewayBin, runnerBin);
179
+ const runnerOptions: GenieCodeRunnerOptions = {
180
+ executable: prepared.installation.path,
181
+ arguments: ["-p", prepared.home.overlayName, ...(input.genieArgs ?? [])],
182
+ home: prepared.home.home,
183
+ gatewayHealthUrl: prepared.gatewayHealthUrl,
184
+ bearerToken: prepared.bearerToken,
185
+ startupTimeoutMs: 60_000,
186
+ };
187
+ const { result } = dependencies.supervise(
188
+ [
189
+ {
190
+ command: shellExecutable(gatewayBin),
191
+ name: "gateway",
192
+ env: {
193
+ ...process.env,
194
+ PATH: path,
195
+ LISTEN: prepared.gatewayListen,
196
+ DATABRICKS_CONFIG_PROFILE: prepared.profile,
197
+ DBX_TOOLS_MODEL_GATEWAY_BEARER_TOKEN: prepared.bearerToken,
198
+ },
199
+ },
200
+ {
201
+ command: shellExecutable(runnerBin),
202
+ name: "genie",
203
+ env: {
204
+ ...process.env,
205
+ PATH: path,
206
+ DATABRICKS_CONFIG_PROFILE: prepared.profile,
207
+ [RUNNER_OPTIONS_ENV]: JSON.stringify(runnerOptions),
208
+ },
209
+ },
210
+ ],
211
+ {
212
+ cwd: input.cwd ?? process.cwd(),
213
+ raw: true,
214
+ killOthersOn: ["failure", "success"],
215
+ killSignal: "SIGTERM",
216
+ killTimeout: 17_000,
217
+ successCondition: "command-genie",
218
+ },
219
+ );
220
+ logger.info("started Genie Code and model gateway", {
221
+ profile: prepared.profile,
222
+ model: prepared.model,
223
+ gateway: prepared.gatewayBaseUrl,
224
+ home: prepared.home.home,
225
+ });
226
+ try {
227
+ await result;
228
+ } finally {
229
+ await rm(prepared.home.overlayPath, { force: true });
230
+ }
231
+ }
@@ -13,12 +13,12 @@ import { defineService, type CliServiceDefinition } from "@dbx-tools/cli-service
13
13
  import { runGraphiti, type GraphitiRuntimeOptions } from "@dbx-tools/graphiti/runtime";
14
14
  import { Command } from "commander";
15
15
 
16
- import { PACKAGE_VERSION } from "../../index.ts";
17
16
  import {
18
17
  GraphitiCliOptionsSchema,
19
18
  GraphitiOptionsSchema,
20
19
  type GraphitiOptions,
21
20
  } from "./options.ts";
21
+ import { PACKAGE_VERSION } from "../../index.ts";
22
22
 
23
23
  /** Injectable runtime and service lifecycle boundaries for CLI callers. */
24
24
  export interface GraphitiCliDependencies {
@@ -6,7 +6,6 @@ import { defineService, type CliServiceDefinition } from "@dbx-tools/cli-service
6
6
  import { connectionUrl } from "@dbx-tools/lakebase";
7
7
  import { Command } from "commander";
8
8
 
9
- import { PACKAGE_VERSION } from "../../index.ts";
10
9
  import {
11
10
  LakebaseProxyOptionsSchema,
12
11
  LakebaseProxyUrlOptionsSchema,
@@ -14,6 +13,7 @@ import {
14
13
  type LakebaseProxyOptions,
15
14
  } from "./options.ts";
16
15
  import { LakebaseProxy } from "./proxy.ts";
16
+ import { PACKAGE_VERSION } from "../../index.ts";
17
17
 
18
18
  /** Injectable service boundary for Lakebase proxy CLI composition and tests. */
19
19
  export interface LakebaseProxyCliDependencies {
@@ -15,8 +15,8 @@ import {
15
15
  } from "@dbx-tools/shared-model-gateway/options";
16
16
  import { Command } from "commander";
17
17
 
18
- import { PACKAGE_VERSION } from "../../index.ts";
19
18
  import { startModelGateway } from "./server.ts";
19
+ import { PACKAGE_VERSION } from "../../index.ts";
20
20
 
21
21
  /** Injectable foreground gateway boundary for CLI tests. */
22
22
  export interface ModelGatewayCliDependencies {
@@ -33,7 +33,11 @@ const DEFAULT_DEPENDENCIES: ModelGatewayCliDependencies = {
33
33
  export function modelGatewayServiceDefinition(
34
34
  options: ModelGatewayOptions = {},
35
35
  ): CliServiceDefinition {
36
- const { runtimeInfo: _, ...resolved } = resolveModelGatewayCliOptions(options);
36
+ const {
37
+ runtimeInfo: _,
38
+ bearerToken: _bearerToken,
39
+ ...resolved
40
+ } = resolveModelGatewayCliOptions(options);
37
41
  const host = urlHost(resolved.listen.host);
38
42
  return defineService(import.meta.url, {
39
43
  id: "dbx-tools.cli-model-gateway",
@@ -4,15 +4,17 @@
4
4
  * @module
5
5
  */
6
6
 
7
+ import { createHash, timingSafeEqual } from "node:crypto";
7
8
  import { createApp, server } from "@databricks/appkit";
8
- import { modelGateway } from "@dbx-tools/appkit-model-gateway/plugin";
9
- import { sendHealth } from "@dbx-tools/appkit-model-gateway/routes";
9
+ import { ModelGateway } from "@dbx-tools/appkit-model-gateway";
10
+ import { sendHealth, sendInference, sendModels } from "@dbx-tools/appkit-model-gateway/routes";
10
11
  import { workspaceClient } from "@dbx-tools/databricks";
11
12
  import {
12
13
  resolveModelGatewayOptions,
13
14
  type ModelGatewayOptions,
14
15
  type ResolvedModelGatewayOptions,
15
16
  } from "@dbx-tools/shared-model-gateway/options";
17
+ import type express from "express";
16
18
 
17
19
  type AppKitServerOptions = NonNullable<Parameters<typeof server>[0]>;
18
20
 
@@ -29,22 +31,55 @@ function appKitServerOptions(options: ResolvedModelGatewayOptions): AppKitServer
29
31
  };
30
32
  }
31
33
 
34
+ /** Require one bearer token without retaining or logging request credentials. */
35
+ export function gatewayBearerMiddleware(token: string): express.RequestHandler {
36
+ const expected = createHash("sha256").update(token).digest();
37
+ return (request, response, next) => {
38
+ const authorization = request.header("authorization");
39
+ const match = /^Bearer\s+(.+)$/i.exec(authorization ?? "");
40
+ const actual = createHash("sha256")
41
+ .update(match?.[1] ?? "")
42
+ .digest();
43
+ if (match && timingSafeEqual(actual, expected)) {
44
+ next();
45
+ return;
46
+ }
47
+ response
48
+ .status(401)
49
+ .setHeader("www-authenticate", "Bearer")
50
+ .json({
51
+ error: {
52
+ message: "Invalid or missing model-gateway bearer token.",
53
+ type: "authentication_error",
54
+ code: "invalid_bearer_token",
55
+ },
56
+ });
57
+ };
58
+ }
59
+
32
60
  /** Start the foreground model gateway and keep its AppKit server active. */
33
61
  export async function startModelGateway(options: ModelGatewayOptions = {}): Promise<void> {
34
62
  const resolved = resolveModelGatewayOptions(options);
63
+ const gateway = new ModelGateway({
64
+ ...(resolved.model ? { model: resolved.model } : {}),
65
+ ...(resolved.modelClass ? { modelClass: resolved.modelClass } : {}),
66
+ });
35
67
  const client = await workspaceClient.createWorkspaceClient({
36
68
  ...(resolved.profile ? { profile: resolved.profile } : {}),
37
69
  });
38
70
  await createApp({
39
71
  client,
40
- plugins: [modelGateway(), server(appKitServerOptions(resolved))],
72
+ plugins: [server(appKitServerOptions(resolved))],
41
73
  onPluginsReady(appkit) {
42
74
  appkit.server.extend((application) => {
75
+ if (resolved.bearerToken) {
76
+ application.use(gatewayBearerMiddleware(resolved.bearerToken));
77
+ }
43
78
  application.get("/api/healthz", (_request, response) => {
44
79
  sendHealth(response);
45
80
  });
46
81
  application.get("/v1/models", (request, response) => {
47
- void appkit.modelGateway.models(request, response);
82
+ void sendModels(gateway, request, response);
48
83
  });
49
84
  for (const [path, protocol] of [
50
85
  ["/v1/chat/completions", "openai-chat"],
@@ -53,7 +88,7 @@ export async function startModelGateway(options: ModelGatewayOptions = {}): Prom
53
88
  ["/v1/embeddings", "openai-embeddings"],
54
89
  ] as const) {
55
90
  application.post(path, (request, response) => {
56
- void appkit.modelGateway.inference(protocol, request, response);
91
+ void sendInference(gateway, protocol, request, response);
57
92
  });
58
93
  }
59
94
  });