postgresai 0.14.0-dev.14 → 0.14.0-dev.15

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.
package/README.md CHANGED
@@ -15,6 +15,8 @@ Or install the latest beta release explicitly:
15
15
  npm install -g postgresai@beta
16
16
  ```
17
17
 
18
+ Note: in this repository, `cli/package.json` uses a placeholder version (`0.0.0-dev.0`). The real published version is set by the git tag in CI when publishing to npm.
19
+
18
20
  ### From Homebrew (macOS)
19
21
 
20
22
  ```bash
@@ -34,6 +36,13 @@ postgresai --help
34
36
  pgai --help # short alias
35
37
  ```
36
38
 
39
+ You can also run it without installing via `npx`:
40
+
41
+ ```bash
42
+ npx postgresai --help
43
+ npx pgai --help
44
+ ```
45
+
37
46
  ## init (create monitoring user in Postgres)
38
47
 
39
48
  This command creates (or updates) the `postgres_ai_mon` user and grants the permissions described in the root `README.md` (it is idempotent).
@@ -42,6 +51,7 @@ Run without installing (positional connection string):
42
51
 
43
52
  ```bash
44
53
  npx postgresai init postgresql://admin@host:5432/dbname
54
+ npx pgai init postgresql://admin@host:5432/dbname
45
55
  ```
46
56
 
47
57
  It also accepts libpq “conninfo” syntax:
@@ -16,7 +16,7 @@ import { Client } from "pg";
16
16
  import { startMcpServer } from "../lib/mcp-server";
17
17
  import { fetchIssues, fetchIssueComments, createIssueComment, fetchIssue } from "../lib/issues";
18
18
  import { resolveBaseUrls } from "../lib/util";
19
- import { applyInitPlan, buildInitPlan, resolveAdminConnection, resolveMonitoringPassword, verifyInitSetup } from "../lib/init";
19
+ import { applyInitPlan, buildInitPlan, DEFAULT_MONITORING_USER, redactPasswordsInSql, resolveAdminConnection, resolveMonitoringPassword, verifyInitSetup } from "../lib/init";
20
20
 
21
21
  const execPromise = promisify(exec);
22
22
  const execFilePromise = promisify(execFile);
@@ -127,7 +127,7 @@ program
127
127
  .option("-U, --username <username>", "PostgreSQL user (psql-like)")
128
128
  .option("-d, --dbname <dbname>", "PostgreSQL database name (psql-like)")
129
129
  .option("--admin-password <password>", "Admin connection password (otherwise uses PGPASSWORD if set)")
130
- .option("--monitoring-user <name>", "Monitoring role name to create/update", "postgres_ai_mon")
130
+ .option("--monitoring-user <name>", "Monitoring role name to create/update", DEFAULT_MONITORING_USER)
131
131
  .option("--password <password>", "Monitoring role password (overrides PGAI_MON_PASSWORD)")
132
132
  .option("--skip-optional-permissions", "Skip optional permissions (RDS/self-managed extras)", false)
133
133
  .option("--verify", "Verify that monitoring role/permissions are in place (no changes)", false)
@@ -152,6 +152,11 @@ program
152
152
  " If auto-generated, it is printed only on TTY by default.",
153
153
  " To print it in non-interactive mode: --print-password",
154
154
  "",
155
+ "Environment variables (libpq standard):",
156
+ " PGHOST, PGPORT, PGUSER, PGDATABASE — connection defaults",
157
+ " PGPASSWORD — admin password",
158
+ " PGAI_MON_PASSWORD — monitoring password",
159
+ "",
155
160
  "Inspect SQL without applying changes:",
156
161
  " postgresai init <conn> --print-sql",
157
162
  "",
@@ -197,7 +202,7 @@ program
197
202
  const redactPasswords = (sql: string): string => {
198
203
  if (!shouldRedactSecrets) return sql;
199
204
  // Replace PASSWORD '<literal>' (handles doubled quotes inside).
200
- return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
205
+ return redactPasswordsInSql(sql);
201
206
  };
202
207
 
203
208
  // Offline mode: allow printing SQL without providing/using an admin connection.
@@ -216,7 +221,6 @@ program
216
221
  monitoringUser: opts.monitoringUser,
217
222
  monitoringPassword: monPassword,
218
223
  includeOptionalPermissions,
219
- roleExists: undefined,
220
224
  });
221
225
 
222
226
  console.log("\n--- SQL plan (offline; not connected) ---");
@@ -250,7 +254,7 @@ program
250
254
  });
251
255
  } catch (e) {
252
256
  const msg = e instanceof Error ? e.message : String(e);
253
- console.error(`✗ ${msg}`);
257
+ console.error(`Error: ${msg}`);
254
258
  // When connection details are missing, show full init help (options + examples).
255
259
  if (typeof msg === "string" && msg.startsWith("Connection is required.")) {
256
260
  console.error("");
@@ -267,16 +271,11 @@ program
267
271
  console.log(`Optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
