postgresai 0.11.0-alpha.8 → 0.12.0-alpha.13

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,1095 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import * as pkg from "../package.json";
5
+ import * as config from "../lib/config";
6
+ import * as yaml from "js-yaml";
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ import * as os from "os";
10
+ import { spawn, spawnSync, exec, execFile } from "child_process";
11
+ import { promisify } from "util";
12
+ import * as readline from "readline";
13
+ import * as http from "https";
14
+ import { URL } from "url";
15
+ import { startMcpServer } from "../lib/mcp-server";
16
+ import { fetchIssues } from "../lib/issues";
17
+ import { resolveBaseUrls } from "../lib/util";
18
+
19
+ const execPromise = promisify(exec);
20
+ const execFilePromise = promisify(execFile);
21
+
22
+ /**
23
+ * CLI configuration options
24
+ */
25
+ interface CliOptions {
26
+ apiKey?: string;
27
+ apiBaseUrl?: string;
28
+ uiBaseUrl?: string;
29
+ }
30
+
31
+ /**
32
+ * Configuration result
33
+ */
34
+ interface ConfigResult {
35
+ apiKey: string;
36
+ }
37
+
38
+ /**
39
+ * Instance configuration
40
+ */
41
+ interface Instance {
42
+ name: string;
43
+ conn_str?: string;
44
+ preset_metrics?: string;
45
+ custom_metrics?: any;
46
+ is_enabled?: boolean;
47
+ group?: string;
48
+ custom_tags?: Record<string, any>;
49
+ }
50
+
51
+ /**
52
+ * Path resolution result
53
+ */
54
+ interface PathResolution {
55
+ fs: typeof fs;
56
+ path: typeof path;
57
+ projectDir: string;
58
+ composeFile: string;
59
+ instancesFile: string;
60
+ }
61
+
62
+ /**
63
+ * Health check service
64
+ */
65
+ interface HealthService {
66
+ name: string;
67
+ url: string;
68
+ }
69
+
70
+ /**
71
+ * Get configuration from various sources
72
+ * @param opts - Command line options
73
+ * @returns Configuration object
74
+ */
75
+ function getConfig(opts: CliOptions): ConfigResult {
76
+ // Priority order:
77
+ // 1. Command line option (--api-key)
78
+ // 2. Environment variable (PGAI_API_KEY)
79
+ // 3. User-level config file (~/.config/postgresai/config.json)
80
+ // 4. Legacy project-local config (.pgwatch-config)
81
+
82
+ let apiKey = opts.apiKey || process.env.PGAI_API_KEY || "";
83
+
84
+ // Try config file if not provided via CLI or env
85
+ if (!apiKey) {
86
+ const fileConfig = config.readConfig();
87
+ if (!apiKey) apiKey = fileConfig.apiKey || "";
88
+ }
89
+
90
+ return { apiKey };
91
+ }
92
+
93
+ const program = new Command();
94
+
95
+ program
96
+ .name("postgres-ai")
97
+ .description("PostgresAI CLI")
98
+ .version(pkg.version)
99
+ .option("--api-key <key>", "API key (overrides PGAI_API_KEY)")
100
+ .option(
101
+ "--api-base-url <url>",
102
+ "API base URL for backend RPC (overrides PGAI_API_BASE_URL)"
103
+ )
104
+ .option(
105
+ "--ui-base-url <url>",
106
+ "UI base URL for browser routes (overrides PGAI_UI_BASE_URL)"
107
+ );
108
+
109
+ /**
110
+ * Stub function for not implemented commands
111
+ */
112
+ const stub = (name: string) => async (): Promise<void> => {
113
+ // Temporary stubs until Node parity is implemented
114
+ console.error(`${name}: not implemented in Node CLI yet; use bash CLI for now`);
115
+ process.exitCode = 2;
116
+ };
117
+
118
+ /**
119
+ * Resolve project paths
120
+ */
121
+ function resolvePaths(): PathResolution {
122
+ const projectDir = process.cwd();
123
+ const composeFile = path.resolve(projectDir, "docker-compose.yml");
124
+ const instancesFile = path.resolve(projectDir, "instances.yml");
125
+ return { fs, path, projectDir, composeFile, instancesFile };
126
+ }
127
+
128
+ /**
129
+ * Get docker compose command
130
+ */
131
+ function getComposeCmd(): string[] | null {
132
+ const tryCmd = (cmd: string, args: string[]): boolean =>
133
+ spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
134
+ if (tryCmd("docker-compose", ["version"])) return ["docker-compose"];
135
+ if (tryCmd("docker", ["compose", "version"])) return ["docker", "compose"];
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * Run docker compose command
141
+ */
142
+ async function runCompose(args: string[]): Promise<number> {
143
+ const { composeFile } = resolvePaths();
144
+ const cmd = getComposeCmd();
145
+ if (!cmd) {
146
+ console.error("docker compose not found (need docker-compose or docker compose)");
147
+ process.exitCode = 1;
148
+ return 1;
149
+ }
150
+ return new Promise<number>((resolve) => {
151
+ const child = spawn(cmd[0], [...cmd.slice(1), "-f", composeFile, ...args], { stdio: "inherit" });
152
+ child.on("close", (code) => resolve(code || 0));
153
+ });
154
+ }
155
+
156
+ program.command("help", { isDefault: true }).description("show help").action(() => {
157
+ program.outputHelp();
158
+ });
159
+
160
+ // Monitoring services management
161
+ const mon = program.command("mon").description("monitoring services management");
162
+
163
+ mon
164
+ .command("quickstart")
165
+ .description("complete setup (generate config, start monitoring services)")
166
+ .option("--demo", "demo mode", false)
167
+ .action(async () => {
168
+ const code1 = await runCompose(["run", "--rm", "sources-generator"]);
169
+ if (code1 !== 0) {
170
+ process.exitCode = code1;
171
+ return;
172
+ }
173
+ const code2 = await runCompose(["up", "-d"]);
174
+ if (code2 !== 0) process.exitCode = code2;
175
+ });
176
+
177
+ mon
178
+ .command("start")
179
+ .description("start monitoring services")
180
+ .action(async () => {
181
+ const code = await runCompose(["up", "-d"]);
182
+ if (code !== 0) process.exitCode = code;
183
+ });
184
+
185
+ mon
186
+ .command("stop")
187
+ .description("stop monitoring services")
188
+ .action(async () => {
189
+ const code = await runCompose(["down"]);
190
+ if (code !== 0) process.exitCode = code;
191
+ });
192
+
193
+ mon
194
+ .command("restart [service]")
195
+ .description("restart all monitoring services or specific service")
196
+ .action(async (service?: string) => {
197
+ const args = ["restart"];
198
+ if (service) args.push(service);
199
+ const code = await runCompose(args);
200
+ if (code !== 0) process.exitCode = code;
201
+ });
202
+
203
+ mon
204
+ .command("status")
205
+ .description("show monitoring services status")
206
+ .action(async () => {
207
+ const code = await runCompose(["ps"]);
208
+ if (code !== 0) process.exitCode = code;
209
+ });
210
+
211
+ mon
212
+ .command("logs [service]")
213
+ .option("-f, --follow", "follow logs", false)
214
+ .option("--tail <lines>", "number of lines to show from the end of logs", "all")
215
+ .description("show logs for all or specific monitoring service")
216
+ .action(async (service: string | undefined, opts: { follow: boolean; tail: string }) => {
217
+ const args: string[] = ["logs"];
218
+ if (opts.follow) args.push("-f");
219
+ if (opts.tail) args.push("--tail", opts.tail);
220
+ if (service) args.push(service);
221
+ const code = await runCompose(args);
222
+ if (code !== 0) process.exitCode = code;
223
+ });
224
+ mon
225
+ .command("health")
226
+ .description("health check for monitoring services")
227
+ .option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0)
228
+ .action(async (opts: { wait: number }) => {
229
+ const services: HealthService[] = [
230
+ { name: "Grafana", url: "http://localhost:3000/api/health" },
231
+ { name: "Prometheus", url: "http://localhost:59090/-/healthy" },
232
+ { name: "PGWatch (Postgres)", url: "http://localhost:58080/health" },
233
+ { name: "PGWatch (Prometheus)", url: "http://localhost:58089/health" },
234
+ ];
235
+
236
+ const waitTime = opts.wait || 0;
237
+ const maxAttempts = waitTime > 0 ? Math.ceil(waitTime / 5) : 1;
238
+
239
+ console.log("Checking service health...\n");
240
+
241
+ let allHealthy = false;
242
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
243
+ if (attempt > 1) {
244
+ console.log(`Retrying (attempt ${attempt}/${maxAttempts})...\n`);
245
+ await new Promise(resolve => setTimeout(resolve, 5000));
246
+ }
247
+
248
+ allHealthy = true;
249
+ for (const service of services) {
250
+ try {
251
+ const { stdout } = await execPromise(
252
+ `curl -sf -o /dev/null -w "%{http_code}" ${service.url}`,
253
+ { timeout: 5000 }
254
+ );
255
+ const code = stdout.trim();
256
+ if (code === "200") {
257
+ console.log(`✓ ${service.name}: healthy`);
258
+ } else {
259
+ console.log(`✗ ${service.name}: unhealthy (HTTP ${code})`);
260
+ allHealthy = false;
261
+ }
262
+ } catch (error) {
263
+ console.log(`✗ ${service.name}: unreachable`);
264
+ allHealthy = false;
265
+ }
266
+ }
267
+
268
+ if (allHealthy) {
269
+ break;
270
+ }
271
+ }
272
+
273
+ console.log("");
274
+ if (allHealthy) {
275
+ console.log("All services are healthy");
276
+ } else {
277
+ console.log("Some services are unhealthy");
278
+ process.exitCode = 1;
279
+ }
280
+ });
281
+ mon
282
+ .command("config")
283
+ .description("show monitoring services configuration")
284
+ .action(async () => {
285
+ const { fs, projectDir, composeFile, instancesFile } = resolvePaths();
286
+ console.log(`Project Directory: ${projectDir}`);
287
+ console.log(`Docker Compose File: ${composeFile}`);
288
+ console.log(`Instances File: ${instancesFile}`);
289
+ if (fs.existsSync(instancesFile)) {
290
+ console.log("\nInstances configuration:\n");
291
+ const text = fs.readFileSync(instancesFile, "utf8");
292
+ process.stdout.write(text);
293
+ if (!/\n$/.test(text)) console.log();
294
+ }
295
+ });
296
+ mon
297
+ .command("update-config")
298
+ .description("apply monitoring services configuration (generate sources)")
299
+ .action(async () => {
300
+ const code = await runCompose(["run", "--rm", "sources-generator"]);
301
+ if (code !== 0) process.exitCode = code;
302
+ });
303
+ mon
304
+ .command("update")
305
+ .description("update monitoring stack")
306
+ .action(async () => {
307
+ console.log("Updating PostgresAI monitoring stack...\n");
308
+
309
+ try {
310
+ // Check if we're in a git repo
311
+ const gitDir = path.resolve(process.cwd(), ".git");
312
+ if (!fs.existsSync(gitDir)) {
313
+ console.error("Not a git repository. Cannot update.");
314
+ process.exitCode = 1;
315
+ return;
316
+ }
317
+
318
+ // Fetch latest changes
319
+ console.log("Fetching latest changes...");
320
+ await execPromise("git fetch origin");
321
+
322
+ // Check current branch
323
+ const { stdout: branch } = await execPromise("git rev-parse --abbrev-ref HEAD");
324
+ const currentBranch = branch.trim();
325
+ console.log(`Current branch: ${currentBranch}`);
326
+
327
+ // Pull latest changes
328
+ console.log("Pulling latest changes...");
329
+ const { stdout: pullOut } = await execPromise("git pull origin " + currentBranch);
330
+ console.log(pullOut);
331
+
332
+ // Update Docker images
333
+ console.log("\nUpdating Docker images...");
334
+ const code = await runCompose(["pull"]);
335
+
336
+ if (code === 0) {
337
+ console.log("\n✓ Update completed successfully");
338
+ console.log("\nTo apply updates, restart monitoring services:");
339
+ console.log(" postgres-ai mon restart");
340
+ } else {
341
+ console.error("\n✗ Docker image update failed");
342
+ process.exitCode = 1;
343
+ }
344
+ } catch (error) {
345
+ const message = error instanceof Error ? error.message : String(error);
346
+ console.error(`Update failed: ${message}`);
347
+ process.exitCode = 1;
348
+ }
349
+ });
350
+ mon
351
+ .command("reset [service]")
352
+ .description("reset all or specific monitoring service")
353
+ .action(async (service?: string) => {
354
+ const rl = readline.createInterface({
355
+ input: process.stdin,
356
+ output: process.stdout,
357
+ });
358
+
359
+ const question = (prompt: string): Promise<string> =>
360
+ new Promise((resolve) => rl.question(prompt, resolve));
361
+
362
+ try {
363
+ if (service) {
364
+ // Reset specific service
365
+ console.log(`\nThis will stop '${service}', remove its volume, and restart it.`);
366
+ console.log("All data for this service will be lost!\n");
367
+
368
+ const answer = await question("Continue? (y/N): ");
369
+ if (answer.toLowerCase() !== "y") {
370
+ console.log("Cancelled");
371
+ rl.close();
372
+ return;
373
+ }
374
+
375
+ console.log(`\nStopping ${service}...`);
376
+ await runCompose(["stop", service]);
377
+
378
+ console.log(`Removing volume for ${service}...`);
379
+ await runCompose(["rm", "-f", "-v", service]);
380
+
381
+ console.log(`Restarting ${service}...`);
382
+ const code = await runCompose(["up", "-d", service]);
383
+
384
+ if (code === 0) {
385
+ console.log(`\n✓ Service '${service}' has been reset`);
386
+ } else {
387
+ console.error(`\n✗ Failed to restart '${service}'`);
388
+ process.exitCode = 1;
389
+ }
390
+ } else {
391
+ // Reset all services
392
+ console.log("\nThis will stop all services and remove all data!");
393
+ console.log("Volumes, networks, and containers will be deleted.\n");
394
+
395
+ const answer = await question("Continue? (y/N): ");
396
+ if (answer.toLowerCase() !== "y") {
397
+ console.log("Cancelled");
398
+ rl.close();
399
+ return;
400
+ }
401
+
402
+ console.log("\nStopping services and removing data...");
403
+ const downCode = await runCompose(["down", "-v"]);
404
+
405
+ if (downCode === 0) {
406
+ console.log("✓ Environment reset completed - all containers and data removed");
407
+ } else {
408
+ console.error("✗ Reset failed");
409
+ process.exitCode = 1;
410
+ }
411
+ }
412
+
413
+ rl.close();
414
+ } catch (error) {
415
+ rl.close();
416
+ const message = error instanceof Error ? error.message : String(error);
417
+ console.error(`Reset failed: ${message}`);
418
+ process.exitCode = 1;
419
+ }
420
+ });
421
+ mon
422
+ .command("clean")
423
+ .description("cleanup monitoring services artifacts")
424
+ .action(async () => {
425
+ console.log("Cleaning up Docker resources...\n");
426
+
427
+ try {
428
+ // Remove stopped containers
429
+ const { stdout: containers } = await execFilePromise("docker", ["ps", "-aq", "--filter", "status=exited"]);
430
+ if (containers.trim()) {
431
+ const containerIds = containers.trim().split('\n');
432
+ await execFilePromise("docker", ["rm", ...containerIds]);
433
+ console.log("✓ Removed stopped containers");
434
+ } else {
435
+ console.log("✓ No stopped containers to remove");
436
+ }
437
+
438
+ // Remove unused volumes
439
+ await execFilePromise("docker", ["volume", "prune", "-f"]);
440
+ console.log("✓ Removed unused volumes");
441
+
442
+ // Remove unused networks
443
+ await execFilePromise("docker", ["network", "prune", "-f"]);
444
+ console.log("✓ Removed unused networks");
445
+
446
+ // Remove dangling images
447
+ await execFilePromise("docker", ["image", "prune", "-f"]);
448
+ console.log("✓ Removed dangling images");
449
+
450
+ console.log("\nCleanup completed");
451
+ } catch (error) {
452
+ const message = error instanceof Error ? error.message : String(error);
453
+ console.error(`Error during cleanup: ${message}`);
454
+ process.exitCode = 1;
455
+ }
456
+ });
457
+ mon
458
+ .command("shell <service>")
459
+ .description("open shell to monitoring service")
460
+ .action(async (service: string) => {
461
+ const code = await runCompose(["exec", service, "/bin/sh"]);
462
+ if (code !== 0) process.exitCode = code;
463
+ });
464
+ mon
465
+ .command("check")
466
+ .description("monitoring services system readiness check")
467
+ .action(async () => {
468
+ const code = await runCompose(["ps"]);
469
+ if (code !== 0) process.exitCode = code;
470
+ });
471
+
472
+ // Monitoring targets (databases to monitor)
473
+ const targets = mon.command("targets").description("manage databases to monitor");
474
+
475
+ targets
476
+ .command("list")
477
+ .description("list monitoring target databases")
478
+ .action(async () => {
479
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
480
+ if (!fs.existsSync(instancesPath)) {
481
+ console.error(`instances.yml not found in ${process.cwd()}`);
482
+ process.exitCode = 1;
483
+ return;
484
+ }
485
+
486
+ try {
487
+ const content = fs.readFileSync(instancesPath, "utf8");
488
+ const instances = yaml.load(content) as Instance[] | null;
489
+
490
+ if (!instances || !Array.isArray(instances) || instances.length === 0) {
491
+ console.log("No monitoring targets configured");
492
+ console.log("");
493
+ console.log("To add a monitoring target:");
494
+ console.log(" postgres-ai mon targets add <connection-string> <name>");
495
+ console.log("");
496
+ console.log("Example:");
497
+ console.log(" postgres-ai mon targets add 'postgresql://user:pass@host:5432/db' my-db");
498
+ return;
499
+ }
500
+
501
+ // Filter out demo placeholder
502
+ const filtered = instances.filter((inst) => inst.name && inst.name !== "target-database");
503
+
504
+ if (filtered.length === 0) {
505
+ console.log("No monitoring targets configured");
506
+ console.log("");
507
+ console.log("To add a monitoring target:");
508
+ console.log(" postgres-ai mon targets add <connection-string> <name>");
509
+ console.log("");
510
+ console.log("Example:");
511
+ console.log(" postgres-ai mon targets add 'postgresql://user:pass@host:5432/db' my-db");
512
+ return;
513
+ }
514
+
515
+ for (const inst of filtered) {
516
+ console.log(`Target: ${inst.name}`);
517
+ }
518
+ } catch (err) {
519
+ const message = err instanceof Error ? err.message : String(err);
520
+ console.error(`Error parsing instances.yml: ${message}`);
521
+ process.exitCode = 1;
522
+ }
523
+ });
524
+ targets
525
+ .command("add [connStr] [name]")
526
+ .description("add monitoring target database")
527
+ .action(async (connStr?: string, name?: string) => {
528
+ const file = path.resolve(process.cwd(), "instances.yml");
529
+ if (!connStr) {
530
+ console.error("Connection string required: postgresql://user:pass@host:port/db");
531
+ process.exitCode = 1;
532
+ return;
533
+ }
534
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
535
+ if (!m) {
536
+ console.error("Invalid connection string format");
537
+ process.exitCode = 1;
538
+ return;
539
+ }
540
+ const host = m[3];
541
+ const db = m[5];
542
+ const instanceName = name && name.trim() ? name.trim() : `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
543
+
544
+ // Check if instance already exists
545
+ try {
546
+ if (fs.existsSync(file)) {
547
+ const content = fs.readFileSync(file, "utf8");
548
+ const instances = yaml.load(content) as Instance[] | null || [];
549
+ if (Array.isArray(instances)) {
550
+ const exists = instances.some((inst) => inst.name === instanceName);
551
+ if (exists) {
552
+ console.error(`Monitoring target '${instanceName}' already exists`);
553
+ process.exitCode = 1;
554
+ return;
555
+ }
556
+ }
557
+ }
558
+ } catch (err) {
559
+ // If YAML parsing fails, fall back to simple check
560
+ const content = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
561
+ if (new RegExp(`^- name: ${instanceName}$`, "m").test(content)) {
562
+ console.error(`Monitoring target '${instanceName}' already exists`);
563
+ process.exitCode = 1;
564
+ return;
565
+ }
566
+ }
567
+
568
+ // Add new instance
569
+ const body = `- name: ${instanceName}\n conn_str: ${connStr}\n preset_metrics: full\n custom_metrics:\n is_enabled: true\n group: default\n custom_tags:\n env: production\n cluster: default\n node_name: ${instanceName}\n sink_type: ~sink_type~\n`;
570
+ const content = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
571
+ fs.appendFileSync(file, (content && !/\n$/.test(content) ? "\n" : "") + body, "utf8");
572
+ console.log(`Monitoring target '${instanceName}' added`);
573
+ });
574
+ targets
575
+ .command("remove <name>")
576
+ .description("remove monitoring target database")
577
+ .action(async (name: string) => {
578
+ const file = path.resolve(process.cwd(), "instances.yml");
579
+ if (!fs.existsSync(file)) {
580
+ console.error("instances.yml not found");
581
+ process.exitCode = 1;
582
+ return;
583
+ }
584
+
585
+ try {
586
+ const content = fs.readFileSync(file, "utf8");
587
+ const instances = yaml.load(content) as Instance[] | null;
588
+
589
+ if (!instances || !Array.isArray(instances)) {
590
+ console.error("Invalid instances.yml format");
591
+ process.exitCode = 1;
592
+ return;
593
+ }
594
+
595
+ const filtered = instances.filter((inst) => inst.name !== name);
596
+
597
+ if (filtered.length === instances.length) {
598
+ console.error(`Monitoring target '${name}' not found`);
599
+ process.exitCode = 1;
600
+ return;
601
+ }
602
+
603
+ fs.writeFileSync(file, yaml.dump(filtered), "utf8");
604
+ console.log(`Monitoring target '${name}' removed`);
605
+ } catch (err) {
606
+ const message = err instanceof Error ? err.message : String(err);
607
+ console.error(`Error processing instances.yml: ${message}`);
608
+ process.exitCode = 1;
609
+ }
610
+ });
611
+ targets
612
+ .command("test <name>")
613
+ .description("test monitoring target database connectivity")
614
+ .action(async (name: string) => {
615
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
616
+ if (!fs.existsSync(instancesPath)) {
617
+ console.error("instances.yml not found");
618
+ process.exitCode = 1;
619
+ return;
620
+ }
621
+
622
+ try {
623
+ const content = fs.readFileSync(instancesPath, "utf8");
624
+ const instances = yaml.load(content) as Instance[] | null;
625
+
626
+ if (!instances || !Array.isArray(instances)) {
627
+ console.error("Invalid instances.yml format");
628
+ process.exitCode = 1;
629
+ return;
630
+ }
631
+
632
+ const instance = instances.find((inst) => inst.name === name);
633
+
634
+ if (!instance) {
635
+ console.error(`Monitoring target '${name}' not found`);
636
+ process.exitCode = 1;
637
+ return;
638
+ }
639
+
640
+ if (!instance.conn_str) {
641
+ console.error(`Connection string not found for monitoring target '${name}'`);
642
+ process.exitCode = 1;
643
+ return;
644
+ }
645
+
646
+ console.log(`Testing connection to monitoring target '${name}'...`);
647
+
648
+ const { stdout, stderr } = await execFilePromise(
649
+ "psql",
650
+ [instance.conn_str, "-c", "SELECT version();", "--no-psqlrc"],
651
+ { timeout: 10000, env: { ...process.env, PAGER: 'cat' } }
652
+ );
653
+ console.log(`✓ Connection successful`);
654
+ console.log(stdout.trim());
655
+ } catch (error) {
656
+ const message = error instanceof Error ? error.message : String(error);
657
+ console.error(`✗ Connection failed: ${message}`);
658
+ process.exitCode = 1;
659
+ }
660
+ });
661
+
662
+ // Authentication and API key management
663
+ program
664
+ .command("auth")
665
+ .description("authenticate via browser and obtain API key")
666
+ .option("--port <port>", "local callback server port (default: random)", parseInt)
667
+ .option("--debug", "enable debug output")
668
+ .action(async (opts: { port?: number; debug?: boolean }) => {
669
+ const pkce = require("../lib/pkce");
670
+ const authServer = require("../lib/auth-server");
671
+
672
+ console.log("Starting authentication flow...\n");
673
+
674
+ // Generate PKCE parameters
675
+ const params = pkce.generatePKCEParams();
676
+
677
+ const rootOpts = program.opts<CliOptions>();
678
+ const cfg = config.readConfig();
679
+ const { apiBaseUrl, uiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
680
+
681
+ if (opts.debug) {
682
+ console.log(`Debug: Resolved API base URL: ${apiBaseUrl}`);
683
+ console.log(`Debug: Resolved UI base URL: ${uiBaseUrl}`);
684
+ }
685
+
686
+ try {
687
+ // Step 1: Start local callback server FIRST to get actual port
688
+ console.log("Starting local callback server...");
689
+ const requestedPort = opts.port || 0; // 0 = OS assigns available port
690
+ const callbackServer = authServer.createCallbackServer(requestedPort, params.state, 120000); // 2 minute timeout
691
+
692
+ // Wait a bit for server to start and get port
693
+ await new Promise(resolve => setTimeout(resolve, 100));
694
+ const actualPort = callbackServer.getPort();
695
+ const redirectUri = `http://localhost:${actualPort}/callback`;
696
+
697
+ console.log(`Callback server listening on port ${actualPort}`);
698
+
699
+ // Step 2: Initialize OAuth session on backend
700
+ console.log("Initializing authentication session...");
701
+ const initData = JSON.stringify({
702
+ client_type: "cli",
703
+ state: params.state,
704
+ code_challenge: params.codeChallenge,
705
+ code_challenge_method: params.codeChallengeMethod,
706
+ redirect_uri: redirectUri,
707
+ });
708
+
709
+ // Build init URL by appending to the API base path (keep /api/general)
710
+ const initUrl = new URL(`${apiBaseUrl}/rpc/oauth_init`);
711
+
712
+ if (opts.debug) {
713
+ console.log(`Debug: Trying to POST to: ${initUrl.toString()}`);
714
+ console.log(`Debug: Request data: ${initData}`);
715
+ }
716
+
717
+ const initReq = http.request(
718
+ initUrl,
719
+ {
720
+ method: "POST",
721
+ headers: {
722
+ "Content-Type": "application/json",
723
+ "Content-Length": Buffer.byteLength(initData),
724
+ },
725
+ },
726
+ (res) => {
727
+ let data = "";
728
+ res.on("data", (chunk) => (data += chunk));
729
+ res.on("end", async () => {
730
+ if (res.statusCode !== 200) {
731
+ console.error(`Failed to initialize auth session: ${res.statusCode}`);
732
+
733
+ // Check if response is HTML (common for 404 pages)
734
+ if (data.trim().startsWith("<!") || data.trim().startsWith("<html")) {
735
+ console.error("Error: Received HTML response instead of JSON. This usually means:");
736
+ console.error(" 1. The API endpoint URL is incorrect");
737
+ console.error(" 2. The endpoint does not exist (404)");
738
+ console.error(`\nAPI URL attempted: ${initUrl.toString()}`);
739
+ console.error("\nPlease verify the --api-base-url parameter.");
740
+ } else {
741
+ console.error(data);
742
+ }
743
+
744
+ callbackServer.server.close();
745
+ process.exit(1);
746
+ }
747
+
748
+ // Step 3: Open browser
749
+ const authUrl = `${uiBaseUrl}/cli/auth?state=${encodeURIComponent(params.state)}&code_challenge=${encodeURIComponent(params.codeChallenge)}&code_challenge_method=S256&redirect_uri=${encodeURIComponent(redirectUri)}`;
750
+
751
+ if (opts.debug) {
752
+ console.log(`Debug: Auth URL: ${authUrl}`);
753
+ }
754
+
755
+ console.log(`\nOpening browser for authentication...`);
756
+ console.log(`If browser does not open automatically, visit:\n${authUrl}\n`);
757
+
758
+ // Open browser (cross-platform)
759
+ const openCommand = process.platform === "darwin" ? "open" :
760
+ process.platform === "win32" ? "start" :
761
+ "xdg-open";
762
+ spawn(openCommand, [authUrl], { detached: true, stdio: "ignore" }).unref();
763
+
764
+ // Step 4: Wait for callback
765
+ console.log("Waiting for authorization...");
766
+ console.log("(Press Ctrl+C to cancel)\n");
767
+
768
+ // Handle Ctrl+C gracefully
769
+ const cancelHandler = () => {
770
+ console.log("\n\nAuthentication cancelled by user.");
771
+ callbackServer.server.close();
772
+ process.exit(130); // Standard exit code for SIGINT
773
+ };
774
+ process.on("SIGINT", cancelHandler);
775
+
776
+ try {
777
+ const { code } = await callbackServer.promise;
778
+
779
+ // Remove the cancel handler after successful auth
780
+ process.off("SIGINT", cancelHandler);
781
+
782
+ // Step 5: Exchange code for token
783
+ console.log("\nExchanging authorization code for API token...");
784
+ const exchangeData = JSON.stringify({
785
+ authorization_code: code,
786
+ code_verifier: params.codeVerifier,
787
+ state: params.state,
788
+ });
789
+ const exchangeUrl = new URL(`${apiBaseUrl}/rpc/oauth_token_exchange`);
790
+ const exchangeReq = http.request(
791
+ exchangeUrl,
792
+ {
793
+ method: "POST",
794
+ headers: {
795
+ "Content-Type": "application/json",
796
+ "Content-Length": Buffer.byteLength(exchangeData),
797
+ },
798
+ },
799
+ (exchangeRes) => {
800
+ let exchangeBody = "";
801
+ exchangeRes.on("data", (chunk) => (exchangeBody += chunk));
802
+ exchangeRes.on("end", () => {
803
+ if (exchangeRes.statusCode !== 200) {
804
+ console.error(`Failed to exchange code for token: ${exchangeRes.statusCode}`);
805
+
806
+ // Check if response is HTML (common for 404 pages)
807
+ if (exchangeBody.trim().startsWith("<!") || exchangeBody.trim().startsWith("<html")) {
808
+ console.error("Error: Received HTML response instead of JSON. This usually means:");
809
+ console.error(" 1. The API endpoint URL is incorrect");
810
+ console.error(" 2. The endpoint does not exist (404)");
811
+ console.error(`\nAPI URL attempted: ${exchangeUrl.toString()}`);
812
+ console.error("\nPlease verify the --api-base-url parameter.");
813
+ } else {
814
+ console.error(exchangeBody);
815
+ }
816
+
817
+ process.exit(1);
818
+ return;
819
+ }
820
+
821
+ try {
822
+ const result = JSON.parse(exchangeBody);
823
+ const apiToken = result.api_token || result?.[0]?.result?.api_token; // There is a bug with PostgREST Caching that may return an array, not single object, it's a workaround to support both cases.
824
+ const orgId = result.org_id || result?.[0]?.result?.org_id; // There is a bug with PostgREST Caching that may return an array, not single object, it's a workaround to support both cases.
825
+
826
+ // Step 6: Save token to config
827
+ config.writeConfig({
828
+ apiKey: apiToken,
829
+ baseUrl: apiBaseUrl,
830
+ orgId: orgId,
831
+ });
832
+
833
+ console.log("\nAuthentication successful!");
834
+ console.log(`API key saved to: ${config.getConfigPath()}`);
835
+ console.log(`Organization ID: ${orgId}`);
836
+ console.log(`\nYou can now use the CLI without specifying an API key.`);
837
+ process.exit(0);
838
+ } catch (err) {
839
+ const message = err instanceof Error ? err.message : String(err);
840
+ console.error(`Failed to parse response: ${message}`);
841
+ process.exit(1);
842
+ }
843
+ });
844
+ }
845
+ );
846
+
847
+ exchangeReq.on("error", (err: Error) => {
848
+ console.error(`Exchange request failed: ${err.message}`);
849
+ process.exit(1);
850
+ });
851
+
852
+ exchangeReq.write(exchangeData);
853
+ exchangeReq.end();
854
+
855
+ } catch (err) {
856
+ // Remove the cancel handler in error case too
857
+ process.off("SIGINT", cancelHandler);
858
+
859
+ const message = err instanceof Error ? err.message : String(err);
860
+
861
+ // Provide more helpful error messages
862
+ if (message.includes("timeout")) {
863
+ console.error(`\nAuthentication timed out.`);
864
+ console.error(`This usually means you closed the browser window without completing authentication.`);
865
+ console.error(`Please try again and complete the authentication flow.`);
866
+ } else {
867
+ console.error(`\nAuthentication failed: ${message}`);
868
+ }
869
+
870
+ process.exit(1);
871
+ }
872
+ });
873
+ }
874
+ );
875
+
876
+ initReq.on("error", (err: Error) => {
877
+ console.error(`Failed to connect to API: ${err.message}`);
878
+ callbackServer.server.close();
879
+ process.exit(1);
880
+ });
881
+
882
+ initReq.write(initData);
883
+ initReq.end();
884
+
885
+ } catch (err) {
886
+ const message = err instanceof Error ? err.message : String(err);
887
+ console.error(`Authentication error: ${message}`);
888
+ process.exit(1);
889
+ }
890
+ });
891
+
892
+ program
893
+ .command("add-key <apiKey>")
894
+ .description("store API key")
895
+ .action(async (apiKey: string) => {
896
+ config.writeConfig({ apiKey });
897
+ console.log(`API key saved to ${config.getConfigPath()}`);
898
+ });
899
+
900
+ program
901
+ .command("show-key")
902
+ .description("show API key (masked)")
903
+ .action(async () => {
904
+ const cfg = config.readConfig();
905
+ if (!cfg.apiKey) {
906
+ console.log("No API key configured");
907
+ console.log(`\nTo authenticate, run: pgai auth`);
908
+ return;
909
+ }
910
+ const { maskSecret } = require("../lib/util");
911
+ console.log(`Current API key: ${maskSecret(cfg.apiKey)}`);
912
+ if (cfg.orgId) {
913
+ console.log(`Organization ID: ${cfg.orgId}`);
914
+ }
915
+ console.log(`Config location: ${config.getConfigPath()}`);
916
+ });
917
+
918
+ program
919
+ .command("remove-key")
920
+ .description("remove API key")
921
+ .action(async () => {
922
+ // Check both new config and legacy config
923
+ const newConfigPath = config.getConfigPath();
924
+ const hasNewConfig = fs.existsSync(newConfigPath);
925
+ const legacyPath = path.resolve(process.cwd(), ".pgwatch-config");
926
+ const hasLegacyConfig = fs.existsSync(legacyPath) && fs.statSync(legacyPath).isFile();
927
+
928
+ if (!hasNewConfig && !hasLegacyConfig) {
929
+ console.log("No API key configured");
930
+ return;
931
+ }
932
+
933
+ // Remove from new config
934
+ if (hasNewConfig) {
935
+ config.deleteConfigKeys(["apiKey", "orgId"]);
936
+ }
937
+
938
+ // Remove from legacy config
939
+ if (hasLegacyConfig) {
940
+ try {
941
+ const content = fs.readFileSync(legacyPath, "utf8");
942
+ const filtered = content
943
+ .split(/\r?\n/)
944
+ .filter((l) => !/^api_key=/.test(l))
945
+ .join("\n")
946
+ .replace(/\n+$/g, "\n");
947
+ fs.writeFileSync(legacyPath, filtered, "utf8");
948
+ } catch (err) {
949
+ // If we can't read/write the legacy config, just skip it
950
+ console.warn(`Warning: Could not update legacy config: ${err instanceof Error ? err.message : String(err)}`);
951
+ }
952
+ }
953
+
954
+ console.log("API key removed");
955
+ console.log(`\nTo authenticate again, run: pgai auth`);
956
+ });
957
+ mon
958
+ .command("generate-grafana-password")
959
+ .description("generate Grafana password for monitoring services")
960
+ .action(async () => {
961
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
962
+
963
+ try {
964
+ // Generate secure password using openssl
965
+ const { stdout: password } = await execPromise(
966
+ "openssl rand -base64 12 | tr -d '\n'"
967
+ );
968
+ const newPassword = password.trim();
969
+
970
+ if (!newPassword) {
971
+ console.error("Failed to generate password");
972
+ process.exitCode = 1;
973
+ return;
974
+ }
975
+
976
+ // Read existing config
977
+ let configContent = "";
978
+ if (fs.existsSync(cfgPath)) {
979
+ const stats = fs.statSync(cfgPath);
980
+ if (stats.isDirectory()) {
981
+ console.error(".pgwatch-config is a directory, expected a file. Skipping read.");
982
+ } else {
983
+ configContent = fs.readFileSync(cfgPath, "utf8");
984
+ }
985
+ }
986
+
987
+ // Update or add grafana_password
988
+ const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
989
+ lines.push(`grafana_password=${newPassword}`);
990
+
991
+ // Write back
992
+ fs.writeFileSync(cfgPath, lines.filter(Boolean).join("\n") + "\n", "utf8");
993
+
994
+ console.log("✓ New Grafana password generated and saved");
995
+ console.log("\nNew credentials:");
996
+ console.log(" URL: http://localhost:3000");
997
+ console.log(" Username: monitor");
998
+ console.log(` Password: ${newPassword}`);
999
+ console.log("\nReset Grafana to apply new password:");
1000
+ console.log(" postgres-ai mon reset grafana");
1001
+ } catch (error) {
1002
+ const message = error instanceof Error ? error.message : String(error);
1003
+ console.error(`Failed to generate password: ${message}`);
1004
+ console.error("\nNote: This command requires 'openssl' to be installed");
1005
+ process.exitCode = 1;
1006
+ }
1007
+ });
1008
+ mon
1009
+ .command("show-grafana-credentials")
1010
+ .description("show Grafana credentials for monitoring services")
1011
+ .action(async () => {
1012
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
1013
+ if (!fs.existsSync(cfgPath)) {
1014
+ console.error("Configuration file not found. Run 'postgres-ai mon quickstart' first.");
1015
+ process.exitCode = 1;
1016
+ return;
1017
+ }
1018
+
1019
+ const stats = fs.statSync(cfgPath);
1020
+ if (stats.isDirectory()) {
1021
+ console.error(".pgwatch-config is a directory, expected a file. Cannot read credentials.");
1022
+ process.exitCode = 1;
1023
+ return;
1024
+ }
1025
+
1026
+ const content = fs.readFileSync(cfgPath, "utf8");
1027
+ const lines = content.split(/\r?\n/);
1028
+ let password = "";
1029
+ for (const line of lines) {
1030
+ const m = line.match(/^grafana_password=(.+)$/);
1031
+ if (m) {
1032
+ password = m[1].trim();
1033
+ break;
1034
+ }
1035
+ }
1036
+ if (!password) {
1037
+ console.error("Grafana password not found in configuration");
1038
+ process.exitCode = 1;
1039
+ return;
1040
+ }
1041
+ console.log("\nGrafana credentials:");
1042
+ console.log(" URL: http://localhost:3000");
1043
+ console.log(" Username: monitor");
1044
+ console.log(` Password: ${password}`);
1045
+ console.log("");
1046
+ });
1047
+
1048
+ // Issues management
1049
+ const issues = program.command("issues").description("issues management");
1050
+
1051
+ issues
1052
+ .command("list")
1053
+ .description("list issues")
1054
+ .option("--debug", "enable debug output")
1055
+ .action(async (opts: { debug?: boolean }) => {
1056
+ try {
1057
+ const rootOpts = program.opts<CliOptions>();
1058
+ const cfg = config.readConfig();
1059
+ const { apiKey } = getConfig(rootOpts);
1060
+ if (!apiKey) {
1061
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1062
+ process.exitCode = 1;
1063
+ return;
1064
+ }
1065
+
1066
+ const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
1067
+
1068
+ const result = await fetchIssues({ apiKey, apiBaseUrl, debug: !!opts.debug });
1069
+ if (typeof result === "string") {
1070
+ process.stdout.write(result);
1071
+ if (!/\n$/.test(result)) console.log();
1072
+ } else {
1073
+ console.log(JSON.stringify(result, null, 2));
1074
+ }
1075
+ } catch (err) {
1076
+ const message = err instanceof Error ? err.message : String(err);
1077
+ console.error(message);
1078
+ process.exitCode = 1;
1079
+ }
1080
+ });
1081
+
1082
+ // MCP server
1083
+ const mcp = program.command("mcp").description("MCP server integration");
1084
+
1085
+ mcp
1086
+ .command("start")
1087
+ .description("start MCP stdio server")
1088
+ .option("--debug", "enable debug output")
1089
+ .action(async (opts: { debug?: boolean }) => {
1090
+ const rootOpts = program.opts<CliOptions>();
1091
+ await startMcpServer(rootOpts, { debug: !!opts.debug });
1092
+ });
1093
+
1094
+ program.parseAsync(process.argv);
1095
+