@dbx-tools/cli 0.9.60 → 0.9.61

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 (39) hide show
  1. package/README.md +64 -17
  2. package/bin/dbx-genie.ts +13 -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 +8 -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 +111 -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 +48 -0
  23. package/lib/src/genie-code/runtime.js +162 -0
  24. package/lib/src/model-gateway/cli.js +3 -3
  25. package/lib/src/model-gateway/server.d.ts +3 -0
  26. package/lib/src/model-gateway/server.js +36 -6
  27. package/lib/tsconfig.tsbuildinfo +1 -1
  28. package/package.json +40 -18
  29. package/src/auth/cli.ts +11 -1
  30. package/src/auth/options.ts +4 -0
  31. package/src/cli.ts +13 -2
  32. package/src/genie-code/cli.ts +58 -0
  33. package/src/genie-code/config.ts +161 -0
  34. package/src/genie-code/install.ts +103 -0
  35. package/src/genie-code/options.ts +14 -0
  36. package/src/genie-code/runner.ts +106 -0
  37. package/src/genie-code/runtime.ts +212 -0
  38. package/src/model-gateway/cli.ts +6 -2
  39. package/src/model-gateway/server.ts +37 -5
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Generate one persistent Genie Code home per exact profile-model pairing.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join, resolve } from "node:path";
11
+ import { withFileLock } from "@dbx-tools/core/file-lock";
12
+ import { object } from "@dbx-tools/shared-core";
13
+ import {
14
+ GenieCodeBaseConfigSchema,
15
+ GenieCodeConfigSchema,
16
+ GenieCodeProviderOverlaySchema,
17
+ type GenieCodeBaseConfig,
18
+ type GenieCodeConfig,
19
+ type GenieCodeProviderOverlay,
20
+ } from "@dbx-tools/shared-genie-code/config";
21
+ import { genieCodePairingName } from "@dbx-tools/shared-genie-code/options";
22
+ import { parse, stringify } from "smol-toml";
23
+
24
+ /** Provider identifier written to the base and invocation overlay configurations. */
25
+ export const GENIE_CODE_GATEWAY_PROVIDER = "dbx_tools_model_gateway";
26
+
27
+ /** Inputs used to update a persistent home and create one invocation overlay. */
28
+ export interface WriteGenieCodeConfigOptions {
29
+ bearerToken: string;
30
+ gatewayBaseUrl: string;
31
+ homeDirectory?: string;
32
+ model: string;
33
+ profile: string;
34
+ projectDirectory: string;
35
+ }
36
+
37
+ /** Stable persistent home for one exact profile-model pairing. */
38
+ export interface GenieCodePairingHome {
39
+ configPath: string;
40
+ home: string;
41
+ name: string;
42
+ }
43
+
44
+ /** Persistent pairing home and invocation-specific provider overlay. */
45
+ export interface GenieCodeHome extends GenieCodePairingHome {
46
+ overlayName: string;
47
+ overlayPath: string;
48
+ }
49
+
50
+ /** Derive the stable home for one exact profile-model pair. */
51
+ export function genieCodeHome(
52
+ profile: string,
53
+ model: string,
54
+ homeDirectory: string = homedir(),
55
+ ): GenieCodePairingHome {
56
+ const digest = createHash("sha256")
57
+ .update(JSON.stringify([profile, model]))
58
+ .digest("hex")
59
+ .slice(0, 12);
60
+ const name = genieCodePairingName({ profile, model, digest });
61
+ const home = join(homeDirectory, ".dbx-tools", "genie", "profiles", name);
62
+ return { name, home, configPath: join(home, "config.toml") };
63
+ }
64
+
65
+ /** Render the persistent profile-model configuration. */
66
+ export function genieCodeBaseConfig(
67
+ options: WriteGenieCodeConfigOptions,
68
+ existingProjects: Readonly<Record<string, unknown>> = {},
69
+ ): GenieCodeBaseConfig {
70
+ const projects = Object.fromEntries(
71
+ Object.entries(existingProjects).filter(
72
+ ([, value]) => object.isRecord(value) && value.trust_level === "trusted",
73
+ ),
74
+ );
75
+ return GenieCodeBaseConfigSchema.parse({
76
+ model_provider: GENIE_CODE_GATEWAY_PROVIDER,
77
+ model: options.model,
78
+ databricks_profile: options.profile,
79
+ projects: {
80
+ ...projects,
81
+ [resolve(options.projectDirectory)]: {
82
+ trust_level: "trusted",
83
+ },
84
+ },
85
+ tui: {
86
+ model_availability_nux: {
87
+ [options.model]: 1,
88
+ },
89
+ },
90
+ });
91
+ }
92
+
93
+ /** Render the invocation-specific guarded provider configuration. */
94
+ export function genieCodeProviderOverlay(
95
+ options: WriteGenieCodeConfigOptions,
96
+ ): GenieCodeProviderOverlay {
97
+ return GenieCodeProviderOverlaySchema.parse({
98
+ model_providers: {
99
+ [GENIE_CODE_GATEWAY_PROVIDER]: {
100
+ name: "dbx-tools model gateway",
101
+ base_url: options.gatewayBaseUrl,
102
+ wire_api: "responses",
103
+ requires_openai_auth: false,
104
+ supports_websockets: false,
105
+ http_headers: {
106
+ Authorization: `Bearer ${options.bearerToken}`,
107
+ Originator: "codex",
108
+ },
109
+ },
110
+ },
111
+ });
112
+ }
113
+
114
+ /** Render the merged configuration used by validation and tests. */
115
+ export function genieCodeConfig(options: WriteGenieCodeConfigOptions): GenieCodeConfig {
116
+ return GenieCodeConfigSchema.parse({
117
+ ...genieCodeBaseConfig(options),
118
+ ...genieCodeProviderOverlay(options),
119
+ });
120
+ }
121
+
122
+ async function existingProjects(path: string): Promise<Record<string, unknown>> {
123
+ try {
124
+ const value = parse(await readFile(path, "utf8"));
125
+ return object.isRecord(value.projects) ? value.projects : {};
126
+ } catch (error) {
127
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {};
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ async function writePrivateToml(path: string, value: unknown): Promise<void> {
133
+ const staged = join(dirname(path), `.${randomUUID()}.toml`);
134
+ try {
135
+ await writeFile(staged, stringify(value), { mode: 0o600 });
136
+ await chmod(staged, 0o600);
137
+ await rename(staged, path);
138
+ } finally {
139
+ await rm(staged, { force: true });
140
+ }
141
+ }
142
+
143
+ /** Update the persistent base config and write one private invocation overlay. */
144
+ export async function writeGenieCodeConfig(
145
+ options: WriteGenieCodeConfigOptions,
146
+ ): Promise<GenieCodeHome> {
147
+ const base = genieCodeHome(options.profile, options.model, options.homeDirectory);
148
+ const overlayName = `dbx-${randomUUID().replaceAll("-", "")}`;
149
+ const destination = {
150
+ ...base,
151
+ overlayName,
152
+ overlayPath: join(base.home, `${overlayName}.config.toml`),
153
+ };
154
+ await mkdir(destination.home, { recursive: true });
155
+ await withFileLock(["genie-code-config", destination.configPath], async () => {
156
+ const projects = await existingProjects(destination.configPath);
157
+ await writePrivateToml(destination.configPath, genieCodeBaseConfig(options, projects));
158
+ });
159
+ await writePrivateToml(destination.overlayPath, genieCodeProviderOverlay(options));
160
+ return destination;
161
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Install the pinned multi-file Genie Code runtime under dbx-tools ownership.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { homedir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { bin } from "@dbx-tools/core";
10
+ import { GENIE_CODE_VERSION } from "@dbx-tools/shared-genie-code/options";
11
+
12
+ interface GenieCodeAsset {
13
+ target: string;
14
+ sha256: string;
15
+ }
16
+
17
+ const GENIE_CODE_ASSETS = {
18
+ "darwin:arm64": {
19
+ target: "aarch64-apple-darwin",
20
+ sha256: "78cc7e358c8bfc62d6da26364c762be37fc2e2a10b7e83f21a3b166f901f528e",
21
+ },
22
+ "darwin:x64": {
23
+ target: "x86_64-apple-darwin",
24
+ sha256: "2021b8b27ec3116fc015c1676b5f65c3ce11d57f1dff9c302aae135f6e4f1a5f",
25
+ },
26
+ "linux:arm64": {
27
+ target: "aarch64-unknown-linux-musl",
28
+ sha256: "dfd278c267dde43e1fe7e7d7a0da8d7a1a148cdf3d2004bd30b351645c4fe0a7",
29
+ },
30
+ "linux:x64": {
31
+ target: "x86_64-unknown-linux-musl",
32
+ sha256: "e3d9a55f6d51bdc745eda4744fb827ba1df6dacf1069518f7347a59f48c89430",
33
+ },
34
+ "win32:arm64": {
35
+ target: "aarch64-pc-windows-msvc",
36
+ sha256: "aeac95bd0148f942194270ba932245cec32e98da67292ba7b008bcab675ba7f8",
37
+ },
38
+ "win32:x64": {
39
+ target: "x86_64-pc-windows-msvc",
40
+ sha256: "c9f92c8d60273250262527bca525451501c4e8351e59927a1686c305be29a922",
41
+ },
42
+ } as const satisfies Record<string, GenieCodeAsset>;
43
+
44
+ /** Host overrides used by installation tests and embedded callers. */
45
+ export interface InstallGenieCodeOptions {
46
+ homeDirectory?: string;
47
+ platform?: NodeJS.Platform;
48
+ architecture?: NodeJS.Architecture;
49
+ }
50
+
51
+ /** Resolve the pinned release asset for one supported host. */
52
+ export function genieCodeAsset(
53
+ platform: NodeJS.Platform = process.platform,
54
+ architecture: NodeJS.Architecture = process.arch,
55
+ ): GenieCodeAsset {
56
+ const asset = GENIE_CODE_ASSETS[`${platform}:${architecture}` as keyof typeof GENIE_CODE_ASSETS];
57
+ if (!asset) {
58
+ throw new Error(
59
+ `Genie Code ${GENIE_CODE_VERSION} does not support ${platform}/${architecture}`,
60
+ );
61
+ }
62
+ return asset;
63
+ }
64
+
65
+ /** Install and return the shared Genie Code package entrypoint. */
66
+ export async function installGenieCode(
67
+ options: InstallGenieCodeOptions = {},
68
+ ): Promise<bin.BinContext> {
69
+ const platform = options.platform ?? process.platform;
70
+ const asset = genieCodeAsset(platform, options.architecture ?? process.arch);
71
+ const executable = platform === "win32" ? "genie.exe" : "genie";
72
+ const helper = platform === "win32" ? "genie-code-mode-host.exe" : "genie-code-mode-host";
73
+ const entrypoint = join("bin", executable);
74
+ const root = join(
75
+ options.homeDirectory ?? homedir(),
76
+ ".dbx-tools",
77
+ "genie",
78
+ "releases",
79
+ `${GENIE_CODE_VERSION}-${asset.target}`,
80
+ );
81
+ const destination: bin.BinContext = {
82
+ root,
83
+ binDir: join(root, dirname(entrypoint)),
84
+ path: join(root, entrypoint),
85
+ };
86
+ const url =
87
+ `https://github.com/databricks/genie-code-cli/releases/download/v${GENIE_CODE_VERSION}/` +
88
+ `genie-package-${asset.target}.tar.gz`;
89
+ return bin.ensure(
90
+ "genie",
91
+ { url, sha256: asset.sha256 },
92
+ {
93
+ destination,
94
+ minVersion: "0.1.0",
95
+ versionParser: ({ stdout }) =>
96
+ stdout.trim() === `genie ${GENIE_CODE_VERSION}` ? "0.1.0" : undefined,
97
+ package: {
98
+ entrypoint,
99
+ requiredPaths: ["genie-package.json", join("bin", helper), "genie-path", "genie-resources"],
100
+ },
101
+ },
102
+ );
103
+ }
@@ -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,212 @@
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 concurrently from "concurrently";
22
+ import getPort from "get-port";
23
+
24
+ import { writeGenieCodeConfig, type GenieCodeHome } from "./config.ts";
25
+ import { installGenieCode } from "./install.ts";
26
+ import { RUNNER_OPTIONS_ENV } from "./runner.ts";
27
+
28
+ const logger = log.logger("genie-code");
29
+
30
+ /** Injectable owners used to prepare and supervise managed Genie Code. */
31
+ export interface GenieCodeRuntimeDependencies {
32
+ createAuthClient: typeof auth.client.createAuthClient;
33
+ install: typeof installGenieCode;
34
+ port(options: { host: string; port?: number }): Promise<number>;
35
+ resolveBin(packageReference: string, binName: string): string;
36
+ resolveCodexModel(model: string, profile: string): Promise<string>;
37
+ supervise: typeof concurrently;
38
+ token(): string;
39
+ writeConfig: typeof writeGenieCodeConfig;
40
+ }
41
+
42
+ const DEFAULT_DEPENDENCIES: GenieCodeRuntimeDependencies = {
43
+ createAuthClient: auth.client.createAuthClient,
44
+ install: installGenieCode,
45
+ port: ({ host, port }) => getPort({ host, ...(port ? { port } : {}) }),
46
+ resolveBin: resolveServicePackageBin,
47
+ resolveCodexModel,
48
+ supervise: concurrently,
49
+ token: () => randomBytes(32).toString("base64url"),
50
+ writeConfig: writeGenieCodeConfig,
51
+ };
52
+
53
+ /** Resolve a Genie `--model` value to the Codex catalogue slug the gateway publishes. */
54
+ async function resolveCodexModel(model: string, profile: string): Promise<string> {
55
+ const client = await workspaceClient.createWorkspaceClient({ profile });
56
+ const target = await new DatabricksModelRegistry({ client }).resolve(model, {
57
+ requiresTools: true,
58
+ });
59
+ if (!target) throw new Error(`Genie Code model not found: ${model}`);
60
+ return models.codexModelSlug(target);
61
+ }
62
+
63
+ /** Inputs accepted by managed Genie Code preparation and execution. */
64
+ export interface RunGenieCodeOptions {
65
+ cwd?: string;
66
+ dependencies?: Partial<GenieCodeRuntimeDependencies>;
67
+ genieArgs?: readonly string[];
68
+ options?: GenieCodeOptions;
69
+ }
70
+
71
+ /** Resolved installation, auth, listener, and home for one invocation. */
72
+ export interface PreparedGenieCodeRuntime {
73
+ bearerToken: string;
74
+ gatewayBaseUrl: string;
75
+ gatewayHealthUrl: string;
76
+ gatewayListen: string;
77
+ gatewayPort: number;
78
+ home: GenieCodeHome;
79
+ installation: BinContext;
80
+ model: string;
81
+ profile: string;
82
+ }
83
+
84
+ /** Resolve auth, installation, listener, and configuration before spawning children. */
85
+ export async function prepareGenieCodeRuntime(
86
+ input: RunGenieCodeOptions = {},
87
+ ): Promise<PreparedGenieCodeRuntime> {
88
+ const dependencies = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
89
+ const options = resolveGenieCodeOptions(input.options);
90
+ logger.info("resolving Databricks authentication", {
91
+ requestedProfile: options.profile,
92
+ });
93
+ const authClient = await dependencies.createAuthClient(
94
+ options.profile ? { profile: options.profile } : {},
95
+ );
96
+ const profile = authClient.profile;
97
+ if (!profile) {
98
+ throw new Error("Genie Code requires a configured Databricks profile");
99
+ }
100
+ logger.info("preparing Genie Code runtime", {
101
+ profile,
102
+ model: options.model,
103
+ });
104
+ const installation = await dependencies.install();
105
+ const host = options.gatewayListen.host;
106
+ const requestedPort = options.gatewayListen.port;
107
+ const gatewayPort = await dependencies.port({
108
+ host,
109
+ ...(requestedPort > 0 ? { port: requestedPort } : {}),
110
+ });
111
+ if (requestedPort > 0 && gatewayPort !== requestedPort) {
112
+ throw new Error(`Genie Code gateway port ${requestedPort} is already in use`);
113
+ }
114
+ const model = await dependencies.resolveCodexModel(options.model, profile);
115
+ logger.info("resolved Genie Code model", { requested: options.model, model });
116
+ const urlHost = host.includes(":") ? `[${host}]` : host;
117
+ const gatewayBaseUrl = `http://${urlHost}:${gatewayPort}/v1`;
118
+ const gatewayHealthUrl = `http://${urlHost}:${gatewayPort}/api/healthz`;
119
+ const gatewayListen = `tcp://${urlHost}:${gatewayPort}`;
120
+ const bearerToken = dependencies.token();
121
+ const home = await dependencies.writeConfig({
122
+ bearerToken,
123
+ gatewayBaseUrl,
124
+ model,
125
+ profile,
126
+ projectDirectory: input.cwd ?? process.cwd(),
127
+ });
128
+ return {
129
+ bearerToken,
130
+ gatewayBaseUrl,
131
+ gatewayHealthUrl,
132
+ gatewayListen,
133
+ gatewayPort,
134
+ home,
135
+ installation,
136
+ model,
137
+ profile,
138
+ };
139
+ }
140
+
141
+ function shellExecutable(path: string): string {
142
+ if (process.platform === "win32") return `"${path.replaceAll('"', '""')}"`;
143
+ return `'${path.replaceAll("'", "'\\''")}'`;
144
+ }
145
+
146
+ function childPath(...paths: string[]): string {
147
+ return [...new Set([...paths.map(dirname), process.env.PATH].filter(Boolean))].join(delimiter);
148
+ }
149
+
150
+ /** Run Genie Code and the model gateway until either process exits. */
151
+ export async function runGenieCode(input: RunGenieCodeOptions = {}): Promise<void> {
152
+ const dependencies = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
153
+ const prepared = await prepareGenieCodeRuntime({
154
+ ...input,
155
+ dependencies,
156
+ });
157
+ const gatewayBin = dependencies.resolveBin(import.meta.url, "dbx-model-gateway");
158
+ const runnerBin = dependencies.resolveBin(import.meta.url, "dbx-genie");
159
+ const path = childPath(gatewayBin, runnerBin);
160
+ const runnerOptions: GenieCodeRunnerOptions = {
161
+ executable: prepared.installation.path,
162
+ arguments: ["-p", prepared.home.overlayName, ...(input.genieArgs ?? [])],
163
+ home: prepared.home.home,
164
+ gatewayHealthUrl: prepared.gatewayHealthUrl,
165
+ bearerToken: prepared.bearerToken,
166
+ startupTimeoutMs: 60_000,
167
+ };
168
+ const { result } = dependencies.supervise(
169
+ [
170
+ {
171
+ command: shellExecutable(gatewayBin),
172
+ name: "gateway",
173
+ env: {
174
+ ...process.env,
175
+ PATH: path,
176
+ LISTEN: prepared.gatewayListen,
177
+ DATABRICKS_CONFIG_PROFILE: prepared.profile,
178
+ DBX_TOOLS_MODEL_GATEWAY_BEARER_TOKEN: prepared.bearerToken,
179
+ },
180
+ },
181
+ {
182
+ command: shellExecutable(runnerBin),
183
+ name: "genie",
184
+ env: {
185
+ ...process.env,
186
+ PATH: path,
187
+ DATABRICKS_CONFIG_PROFILE: prepared.profile,
188
+ [RUNNER_OPTIONS_ENV]: JSON.stringify(runnerOptions),
189
+ },
190
+ },
191
+ ],
192
+ {
193
+ cwd: input.cwd ?? process.cwd(),
194
+ raw: true,
195
+ killOthersOn: ["failure", "success"],
196
+ killSignal: "SIGTERM",
197
+ killTimeout: 17_000,
198
+ successCondition: "command-genie",
199
+ },
200
+ );
201
+ logger.info("started Genie Code and model gateway", {
202
+ profile: prepared.profile,
203
+ model: prepared.model,
204
+ gateway: prepared.gatewayBaseUrl,
205
+ home: prepared.home.home,
206
+ });
207
+ try {
208
+ await result;
209
+ } finally {
210
+ await rm(prepared.home.overlayPath, { force: true });
211
+ }
212
+ }
@@ -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",