268
272
 
269
273
  // Use native pg client instead of requiring psql to be installed
270
- const client = new Client(adminConn.clientConfig);
271
-
274
+ let client: Client | undefined;
272
275
  try {
276
+ client = new Client(adminConn.clientConfig);
273
277
  await client.connect();
274
278
 
275
- const roleRes = await client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [
276
- opts.monitoringUser,
277
- ]);
278
- const roleExists = (roleRes.rowCount ?? 0) > 0;
279
-
280
279
  const dbRes = await client.query("select current_database() as db");
281
280
  const database = dbRes.rows?.[0]?.db;
282
281
  if (typeof database !== "string" || !database) {
@@ -319,10 +318,12 @@ program
319
318
  if (resolved.generated) {
320
319
  const canPrint = process.stdout.isTTY || !!opts.printPassword;
321
320
  if (canPrint) {
322
- console.log("");
323
- console.log(`Generated monitoring password for ${opts.monitoringUser} (copy/paste):`);
324
- console.log(`PGAI_MON_PASSWORD=${monPassword}`);
325
- console.log("");
321
+ // Print secrets to stderr to reduce the chance they end up in piped stdout logs.
322
+ console.error("");
323
+ console.error(`Generated monitoring password for ${opts.monitoringUser} (copy/paste):`);
324
+ // Quote for shell copy/paste safety.
325
+ console.error(`PGAI_MON_PASSWORD='${monPassword}'`);
326
+ console.error("");
326
327
  console.log("Store it securely (or rerun with --password / PGAI_MON_PASSWORD to set your own).");
327
328
  } else {
328
329
  console.error(
@@ -352,7 +353,6 @@ program
352
353
  monitoringUser: opts.monitoringUser,
353
354
  monitoringPassword: monPassword,
354
355
  includeOptionalPermissions,
355
- roleExists,
356
356
  });
357
357
 
358
358
  const effectivePlan = opts.resetPassword
@@ -396,57 +396,54 @@ program
396
396
  if (!message || message === "[object Object]") {
397
397
  message = "Unknown error";
398
398
  }
399
- console.error(`✗ init failed: ${message}`);
399
+ console.error(`Error: init failed: ${message}`);
400
400
  // If this was a plan step failure, surface the step name explicitly to help users diagnose quickly.
401
401
  const stepMatch =
402
402
  typeof message === "string" ? message.match(/Failed at step "([^"]+)":/i) : null;
403
403
  const failedStep = stepMatch?.[1];
404
404
  if (failedStep) {
405
- console.error(`Step: ${failedStep}`);
405
+ console.error(` Step: ${failedStep}`);
406
406
  }
407
407
  if (errAny && typeof errAny === "object") {
408
408
  if (typeof errAny.code === "string" && errAny.code) {
409
- console.error(`Error code: ${errAny.code}`);
409
+ console.error(` Code: ${errAny.code}`);
410
410
  }
411
411
  if (typeof errAny.detail === "string" && errAny.detail) {
412
- console.error(`Detail: ${errAny.detail}`);
412
+ console.error(` Detail: ${errAny.detail}`);
413
413
  }
414
414
  if (typeof errAny.hint === "string" && errAny.hint) {
415
- console.error(`Hint: ${errAny.hint}`);
415
+ console.error(` Hint: ${errAny.hint}`);
416
416
  }
417
417
  }
418
418
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
419
419
  if (errAny.code === "42501") {
420
- console.error("");
421
- console.error("Permission error: your admin connection is not allowed to complete the setup.");
422
420
  if (failedStep === "01.role") {
423
- console.error("What failed: create/update the monitoring role (needs CREATEROLE or superuser).");
421
+ console.error(" Context: role creation/update requires CREATEROLE or superuser");
424
422
  } else if (failedStep === "02.permissions") {
425
- console.error("What failed: grant required permissions / create view / set role search_path.");
423
+ console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
426
424
  }
427
- console.error("How to fix:");
428
- console.error("- Connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
429
- console.error("- On managed Postgres, use the provider's admin/master user.");
430
- console.error("Tip: run with --print-sql to review the exact SQL plan.");
431
- console.error("");
432
- console.error("Hint: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
425
+ console.error(" Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
426
+ console.error(" Fix: on managed Postgres, use the provider's admin/master user");
427
+ console.error(" Tip: run with --print-sql to review the exact SQL plan");
433
428
  }
434
429
  if (errAny.code === "ECONNREFUSED") {
435
- console.error("Hint: check host/port and ensure Postgres is reachable from this machine.");
430
+ console.error(" Hint: check host/port and ensure Postgres is reachable from this machine");
436
431
  }
437
432
  if (errAny.code === "ENOTFOUND") {
438
- console.error("Hint: DNS resolution failed; double-check the host name.");
433
+ console.error(" Hint: DNS resolution failed; double-check the host name");
439
434
  }
440
435
  if (errAny.code === "ETIMEDOUT") {
441
- console.error("Hint: connection timed out; check network/firewall rules.");
436
+ console.error(" Hint: connection timed out; check network/firewall rules");
442
437
  }
443
438
  }
444
439
  process.exitCode = 1;
445
440
  } finally {
446
- try {
447
- await client.end();
448
- } catch {
449
- // ignore
441
+ if (client) {
442
+ try {
443
+ await client.end();
444
+ } catch {
445
+ // ignore
446
+ }
450
447
  }
451
448
  }
452
449
  });
@@ -109,7 +109,7 @@ program
109
109
  .option("-U, --username <username>", "PostgreSQL user (psql-like)")
110
110
  .option("-d, --dbname <dbname>", "PostgreSQL database name (psql-like)")
111
111
  .option("--admin-password <password>", "Admin connection password (otherwise uses PGPASSWORD if set)")
112
- .option("--monitoring-user <name>", "Monitoring role name to create/update", "postgres_ai_mon")
112
+ .option("--monitoring-user <name>", "Monitoring role name to create/update", init_1.DEFAULT_MONITORING_USER)
113
113
  .option("--password <password>", "Monitoring role password (overrides PGAI_MON_PASSWORD)")
114
114
  .option("--skip-optional-permissions", "Skip optional permissions (RDS/self-managed extras)", false)
115
115
  .option("--verify", "Verify that monitoring role/permissions are in place (no changes)", false)
@@ -132,6 +132,11 @@ program
132
132
  " If auto-generated, it is printed only on TTY by default.",
133
133
  " To print it in non-interactive mode: --print-password",
134
134
  "",
135
+ "Environment variables (libpq standard):",
136
+ " PGHOST, PGPORT, PGUSER, PGDATABASE — connection defaults",
137
+ " PGPASSWORD — admin password",
138
+ " PGAI_MON_PASSWORD — monitoring password",
139
+ "",
135
140
  "Inspect SQL without applying changes:",
136
141
  " postgresai init <conn> --print-sql",
137
142
  "",
@@ -161,7 +166,7 @@ program
161
166
  if (!shouldRedactSecrets)
162
167
  return sql;
163
168
  // Replace PASSWORD '<literal>' (handles doubled quotes inside).
164
- return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
169
+ return (0, init_1.redactPasswordsInSql)(sql);
165
170
  };
