postgresai 0.12.0-beta.6 → 0.14.0-dev.7

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.
@@ -49,6 +49,7 @@ const url_1 = require("url");
49
49
  const mcp_server_1 = require("../lib/mcp-server");
50
50
  const issues_1 = require("../lib/issues");
51
51
  const util_2 = require("../lib/util");
52
+ const init_1 = require("../lib/init");
52
53
  const execPromise = (0, util_1.promisify)(child_process_1.exec);
53
54
  const execFilePromise = (0, util_1.promisify)(child_process_1.execFile);
54
55
  /**
@@ -71,6 +72,25 @@ function getConfig(opts) {
71
72
  }
72
73
  return { apiKey };
73
74
  }
75
+ // Human-friendly output helper: YAML for TTY by default, JSON when --json or non-TTY
76
+ function printResult(result, json) {
77
+ if (typeof result === "string") {
78
+ process.stdout.write(result);
79
+ if (!/\n$/.test(result))
80
+ console.log();
81
+ return;
82
+ }
83
+ if (json || !process.stdout.isTTY) {
84
+ console.log(JSON.stringify(result, null, 2));
85
+ }
86
+ else {
87
+ let text = yaml.dump(result);
88
+ if (Array.isArray(result)) {
89
+ text = text.replace(/\n- /g, "\n\n- ");
90
+ }
91
+ console.log(text);
92
+ }
93
+ }
74
94
  const program = new commander_1.Command();
75
95
  program
76
96
  .name("postgres-ai")
@@ -79,6 +99,109 @@ program
79
99
  .option("--api-key <key>", "API key (overrides PGAI_API_KEY)")
80
100
  .option("--api-base-url <url>", "API base URL for backend RPC (overrides PGAI_API_BASE_URL)")
81
101
  .option("--ui-base-url <url>", "UI base URL for browser routes (overrides PGAI_UI_BASE_URL)");
102
+ program
103
+ .command("init [conn]")
104
+ .description("Create a monitoring user and grant all required permissions (idempotent)")
105
+ .option("--db-url <url>", "PostgreSQL connection URL (admin) to run the setup against (deprecated; pass it as positional arg)")
106
+ .option("-h, --host <host>", "PostgreSQL host (psql-like)")
107
+ .option("-p, --port <port>", "PostgreSQL port (psql-like)")
108
+ .option("-U, --username <username>", "PostgreSQL user (psql-like)")
109
+ .option("-d, --dbname <dbname>", "PostgreSQL database name (psql-like)")
110
+ .option("--admin-password <password>", "Admin connection password (otherwise uses PGPASSWORD if set)")
111
+ .option("--monitoring-user <name>", "Monitoring role name to create/update", "postgres_ai_mon")
112
+ .option("--password <password>", "Monitoring role password (overrides PGAI_MON_PASSWORD)")
113
+ .option("--skip-optional-permissions", "Skip optional permissions (RDS/self-managed extras)", false)
114
+ .action(async (conn, opts) => {
115
+ let adminConn;
116
+ try {
117
+ adminConn = (0, init_1.resolveAdminConnection)({
118
+ conn,
119
+ dbUrlFlag: opts.dbUrl,
120
+ host: opts.host,
121
+ port: opts.port,
122
+ username: opts.username,
123
+ dbname: opts.dbname,
124
+ adminPassword: opts.adminPassword,
125
+ envPassword: process.env.PGPASSWORD,
126
+ });
127
+ }
128
+ catch (e) {
129
+ const msg = e instanceof Error ? e.message : String(e);
130
+ console.error(`✗ ${msg}`);
131
+ process.exitCode = 1;
132
+ return;
133
+ }
134
+ let monPassword;
135
+ try {
136
+ monPassword = await (0, init_1.resolveMonitoringPassword)({
137
+ passwordFlag: opts.password,
138
+ passwordEnv: process.env.PGAI_MON_PASSWORD,
139
+ monitoringUser: opts.monitoringUser,
140
+ });
141
+ }
142
+ catch (e) {
143
+ const msg = e instanceof Error ? e.message : String(e);
144
+ console.error(`✗ ${msg}`);
145
+ process.exitCode = 1;
146
+ return;
147
+ }
148
+ const includeOptionalPermissions = !opts.skipOptionalPermissions;
149
+ console.log(`Connecting to: ${adminConn.display}`);
150
+ console.log(`Monitoring user: ${opts.monitoringUser}`);
151
+ console.log(`Optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
152
+ // Use native pg client instead of requiring psql to be installed
153
+ const { Client } = require("pg");
154
+ const client = new Client(adminConn.clientConfig);
155
+ try {
156
+ await client.connect();
157
+ const roleRes = await client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [
158
+ opts.monitoringUser,
159
+ ]);
160
+ const roleExists = roleRes.rowCount > 0;
161
+ const dbRes = await client.query("select current_database() as db");
162
+ const database = dbRes.rows?.[0]?.db;
163
+ if (typeof database !== "string" || !database) {
164
+ throw new Error("Failed to resolve current database name");
165
+ }
166
+ const plan = await (0, init_1.buildInitPlan)({
167
+ database,
168
+ monitoringUser: opts.monitoringUser,
169
+ monitoringPassword: monPassword,
170
+ includeOptionalPermissions,
171
+ roleExists,
172
+ });
173
+ const { applied, skippedOptional } = await (0, init_1.applyInitPlan)({ client, plan });
174
+ console.log("✓ init completed");
175
+ if (skippedOptional.length > 0) {
176
+ console.log("⚠ Some optional steps were skipped (not supported or insufficient privileges):");
177
+ for (const s of skippedOptional)
178
+ console.log(`- ${s}`);
179
+ }
180
+ // Keep output compact but still useful
181
+ if (process.stdout.isTTY) {
182
+ console.log(`Applied ${applied.length} steps`);
183
+ }
184
+ }
185
+ catch (error) {
186
+ const errAny = error;
187
+ const message = error instanceof Error ? error.message : String(error);
188
+ console.error(`✗ init failed: ${message}`);
189
+ if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
190
+ if (errAny.code === "42501") {
191
+ console.error("Hint: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
192
+ }
193
+ }
194
+ process.exitCode = 1;
195
+ }
196
+ finally {
197
+ try {
198
+ await client.end();
199
+ }
200
+ catch {
201
+ // ignore
202
+ }
203
+ }
204
+ });
82
205
  /**
83
206
  * Stub function for not implemented commands
84
207
  */
