postgresai 0.11.0-alpha.1 → 0.11.0-alpha.10

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