166
171
  // Offline mode: allow printing SQL without providing/using an admin connection.
167
172
  // Useful for audits/reviews; caller can provide -d/PGDATABASE and an explicit monitoring password.
@@ -176,7 +181,6 @@ program
176
181
  monitoringUser: opts.monitoringUser,
177
182
  monitoringPassword: monPassword,
178
183
  includeOptionalPermissions,
179
- roleExists: undefined,
180
184
  });
181
185
  console.log("\n--- SQL plan (offline; not connected) ---");
182
186
  console.log(`-- database: ${database}`);
@@ -209,7 +213,7 @@ program
209
213
  }
210
214
  catch (e) {
211
215
  const msg = e instanceof Error ? e.message : String(e);
212
- console.error(`✗ ${msg}`);
216
+ console.error(`Error: ${msg}`);
213
217
  // When connection details are missing, show full init help (options + examples).
214
218
  if (typeof msg === "string" && msg.startsWith("Connection is required.")) {
215
219
  console.error("");
@@ -223,13 +227,10 @@ program
223
227
  console.log(`Monitoring user: ${opts.monitoringUser}`);
224
228
  console.log(`Optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
225
229
  // Use native pg client instead of requiring psql to be installed
226
- const client = new pg_1.Client(adminConn.clientConfig);
230
+ let client;
227
231
  try {
232
+ client = new pg_1.Client(adminConn.clientConfig);
228
233
  await client.connect();
229
- const roleRes = await client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [
230
- opts.monitoringUser,
231
- ]);
232
- const roleExists = (roleRes.rowCount ?? 0) > 0;
233
234
  const dbRes = await client.query("select current_database() as db");
234
235
  const database = dbRes.rows?.[0]?.db;
235
236
  if (typeof database !== "string" || !database) {
@@ -273,10 +274,12 @@ program
273
274
  if (resolved.generated) {
274
275
  const canPrint = process.stdout.isTTY || !!opts.printPassword;
275
276
  if (canPrint) {
276
- console.log("");
277
- console.log(`Generated monitoring password for ${opts.monitoringUser} (copy/paste):`);
278
- console.log(`PGAI_MON_PASSWORD=${monPassword}`);
279
- console.log("");
277
+ // Print secrets to stderr to reduce the chance they end up in piped stdout logs.
278
+ console.error("");
279
+ console.error(`Generated monitoring password for ${opts.monitoringUser} (copy/paste):`);
280
+ // Quote for shell copy/paste safety.
281
+ console.error(`PGAI_MON_PASSWORD='${monPassword}'`);
282
+ console.error("");
280
283
  console.log("Store it securely (or rerun with --password / PGAI_MON_PASSWORD to set your own).");
281
284
  }
282
285
  else {
@@ -305,7 +308,6 @@ program
305
308
  monitoringUser: opts.monitoringUser,
306
309
  monitoringPassword: monPassword,
307
310
  includeOptionalPermissions,
308
- roleExists,
309
311
  });
310
312
  const effectivePlan = opts.resetPassword
311
313
  ? { ...plan, steps: plan.steps.filter((s) => s.name === "01.role") }
@@ -349,59 +351,56 @@ program
349
351
  if (!message || message === "[object Object]") {
350
352
  message = "Unknown error";
351
353
  }
352
- console.error(`✗ init failed: ${message}`);
354
+ console.error(`Error: init failed: ${message}`);
353
355
  // If this was a plan step failure, surface the step name explicitly to help users diagnose quickly.
354
356
  const stepMatch = typeof message === "string" ? message.match(/Failed at step "([^"]+)":/i) : null;
355
357
  const failedStep = stepMatch?.[1];
356
358
  if (failedStep) {
357
- console.error(`Step: ${failedStep}`);
359
+ console.error(` Step: ${failedStep}`);
358
360
  }
359
361
  if (errAny && typeof errAny === "object") {
360
362
  if (typeof errAny.code === "string" && errAny.code) {
361
- console.error(`Error code: ${errAny.code}`);
363
+ console.error(` Code: ${errAny.code}`);
362
364
  }
363
365
  if (typeof errAny.detail === "string" && errAny.detail) {
364
- console.error(`Detail: ${errAny.detail}`);
366
+ console.error(` Detail: ${errAny.detail}`);
365
367
  }
366
368
  if (typeof errAny.hint === "string" && errAny.hint) {
367
- console.error(`Hint: ${errAny.hint}`);
369
+ console.error(` Hint: ${errAny.hint}`);
368
370
  }
369
371
  }
370
372
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
371
373
  if (errAny.code === "42501") {
372
- console.error("");
373
- console.error("Permission error: your admin connection is not allowed to complete the setup.");
374
374
  if (failedStep === "01.role") {
375
- console.error("What failed: create/update the monitoring role (needs CREATEROLE or superuser).");
375
+ console.error(" Context: role creation/update requires CREATEROLE or superuser");
376
376
  }
377
377
  else if (failedStep === "02.permissions") {
378
- console.error("What failed: grant required permissions / create view / set role search_path.");
378
+ console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
379
379
  }
380
- console.error("How to fix:");
381
- console.error("- Connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
382
- console.error("- On managed Postgres, use the provider's admin/master user.");
383
- console.error("Tip: run with --print-sql to review the exact SQL plan.");
384
- console.error("");
385
- console.error("Hint: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
380
+ console.error(" Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
381
+ console.error(" Fix: on managed Postgres, use the provider's admin/master user");
382
+ console.error(" Tip: run with --print-sql to review the exact SQL plan");
386
383
  }
387
384
  if (errAny.code === "ECONNREFUSED") {
388
- console.error("Hint: check host/port and ensure Postgres is reachable from this machine.");
385
+ console.error(" Hint: check host/port and ensure Postgres is reachable from this machine");
389
386
  }
390
387
  if (errAny.code === "ENOTFOUND") {
391
- console.error("Hint: DNS resolution failed; double-check the host name.");
388
+ console.error(" Hint: DNS resolution failed; double-check the host name");
392
389
  }
393
390
  if (errAny.code === "ETIMEDOUT") {
394
- console.error("Hint: connection timed out; check network/firewall rules.");
391
+ console.error(" Hint: connection timed out; check network/firewall rules");
395
392
  }
396
393
  }
397
394
  process.exitCode = 1;
398
395
  }
399
396
  finally {
400
- try {
401
- await client.end();
402
- }
403
- catch {
404
- // ignore
397
+ if (client) {
398
+ try {
399
+ await client.end();
400
+ }
401
+ catch {
402
+ // ignore
403
+ }
405
404
  }
406
405
  }
407
406
  });