@@ -206,23 +329,284 @@ const mon = program.command("mon").description("monitoring services management")
206
329
  mon
207
330
  .command("quickstart")
208
331
  .description("complete setup (generate config, start monitoring services)")
209
- .option("--demo", "demo mode", false)
210
- .action(async () => {
332
+ .option("--demo", "demo mode with sample database", false)
333
+ .option("--api-key <key>", "Postgres AI API key for automated report uploads")
334
+ .option("--db-url <url>", "PostgreSQL connection URL to monitor")
335
+ .option("-y, --yes", "accept all defaults and skip interactive prompts", false)
336
+ .action(async (opts) => {
337
+ console.log("\n=================================");
338
+ console.log(" PostgresAI Monitoring Quickstart");
339
+ console.log("=================================\n");
340
+ console.log("This will install, configure, and start the monitoring system\n");
341
+ // Validate conflicting options
342
+ if (opts.demo && opts.dbUrl) {
343
+ console.log("⚠ Both --demo and --db-url provided. Demo mode includes its own database.");
344
+ console.log("⚠ The --db-url will be ignored in demo mode.\n");
345
+ opts.dbUrl = undefined;
346
+ }
347
+ if (opts.demo && opts.apiKey) {
348
+ console.error("✗ Cannot use --api-key with --demo mode");
349
+ console.error("✗ Demo mode is for testing only and does not support API key integration");
350
+ console.error("\nUse demo mode without API key: postgres-ai mon quickstart --demo");
351
+ console.error("Or use production mode with API key: postgres-ai mon quickstart --api-key=your_key");
352
+ process.exitCode = 1;
353
+ return;
354
+ }
211
355
  // Check if containers are already running
212
356
  const { running, containers } = checkRunningContainers();
213
357
  if (running) {
214
- console.log(`Monitoring services are already running: ${containers.join(", ")}`);
215
- console.log("Use 'postgres-ai mon restart' to restart them");
358
+ console.log(`⚠ Monitoring services are already running: ${containers.join(", ")}`);
359
+ console.log("Use 'postgres-ai mon restart' to restart them\n");
216
360
  return;
217
361
  }
362
+ // Step 1: API key configuration (only in production mode)
363
+ if (!opts.demo) {
364
+ console.log("Step 1: Postgres AI API Configuration (Optional)");
365
+ console.log("An API key enables automatic upload of PostgreSQL reports to Postgres AI\n");
366
+ if (opts.apiKey) {
367
+ console.log("Using API key provided via --api-key parameter");
368
+ config.writeConfig({ apiKey: opts.apiKey });
369
+ console.log("✓ API key saved\n");
370
+ }
371
+ else if (opts.yes) {
372
+ // Auto-yes mode without API key - skip API key setup
373
+ console.log("Auto-yes mode: no API key provided, skipping API key setup");
374
+ console.log("⚠ Reports will be generated locally only");
375
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
376
+ }
377
+ else {
378
+ const rl = readline.createInterface({
379
+ input: process.stdin,
380
+ output: process.stdout
381
+ });
382
+ const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
383
+ try {
384
+ const answer = await question("Do you have a Postgres AI API key? (Y/n): ");
385
+ const proceedWithApiKey = !answer || answer.toLowerCase() === "y";
386
+ if (proceedWithApiKey) {
387
+ while (true) {
388
+ const inputApiKey = await question("Enter your Postgres AI API key: ");
389
+ const trimmedKey = inputApiKey.trim();
390
+ if (trimmedKey) {
391
+ config.writeConfig({ apiKey: trimmedKey });
392
+ console.log("✓ API key saved\n");
393
+ break;
394
+ }
395
+ console.log("⚠ API key cannot be empty");
396
+ const retry = await question("Try again or skip API key setup, retry? (Y/n): ");
397
+ if (retry.toLowerCase() === "n") {
398
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
399
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
400
+ break;
401
+ }
402
+ }
403
+ }
404
+ else {
405
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
406
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
407
+ }
408
+ }
409
+ finally {
410
+ rl.close();
411
+ }
412
+ }
413
+ }
414
+ else {
415
+ console.log("Step 1: Demo mode - API key configuration skipped");
416
+ console.log("Demo mode is for testing only and does not support API key integration\n");
417
+ }
418
+ // Step 2: Add PostgreSQL instance (if not demo mode)
419
+ if (!opts.demo) {
420
+ console.log("Step 2: Add PostgreSQL Instance to Monitor\n");
421
+ // Clear instances.yml in production mode (start fresh)
422
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
423
+ const emptyInstancesContent = "# PostgreSQL instances to monitor\n# Add your instances using: postgres-ai mon targets add\n\n";
424
+ fs.writeFileSync(instancesPath, emptyInstancesContent, "utf8");
425
+ if (opts.dbUrl) {
426
+ console.log("Using database URL provided via --db-url parameter");
427
+ console.log(`Adding PostgreSQL instance from: ${opts.dbUrl}\n`);
428
+ const match = opts.dbUrl.match(/^postgresql:\/\/[^@]+@([^:/]+)/);
429
+ const autoInstanceName = match ? match[1] : "db-instance";
430
+ const connStr = opts.dbUrl;
431
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
432
+ if (!m) {
433
+ console.error("✗ Invalid connection string format");
434
+ process.exitCode = 1;
435
+ return;
436
+ }
437
+ const host = m[3];
438
+ const db = m[5];
439
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
440
+ 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`;
441
+ fs.appendFileSync(instancesPath, body, "utf8");
442
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
443
+ // Test connection
444
+ console.log("Testing connection to the added instance...");
445
+ try {
446
+ const { Client } = require("pg");
447
+ const client = new Client({ connectionString: connStr });
448
+ await client.connect();
449
+ const result = await client.query("select version();");
450
+ console.log("✓ Connection successful");
451
+ console.log(`${result.rows[0].version}\n`);
452
+ await client.end();
453
+ }
454
+ catch (error) {
455
+ const message = error instanceof Error ? error.message : String(error);
456
+ console.error(`✗ Connection failed: ${message}\n`);
457
+ }
458
+ }
459
+ else if (opts.yes) {
460
+ // Auto-yes mode without database URL - skip database setup
461
+ console.log("Auto-yes mode: no database URL provided, skipping database setup");
462
+ console.log("⚠ No PostgreSQL instance added");
463
+ console.log("You can add one later with: postgres-ai mon targets add\n");
464
+ }
465
+ else {
466
+ const rl = readline.createInterface({
467
+ input: process.stdin,
468
+ output: process.stdout
469
+ });
470
+ const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
471
+ try {
472
+ console.log("You need to add at least one PostgreSQL instance to monitor");
473
+ const answer = await question("Do you want to add a PostgreSQL instance now? (Y/n): ");
474
+ const proceedWithInstance = !answer || answer.toLowerCase() === "y";
475
+ if (proceedWithInstance) {
476
+ console.log("\nYou can provide either:");
477
+ console.log(" 1. A full connection string: postgresql://user:pass@host:port/database");
478
+ console.log(" 2. Press Enter to skip for now\n");
479
+ const connStr = await question("Enter connection string (or press Enter to skip): ");
480
+ if (connStr.trim()) {
481
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
482
+ if (!m) {
483
+ console.error("✗ Invalid connection string format");
484
+ console.log("⚠ Continuing without adding instance\n");
485
+ }
486
+ else {
487
+ const host = m[3];
488
+ const db = m[5];
489
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
490
+ 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`;
491
+ fs.appendFileSync(instancesPath, body, "utf8");
492
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
493
+ // Test connection
494
+ console.log("Testing connection to the added instance...");
495
+ try {
496
+ const { Client } = require("pg");
497
+ const client = new Client({ connectionString: connStr });
498
+ await client.connect();
499
+ const result = await client.query("select version();");
500
+ console.log("✓ Connection successful");
501
+ console.log(`${result.rows[0].version}\n`);
502
+ await client.end();
503
+ }
504
+ catch (error) {
505
+ const message = error instanceof Error ? error.message : String(error);
506
+ console.error(`✗ Connection failed: ${message}\n`);
507
+ }
508
+ }
509
+ }
510
+ else {
511
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
512
+ }
513
+ }
514
+ else {
515
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
516
+ }
517
+ }
518
+ finally {
519
+ rl.close();
520
+ }
521
+ }
522
+ }
523
+ else {
524
+ console.log("Step 2: Demo mode enabled - using included demo PostgreSQL database\n");
525
+ }
526
+ // Step 3: Update configuration
527
+ console.log(opts.demo ? "Step 3: Updating configuration..." : "Step 3: Updating configuration...");
218
528
  const code1 = await runCompose(["run", "--rm", "sources-generator"]);
