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