219
529
  if (code1 !== 0) {
220
530
  process.exitCode = code1;
221
531
  return;
222
532
  }
223
- const code2 = await runCompose(["up", "-d"]);
224
- if (code2 !== 0)
533
+ console.log(" Configuration updated\n");
534
+ // Step 4: Ensure Grafana password is configured
535
+ console.log(opts.demo ? "Step 4: Configuring Grafana security..." : "Step 4: Configuring Grafana security...");
536
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
537
+ let grafanaPassword = "";
538
+ try {
539
+ if (fs.existsSync(cfgPath)) {
540
+ const stats = fs.statSync(cfgPath);
541
+ if (!stats.isDirectory()) {
542
+ const content = fs.readFileSync(cfgPath, "utf8");
543
+ const match = content.match(/^grafana_password=([^\r\n]+)/m);
544
+ if (match) {
545
+ grafanaPassword = match[1].trim();
546
+ }
547
+ }
548
+ }
549
+ if (!grafanaPassword) {
550
+ console.log("Generating secure Grafana password...");
551
+ const { stdout: password } = await execPromise("openssl rand -base64 12 | tr -d '\n'");
552
+ grafanaPassword = password.trim();
553
+ let configContent = "";
554
+ if (fs.existsSync(cfgPath)) {
555
+ const stats = fs.statSync(cfgPath);
556
+ if (!stats.isDirectory()) {
557
+ configContent = fs.readFileSync(cfgPath, "utf8");
558
+ }
559
+ }
560
+ const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
561
+ lines.push(`grafana_password=${grafanaPassword}`);
562
+ fs.writeFileSync(cfgPath, lines.filter(Boolean).join("\n") + "\n", "utf8");
563
+ }
564
+ console.log("✓ Grafana password configured\n");
565
+ }
566
+ catch (error) {
567
+ console.log("⚠ Could not generate Grafana password automatically");
568
+ console.log("Using default password: demo\n");
569
+ grafanaPassword = "demo";
570
+ }
571
+ // Step 5: Start services
572
+ console.log(opts.demo ? "Step 5: Starting monitoring services..." : "Step 5: Starting monitoring services...");
573
+ const code2 = await runCompose(["up", "-d", "--force-recreate"]);
574
+ if (code2 !== 0) {
225
575
  process.exitCode = code2;
576
+ return;
577
+ }
578
+ console.log("✓ Services started\n");
579
+ // Final summary
580
+ console.log("=================================");
581
+ console.log(" 🎉 Quickstart setup completed!");
582
+ console.log("=================================\n");
583
+ console.log("What's running:");
584
+ if (opts.demo) {
585
+ console.log(" ✅ Demo PostgreSQL database (monitoring target)");
586
+ }
587
+ console.log(" ✅ PostgreSQL monitoring infrastructure");
588
+ console.log(" ✅ Grafana dashboards (with secure password)");
589
+ console.log(" ✅ Prometheus metrics storage");
590
+ console.log(" ✅ Flask API backend");
591
+ console.log(" ✅ Automated report generation (every 24h)");
592
+ console.log(" ✅ Host stats monitoring (CPU, memory, disk, I/O)\n");
593
+ if (!opts.demo) {
594
+ console.log("Next steps:");
595
+ console.log(" • Add more PostgreSQL instances: postgres-ai mon targets add");
596
+ console.log(" • View configured instances: postgres-ai mon targets list");
597
+ console.log(" • Check service health: postgres-ai mon health\n");
598
+ }
599
+ else {
600
+ console.log("Demo mode next steps:");
601
+ console.log(" • Explore Grafana dashboards at http://localhost:3000");
602
+ console.log(" • Connect to demo database: postgresql://postgres:postgres@localhost:55432/target_database");
603
+ console.log(" • Generate some load on the demo database to see metrics\n");
604
+ }
605
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
606
+ console.log("🚀 MAIN ACCESS POINT - Start here:");
607
+ console.log(" Grafana Dashboard: http://localhost:3000");
608
+ console.log(` Login: monitor / ${grafanaPassword}`);
609
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
226
610
  });
227
611
  mon
228
612
  .command("start")
@@ -289,10 +673,12 @@ mon
289
673
  .option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0)
290
674
  .action(async (opts) => {
291
675
  const services = [
292
- { name: "Grafana", url: "http://localhost:3000/api/health" },
293
- { name: "Prometheus", url: "http://localhost:59090/-/healthy" },
294
- { name: "PGWatch (Postgres)", url: "http://localhost:58080/health" },
295
- { name: "PGWatch (Prometheus)", url: "http://localhost:58089/health" },
676
+ { name: "Grafana", container: "grafana-with-datasources" },
677
+ { name: "Prometheus", container: "sink-prometheus" },
678
+ { name: "PGWatch (Postgres)", container: "pgwatch-postgres" },
679
+ { name: "PGWatch (Prometheus)", container: "pgwatch-prometheus" },
680
+ { name: "Target DB", container: "target-db" },
681
+ { name: "Sink Postgres", container: "sink-postgres" },
296
682
  ];
297
683
  const waitTime = opts.wait || 0;
298
684
  const maxAttempts = waitTime > 0 ? Math.ceil(waitTime / 5) : 1;
@@ -306,19 +692,16 @@ mon
306
692
  allHealthy = true;
307
693
  for (const service of services) {
308
694
  try {
309
- // Use native fetch instead of requiring curl to be installed
310
- const controller = new AbortController();
311
- const timeoutId = setTimeout(() => controller.abort(), 5000);
312
- const response = await fetch(service.url, {
313
- signal: controller.signal,
314
- method: 'GET',
315
- });
316
- clearTimeout(timeoutId);
317
- if (response.status === 200) {
695
+ const { execSync } = require("child_process");
696
+ const status = execSync(`docker inspect -f '{{.State.Status}}' ${service.container} 2>/dev/null`, {
697
+ encoding: 'utf8',
698
+ stdio: ['pipe', 'pipe', 'pipe']
699
+ }).trim();
700
+ if (status === 'running') {
318
701
  console.log(`✓ ${service.name}: healthy`);
319
702
  }
320
703
  else {
321
- console.log(`✗ ${service.name}: unhealthy (HTTP ${response.status})`);
704
+ console.log(`✗ ${service.name}: unhealthy (status: ${status})`);
322
705
  allHealthy = false;
323
706
  }
324
707
  }
@@ -1041,12 +1424,30 @@ mon
1041
1424
  console.log(` Password: ${password}`);
1042
1425
  console.log("");
1043
1426
  });
1427
+ /**
1428
+ * Interpret escape sequences in a string (e.g., \n -> newline)
1429
+ * Note: In regex, to match literal backslash-n, we need \\n in the pattern
1430
+ * which requires \\\\n in the JavaScript string literal
1431
+ */
1432
+ function interpretEscapes(str) {
1433
+ // First handle double backslashes by temporarily replacing them
1434
+ // Then handle other escapes, then restore double backslashes as single
1435
+ return str
1436
+ .replace(/\\\\/g, '\x00') // Temporarily mark double backslashes
1437
+ .replace(/\\n/g, '\n') // Match literal backslash-n (\\\\n in JS string -> \\n in regex -> matches \n)
1438
+ .replace(/\\t/g, '\t')
1439
+ .replace(/\\r/g, '\r')
1440
+ .replace(/\\"/g, '"')
1441
+ .replace(/\\'/g, "'")
1442
+ .replace(/\x00/g, '\\'); // Restore double backslashes as single
1443
+ }
1044
1444
  // Issues management
1045
1445
  const issues = program.command("issues").description("issues management");
1046
1446
  issues
1047
1447
  .command("list")
1048
1448
  .description("list issues")
1049
1449
  .option("--debug", "enable debug output")
1450
+ .option("--json", "output raw JSON")
1050
1451
  .action(async (opts) => {
1051
1452
  try {
1052
1453
  const rootOpts = program.opts();
@@ -1059,14 +1460,90 @@ issues
1059
1460
  }
1060
1461
  const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1061
1462
  const result = await (0, issues_1.fetchIssues)({ apiKey, apiBaseUrl, debug: !!opts.debug });
1062
- if (typeof result === "string") {
1063
- process.stdout.write(result);
1064
- if (!/\n$/.test(result))
1065
- console.log();
1463
+ const trimmed = Array.isArray(result)
1464
+ ? result.map((r) => ({
1465
+ id: r.id,
1466
+ title: r.title,
1467
+ status: r.status,
1468
+ created_at: r.created_at,
1469
+ }))
1470
+ : result;
1471
+ printResult(trimmed, opts.json);
1472
+ }
1473
+ catch (err) {
1474
+ const message = err instanceof Error ? err.message : String(err);
1475
+ console.error(message);
1476
+ process.exitCode = 1;
1477
+ }
1478
+ });
1479
+ issues
1480
+ .command("view <issueId>")
1481
+ .description("view issue details and comments")
1482
+ .option("--debug", "enable debug output")
1483
+ .option("--json", "output raw JSON")
1484
+ .action(async (issueId, opts) => {
1485
+ try {
1486
+ const rootOpts = program.opts();
1487
+ const cfg = config.readConfig();
1488
+ const { apiKey } = getConfig(rootOpts);
1489
+ if (!apiKey) {
1490
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1491
+ process.exitCode = 1;
1492
+ return;
1066
1493
  }
1067
- else {
1068
- console.log(JSON.stringify(result, null, 2));
1494
+ const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1495
+ const issue = await (0, issues_1.fetchIssue)({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1496
+ if (!issue) {
1497
+ console.error("Issue not found");
1498
+ process.exitCode = 1;
1499
+ return;
1500
+ }
1501
+ const comments = await (0, issues_1.fetchIssueComments)({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1502
+ const combined = { issue, comments };
1503
+ printResult(combined, opts.json);
1504
+ }
1505
+ catch (err) {
1506
+ const message = err instanceof Error ? err.message : String(err);
1507
+ console.error(message);
1508
+ process.exitCode = 1;
1509
+ }
1510
+ });
1511
+ issues
1512
+ .command("post_comment <issueId> <content>")
1513
+ .description("post a new comment to an issue")
1514
+ .option("--parent <uuid>", "parent comment id")
1515
+ .option("--debug", "enable debug output")
1516
+ .option("--json", "output raw JSON")
1517
+ .action(async (issueId, content, opts) => {
1518
+ try {
1519
+ // Interpret escape sequences in content (e.g., \n -> newline)
1520
+ if (opts.debug) {
1521
+ // eslint-disable-next-line no-console
1522
+ console.log(`Debug: Original content: ${JSON.stringify(content)}`);
1523
+ }
1524
+ content = interpretEscapes(content);
1525
+ if (opts.debug) {
1526
+ // eslint-disable-next-line no-console
1527
+ console.log(`Debug: Interpreted content: ${JSON.stringify(content)}`);
1069
1528
  }
1529
+ const rootOpts = program.opts();
1530
+ const cfg = config.readConfig();
1531
+ const { apiKey } = getConfig(rootOpts);
1532
+ if (!apiKey) {
1533
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1534
+ process.exitCode = 1;
1535
+ return;
1536
+ }
1537
+ const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1538
+ const result = await (0, issues_1.createIssueComment)({
1539
+ apiKey,
1540
+ apiBaseUrl,
1541
+ issueId,
1542
+ content,
1543
+ parentCommentId: opts.parent,
1544
+ debug: !!opts.debug,
1545
+ });
1546
+ printResult(result, opts.json);
1070
1547
  }
1071
1548
  catch (err) {
1072
1549
  const message = err instanceof Error ? err.message : String(err);