postgresai 0.18.0-dev.8 → 0.18.0-dev.9

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
@@ -252,7 +252,8 @@ terminal, or with `--json`, it only points to `pgai mon deploy`.
252
252
  | `--provider <provider>` | `generic` (direct PostgreSQL; `self-managed` remains an alias), `clickhouse`, `rds` or `supabase`; default: detected from the host |
253
253
  | `--clickhouse-key <key-id>:<key-secret>` | ClickHouse Cloud API key, for CPU, memory and disk |
254
254
  | `--self-hosted` | run the stack on this machine (`mon local-install`) instead of PostgresAI Cloud |
255
- | `--reset-password` | `postgres_ai_mon` exists and its password is lost: set a new one (see below) |
255
+ | `--reset-password` | the monitoring role exists and its password is lost: set a new one (see below) |
256
+ | `--monitoring-user <name>` | the monitoring role to create or use (default `postgres_ai_mon`; at most 63 bytes; MCP: `monitoring_user`). A custom role always carries its own password: PostgresAI keeps only `postgres_ai_mon`'s, so creating or resetting a custom role needs `PGAI_MON_PASSWORD` (an agent passes the role's URL). A name with `'`, `$`, `%`, backslash or a control character is refused, and so is a role that is a superuser or has `CREATEDB`, `CREATEROLE`, `REPLICATION` or `BYPASSRLS`, is a member of a role other than `pg_monitor`, `pg_read_all_stats`, `pg_read_all_settings` and `pg_stat_scan_tables` (directly or through other roles, also through `pg_monitor` itself), owns objects, has grants in another database of the server, or has grants in the database beyond `CONNECT`, `USAGE` on schemas other than `pg_toast`, `SELECT` outside `pg_catalog` and `pg_toast`, and the grants pgai makes, or holds any grant `WITH GRANT OPTION` or a membership `WITH ADMIN OPTION`. So a custom role used for databases on one server is refused for the second one. `SELECT` on application tables and views is allowed, including a view over `pg_authid`: what a role may read through views is the owner's choice. Ignored for a host handed to the Console |
256
257
  | `--db-url <url>` | the database URL, instead of the argument |
257
258
  | `--name <name>` | the instance's name (default: `host[:port]/database`); ignored, with a note, for a database already monitored |
258
259
  | `--location <location>` | Hetzner location `fsn1`, `nbg1` or `hel1` (default: any with capacity) |
@@ -274,8 +275,8 @@ and asks you to re-run with `--yes` to accept it.
274
275
  | `PGSSLMODE` | the `sslmode` for a URL without one (`sslmode` in the URL wins, as in libpq) |
275
276
  | `CLICKHOUSE_KEY_ID` + `CLICKHOUSE_KEY_SECRET` | instead of `--clickhouse-key`; read for ClickHouse hosts only |
276
277
 
277
- `postgres_ai_mon` is one role for the whole server, so `mon deploy` never changes the password of an
278
- existing one. If the role exists and you do not have its password (a deployment after
278
+ The monitoring role (`postgres_ai_mon`, or `--monitoring-user`) is one role for the whole server, so
279
+ `mon deploy` never changes the password of an existing one. If the role exists and you do not have its password (a deployment after
279
280
  `pgai mon instances delete`, say), `pgai mon deploy <admin-url> --reset-password` sets a new one
280
281
  (`PGAI_MON_PASSWORD`, else generated). It is refused while another database on the same server (the same host name, in this
281
282
  organization) is monitored with the role, while a box's server is not known (it was created before
@@ -284,7 +285,7 @@ already monitored. After the price is accepted, the run takes the platform's loc
284
285
  name and port, in this organization) until the box is requested. A second `--reset-password` for
285
286
  the same server exits 3 meanwhile. A run that stopped, or whose box request got no answer, frees the
286
287
  server 15 minutes after it took the lock. A platform without the lock answers "set
287
- `PGAI_MON_PASSWORD`" instead. Anything else that logs in as `postgres_ai_mon` (another organization,
288
+ `PGAI_MON_PASSWORD`" instead. Anything else that logs in as the role (another organization,
288
289
  another host name for the same server, a deploy without `--reset-password` running at the same
289
290
  time) needs the new password.
290
291
 
@@ -402,6 +403,7 @@ pgai reports list --org-id 5225 # by numeric id — same on every org-scope
402
403
  PGAI_ORG=acme pgai checkup ... # for scripts and agents
403
404
 
404
405
  pgai orgs # which organizations can this token reach?
406
+ pgai orgs create --name "My team" --alias my-team --json # global user token required
405
407
  ```
406
408
 
407
409
  `--org` always means an alias and `--org-id` always means a numeric id.
@@ -575,7 +577,7 @@ Tools exposed:
575
577
  - `update_issue_comment`: update an existing comment (args: `{ comment_id, org_id, content?, attachments?, debug? }`).
576
578
  - `upload_file`: upload a local file and return the storage URL plus a ready-to-paste markdown link (args: `{ path, org_id, debug? }`).
577
579
  - `download_file`: download a file from storage (args: `{ url, org_id, output_path?, debug? }`).
578
- - `deploy_monitoring`: `pgai mon deploy` as a tool (args: `{ database_url, org_id, provider?, clickhouse_key?, yes?, coupon?, debug? }`). Returns the same JSON (`status`: `ready`, `in_progress`, `deleting`, `deleted`, `inactive`, `action_required` or `failed`; `health_url`; `dashboard_url`; `next`). For a billed box, the tool first returns the price with `action_required`; an explicit call with `yes: true` accepts it. `coupon` supplies a promotion code. It does not wait for the monitoring box: call it again to see the status. `database_url` must carry its password, and only the query parameters `sslmode`, `channel_binding`, `application_name` (and `password`); `PGAI_MON_PASSWORD`, `PGPASSWORD` and `CLICKHOUSE_KEY_ID` + `CLICKHOUSE_KEY_SECRET` of the server process are not used, a TLS failure is not retried in plaintext, and `--self-hosted` is CLI-only. For another database on a server PostgresAI already monitors for the organization, an admin `database_url` with `sslmode=require` (or `verify-*`) is enough: PostgresAI fills in the password of `postgres_ai_mon` it keeps.
580
+ - `deploy_monitoring`: `pgai mon deploy` as a tool (args: `{ database_url, org_id, provider?, clickhouse_key?, yes?, coupon?, monitoring_user?, debug? }`). Returns the same JSON (`status`: `ready`, `in_progress`, `deleting`, `deleted`, `inactive`, `action_required` or `failed`; `health_url`; `dashboard_url`; `next`). For a billed box, the tool first returns the price with `action_required`; an explicit call with `yes: true` accepts it. `coupon` supplies a promotion code. It does not wait for the monitoring box: call it again to see the status. `database_url` must carry its password, and only the query parameters `sslmode`, `channel_binding`, `application_name` (and `password`); `PGAI_MON_PASSWORD`, `PGPASSWORD` and `CLICKHOUSE_KEY_ID` + `CLICKHOUSE_KEY_SECRET` of the server process are not used, a TLS failure is not retried in plaintext, and `--self-hosted` is CLI-only. For another database on a server PostgresAI already monitors for the organization, an admin `database_url` with `sslmode=require` (or `verify-*`) is enough: PostgresAI fills in the password of `postgres_ai_mon` it keeps.
579
581
 
580
582
  #### `attachments` parameter (issue/comment tools)
581
583
 
@@ -708,6 +710,22 @@ postgresai show-key # Show stored key (masked)
708
710
  postgresai remove-key # Remove stored key
709
711
  ```
710
712
 
713
+ ### Create an organization
714
+
715
+ ```bash
716
+ pgai auth login # choose "All my organizations (global token)"
717
+ pgai orgs create --name "My team" --alias my-team --json
718
+ ```
719
+
720
+ - Choose the name explicitly. An agent should ask the user to approve its proposed name first.
721
+ - At login, choose "All my organizations (global token)". A token for one organization cannot create organizations.
722
+ - This works before you belong to any organization. The consent page then offers only the global token.
723
+ - Alternatively, create a global token at https://console.postgres.ai/profile/global-tokens, then run `pgai auth --set-key <token>` or set `PGAI_API_KEY`.
724
+ - Organization and instance tokens cannot create organizations. The CLI refuses them before sending anything.
725
+ - The alias is normalized like the Console does it: lowercase, and spaces and reserved characters become `-`. Omit `--alias` to derive it from the name. It must be ASCII because `--org` sends it as a header.
726
+ - You become the owner and an Admin member. No organization selection is sent, and your saved configuration does not change. Use the returned alias with `--org` afterwards.
727
+ - Requires the Platform change https://gitlab.com/postgres-ai/platform-all/-/merge_requests/1157 to be deployed.
728
+
711
729
  ## Configuration
712
730
 
713
731
  The CLI stores configuration in `~/.config/postgresai/config.json` including:
@@ -13533,7 +13533,7 @@ var {
13533
13533
  // package.json
13534
13534
  var package_default = {
13535
13535
  name: "postgresai",
13536
- version: "0.18.0-dev.8",
13536
+ version: "0.18.0-dev.9",
13537
13537
  description: "postgres_ai CLI",
13538
13538
  license: "Apache-2.0",
13539
13539
  private: false,
@@ -16893,7 +16893,7 @@ var Result = import_lib.default.Result;
16893
16893
  var TypeOverrides = import_lib.default.TypeOverrides;
16894
16894
  var defaults = import_lib.default.defaults;
16895
16895
  // package.json
16896
- var version = "0.18.0-dev.8";
16896
+ var version = "0.18.0-dev.9";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -22721,7 +22721,7 @@ function priceText(q) {
22721
22721
  }
22722
22722
  return base;
22723
22723
  }
22724
- var FIRST_CHECKUP_DELAY_MS = 30 * 60000;
22724
+ var FIRST_CHECKUP_DELAY_MS = 3 * 60000;
22725
22725
  var POLL_MS = 15000;
22726
22726
  var PROVIDERS = ["clickhouse", "rds", "supabase", "self-managed"];
22727
22727
  var providerArg = (provider) => {
@@ -22843,9 +22843,13 @@ function storedPasswordNeeds(monitoringUrl) {
22843
22843
  }
22844
22844
  var shellWord = (s) => /^[\w./:@%+=,-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
22845
22845
  var disconnectEach = (names) => names.map((n) => `pgai mon instances delete ${shellWord(n)} --yes`).join(" and ");
22846
- function roleUrlFor(url, db, password, kept) {
22846
+ function loginName(url, sessionUser, role) {
22847
+ const user = decodeURIComponent(new URL(url).username);
22848
+ return user.startsWith(`${sessionUser}.`) ? role + user.slice(sessionUser.length) : role;
22849
+ }
22850
+ function roleUrlFor(url, user, db, password, kept) {
22847
22851
  const u = new URL(url);
22848
- u.username = DEFAULT_MONITORING_USER;
22852
+ u.username = encodeURIComponent(user);
22849
22853
  u.password = encodeURIComponent(password);
22850
22854
  u.pathname = `/${encodeURIComponent(db)}`;
22851
22855
  for (const name of [...u.searchParams.keys()])
@@ -22854,8 +22858,8 @@ function roleUrlFor(url, db, password, kept) {
22854
22858
  u.search = u.search.replace(/@/g, "%40");
22855
22859
  return u.toString();
22856
22860
  }
22857
- var monitoringUrlFor = (url, db, password) => roleUrlFor(url, db, password, URL_PARAMS_KEPT.filter((p) => p !== "channel_binding"));
22858
- var loginUrlFor = (url, db, password) => roleUrlFor(url, db, password, [...URL_PARAMS_KEPT, ...URL_PARAMS_TLS]);
22861
+ var monitoringUrlFor = (url, user, db, password) => roleUrlFor(url, user, db, password, URL_PARAMS_KEPT.filter((p) => p !== "channel_binding"));
22862
+ var loginUrlFor = (url, user, db, password) => roleUrlFor(url, user, db, password, [...URL_PARAMS_KEPT, ...URL_PARAMS_TLS]);
22859
22863
  function caNote(url) {
22860
22864
  const q = new URL(url).searchParams;
22861
22865
  if (!q.get("sslrootcert") || !/^verify-/.test(q.get("sslmode") ?? ""))
@@ -22922,6 +22926,19 @@ async function connect(url, opts, deps) {
22922
22926
  assertEncodedUserinfo(url);
22923
22927
  checkUrlParams(url, opts.agent);
22924
22928
  const name = databaseName2(url);
22929
+ const asked = opts.monitoringUser?.trim();
22930
+ if (opts.monitoringUser !== undefined && !asked) {
22931
+ const flag = opts.agent ? "monitoring_user" : "--monitoring-user";
22932
+ return { status: "action_required", provider, name, next: `${flag} is empty: pass a role name, or leave it out for ${DEFAULT_MONITORING_USER}` };
22933
+ }
22934
+ const monitoringUser = asked && asked !== DEFAULT_MONITORING_USER ? asked : undefined;
22935
+ const role = monitoringUser ?? DEFAULT_MONITORING_USER;
22936
+ if (monitoringUser && /['$%\\\u0000-\u001f\u007f]/.test(monitoringUser)) {
22937
+ return { status: "action_required", provider, name, next: `${opts.agent ? "monitoring_user" : "--monitoring-user"} must not contain ', $, %, backslash or control characters` };
22938
+ }
22939
+ if (monitoringUser && Buffer.byteLength(monitoringUser) > 63) {
22940
+ return { status: "action_required", provider, name, next: `${opts.agent ? "monitoring_user" : "--monitoring-user"} must be at most 63 bytes (Postgres truncates longer role names)` };
22941
+ }
22925
22942
  try {
22926
22943
  const collector = await collectorConnection(url, deps.verifyTls);
22927
22944
  const required = splitChannelBinding(url).value === "require";
@@ -22939,7 +22956,8 @@ async function connect(url, opts, deps) {
22939
22956
  if (key && provider !== "clickhouse")
22940
22957
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
22941
22958
  if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
22942
- return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}` };
22959
+ const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
22960
+ return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
22943
22961
  }
22944
22962
  if (opts.selfHosted && opts.resetPassword) {
22945
22963
  return { status: "action_required", provider, name, next: "--reset-password works with PostgresAI Cloud only (it checks what else monitors this server): deploy without --self-hosted, or set PGAI_MON_PASSWORD" };
@@ -23015,13 +23033,13 @@ async function connect(url, opts, deps) {
23015
23033
  }
23016
23034
  const undo = async (p) => {
23017
23035
  if ("generated" in p && p.generated)
23018
- await deps.unprepare(url).catch(() => false);
23036
+ await deps.unprepare(url, monitoringUser).catch(() => false);
23019
23037
  };
23020
23038
  let lockId;
23021
23039
  const unread = (d) => !d.cluster;
23022
23040
  const onServer = (d) => !!d.cluster && serverOf(d.cluster) === cluster;
23023
23041
  const othersOnServer = (list) => list.filter((d) => !disconnecting(d.status) && (unread(d) || onServer(d)));
23024
- const storedPassword = rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
23042
+ const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
23025
23043
  const cutOff = (others) => {
23026
23044
  const on = others.filter((d) => !unread(d)).map((d) => d.name).join(", ");
23027
23045
  const maybe = others.filter(unread).map((d) => d.name).join(", ");
@@ -23031,7 +23049,7 @@ async function connect(url, opts, deps) {
23031
23049
  "set PGAI_MON_PASSWORD to its password instead",
23032
23050
  `${disconnectEach(others.map((d) => d.name))} first`
23033
23051
  ];
23034
- return { status: "action_required", provider, name, next: `A new password for ${DEFAULT_MONITORING_USER} ${what}: ${instead.join(", or ")}` };
23052
+ return { status: "action_required", provider, name, next: `A new password for ${role} ${what}: ${instead.join(", or ")}` };
23035
23053
  };
23036
23054
  const others = othersOnServer(rows).filter((d) => !unread(d)).map((d) => d.name);
23037
23055
  if (opts.resetPassword && othersOnServer(rows).length)
@@ -23039,7 +23057,7 @@ async function connect(url, opts, deps) {
23039
23057
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
23040
23058
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
23041
23059
  }
23042
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {} };
23060
+ const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
23043
23061
  if (!opts.selfHosted) {
23044
23062
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
23045
23063
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText(err)))
@@ -23084,7 +23102,7 @@ async function connect(url, opts, deps) {
23084
23102
  return { status: "action_required", provider, name, ...billing, next: `Another pgai mon deploy --reset-password for ${cluster} is running: wait for it to finish, then re-run (a run that stopped frees the server 15 minutes after it started)` };
23085
23103
  }
23086
23104
  if (err instanceof HttpStatusError && err.status === 404) {
23087
- return { status: "action_required", provider, name, ...billing, next: `This platform cannot lock the server for --reset-password yet: set PGAI_MON_PASSWORD to ${DEFAULT_MONITORING_USER}'s password instead` };
23105
+ return { status: "action_required", provider, name, ...billing, next: `This platform cannot lock the server for --reset-password yet: set PGAI_MON_PASSWORD to ${role}'s password instead` };
23088
23106
  }
23089
23107
  throw err;
23090
23108
  }
@@ -23224,23 +23242,34 @@ async function openConnection(url, opts) {
23224
23242
  await client.query("set search_path = pg_catalog, pg_temp");
23225
23243
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
23226
23244
  }
23227
- async function dropMonitoringRole(client) {
23228
- for (const sql of [`drop role ${DEFAULT_MONITORING_USER}`, `drop owned by ${DEFAULT_MONITORING_USER}; drop role ${DEFAULT_MONITORING_USER}`]) {
23245
+ async function dropMonitoringRole(client, role) {
23246
+ const q = quoteIdent(role);
23247
+ for (const sql of [`drop role ${q}`, `drop owned by ${q}; drop role ${q}`]) {
23229
23248
  if (await client.query(sql).then(() => true, () => false))
23230
23249
  return true;
23231
23250
  }
23232
23251
  return false;
23233
23252
  }
23253
+ var MONITORING_GROUPS = ["pg_monitor", "pg_read_all_stats", "pg_read_all_settings", "pg_stat_scan_tables"];
23254
+ var MONITORING_FUNCTIONS = [
23255
+ "pg_catalog.pg_stat_file(text)",
23256
+ "pg_catalog.pg_stat_file(text, boolean)",
23257
+ "pg_catalog.pg_ls_dir(text)",
23258
+ "pg_catalog.pg_ls_dir(text, boolean, boolean)",
23259
+ "rds_tools.pg_ls_multixactdir()",
23260
+ "postgres_ai.table_describe(text)"
23261
+ ];
23234
23262
  async function unprepareDatabase(url, opts = {}) {
23235
23263
  const { client } = await openConnection(url, opts);
23236
23264
  try {
23237
- return await dropMonitoringRole(client);
23265
+ return await dropMonitoringRole(client, opts.monitoringUser || DEFAULT_MONITORING_USER);
23238
23266
  } finally {
23239
23267
  await client.end();
23240
23268
  }
23241
23269
  }
23242
23270
  async function prepareDatabase(url, provider, opts = {}) {
23243
23271
  const pgProvider = provider === "rds" ? "self-managed" : provider;
23272
+ const role = opts.monitoringUser || DEFAULT_MONITORING_USER;
23244
23273
  const open = (u) => openConnection(u, opts);
23245
23274
  const logsIn = async (u) => {
23246
23275
  try {
@@ -23268,20 +23297,54 @@ async function prepareDatabase(url, provider, opts = {}) {
23268
23297
  and pg_has_role(current_user, 'pg_read_all_stats', 'USAGE WITH ADMIN OPTION')))
23269
23298
  and has_database_privilege(current_user, current_database(), 'CREATE')
23270
23299
  and exists (select 1 from pg_extension where extname = 'pg_stat_statements')) as admin,
23271
- exists (select 1 from pg_roles where rolname = '${DEFAULT_MONITORING_USER}') as mon_exists,
23300
+ exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)}) as mon_exists,
23301
+ exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)} and (rolsuper or rolcreatedb or rolcreaterole or rolreplication or rolbypassrls)) as mon_privileged,
23302
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m join pg_roles g
23303
+ on g.oid <> m.oid and pg_has_role(m.oid, g.oid, 'MEMBER')
23304
+ where m.rolname = ${quoteLiteral(role)} and g.rolname not in (${MONITORING_GROUPS.map(quoteLiteral).join(", ")})) as mon_groups,
23305
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m
23306
+ join pg_auth_members a on a.member = m.oid join pg_roles g on g.oid = a.roleid
23307
+ where m.rolname = ${quoteLiteral(role)} and a.admin_option) as mon_admin_groups,
23308
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles g
23309
+ where g.rolname not in (${[...MONITORING_GROUPS, role].map(quoteLiteral).join(", ")})
23310
+ and (pg_has_role('pg_monitor', g.oid, 'MEMBER') or pg_has_role('pg_read_all_stats', g.oid, 'MEMBER'))) as mon_plan_groups,
23311
+ exists (select 1 from pg_shdepend d join pg_roles m on m.oid = d.refobjid
23312
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'o' and m.rolname = ${quoteLiteral(role)}) as mon_owns,
23313
+ (select string_agg(distinct db.datname::text, ', ') from pg_shdepend d join pg_roles m on m.oid = d.refobjid join pg_database db on db.oid = d.dbid
23314
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'a' and m.rolname = ${quoteLiteral(role)}
23315
+ and db.datname <> current_database()) as mon_other_dbs,
23316
+ (select string_agg(distinct pg_describe_object(d.classid, d.objid, d.objsubid), ', ') from pg_shdepend d join pg_roles m on m.oid = d.refobjid
23317
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'a' and m.rolname = ${quoteLiteral(role)}
23318
+ and d.dbid in (0, (select oid from pg_database where datname = current_database()))
23319
+ and not exists (select 1 from (
23320
+ select relacl as acl, 'SELECT' as ok from pg_class where d.classid = 'pg_class'::regclass and d.objsubid = 0 and oid = d.objid
23321
+ and ((relnamespace not in ('pg_catalog'::regnamespace, 'pg_toast'::regnamespace) and relkind <> 't') or oid = 'pg_catalog.pg_index'::regclass)
23322
+ union all select attacl, 'SELECT' from pg_attribute where d.classid = 'pg_class'::regclass and attrelid = d.objid and attnum = d.objsubid
23323
+ and (select relnamespace not in ('pg_catalog'::regnamespace, 'pg_toast'::regnamespace) and relkind <> 't' from pg_class where oid = d.objid)
23324
+ union all select nspacl, 'USAGE' from pg_namespace where d.classid = 'pg_namespace'::regclass and oid = d.objid and nspname !~ '^pg_toast'
23325
+ union all select proacl, 'EXECUTE' from pg_proc where d.classid = 'pg_proc'::regclass and oid = d.objid
23326
+ and pronamespace::regnamespace::text || '.' || proname || '(' || array_to_string(proargtypes::oid[]::regtype[], ', ') || ')'
23327
+ in (${MONITORING_FUNCTIONS.map(quoteLiteral).join(", ")})
23328
+ union all select datacl, 'CONNECT' from pg_database where d.classid = 'pg_database'::regclass and oid = d.objid) o
23329
+ where not exists (select 1 from aclexplode(o.acl) e where e.grantee = d.refobjid and (e.privilege_type <> o.ok or e.is_grantable)))) as mon_grants,
23272
23330
  current_setting('scram_iterations', true) as iterations, current_setting('ssl') as ssl
23273
23331
  from pg_roles where rolname = current_user`)).rows[0];
23332
+ const user = loginName(url, me.name, role);
23333
+ const custom = role !== DEFAULT_MONITORING_USER;
23334
+ const unsafe = me.mon_privileged ? "is a superuser, or has CREATEDB, CREATEROLE, REPLICATION or BYPASSRLS: a monitoring role must not" : me.mon_groups ? `is a member of ${me.mon_groups}: a monitoring role may be a member of ${MONITORING_GROUPS.slice(0, -1).join(", ")} and ${MONITORING_GROUPS.at(-1)} only` : me.mon_admin_groups ? `is a member of ${me.mon_admin_groups} WITH ADMIN OPTION: a monitoring role must not have ADMIN OPTION` : me.mon_plan_groups ? `would become a member of ${me.mon_plan_groups} through pg_monitor or pg_read_all_stats: a monitoring role may be a member of ${MONITORING_GROUPS.slice(0, -1).join(", ")} and ${MONITORING_GROUPS.at(-1)} only` : me.mon_owns ? "owns objects on this server: a monitoring role must own nothing" : me.mon_other_dbs ? `has grants in database ${me.mon_other_dbs}: a monitoring role may have grants in this database only` : me.mon_grants ? `has grants on ${me.mon_grants}: a monitoring role may have only CONNECT, USAGE on schemas other than pg_toast, SELECT outside pg_catalog and pg_toast, and the grants pgai makes` : "";
23335
+ if (custom && unsafe)
23336
+ return { next: `${role} ${unsafe}. Use another ${opts.agent ? "monitoring_user" : "--monitoring-user"}` };
23274
23337
  const notes = [caNote(url)].filter((n) => !!n);
23275
23338
  const noted = () => notes.length ? { note: notes.join("; ") } : {};
23276
- const acceptsAnyPassword = async () => logsIn(loginUrlFor(url, me.db, (await resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER })).password)).catch(() => false);
23339
+ const acceptsAnyPassword = async () => logsIn(loginUrlFor(url, user, me.db, (await resolveMonitoringPassword({ monitoringUser: role })).password)).catch(() => false);
23277
23340
  const unchecked = (what) => `this server accepts any password from this host, so ${what} was not checked; if no data arrives, delete the instance (pgai mon instances delete) and deploy again with the right password`;
23278
- if (me.name === DEFAULT_MONITORING_USER) {
23341
+ if (me.name === role) {
23279
23342
  const v = await verifyInitSetup({ client, database: me.db, monitoringUser: me.name, includeOptionalPermissions: false, provider: pgProvider });
23280
23343
  if (v.ok) {
23281
23344
  const used = client.password;
23282
23345
  const inUrl = urlPassword(new URL(url));
23283
23346
  const password = inUrl || (typeof used === "string" ? used : "");
23284
- const putInUrl = `Put the password of ${DEFAULT_MONITORING_USER} in the URL: the monitoring box logs in with it`;
23347
+ const putInUrl = `Put the password of ${role} in the URL: the monitoring box logs in with it`;
23285
23348
  if (!password)
23286
23349
  return { next: putInUrl };
23287
23350
  if (await acceptsAnyPassword()) {
@@ -23289,14 +23352,14 @@ async function prepareDatabase(url, provider, opts = {}) {
23289
23352
  return { next: `This server accepts any password from this host, so the one from the environment was not checked and is not used. ${putInUrl}` };
23290
23353
  notes.push(unchecked("the password in the URL"));
23291
23354
  }
23292
- return { monitoringUrl: monitoringUrlFor(url, me.db, password), ...noted() };
23355
+ return { monitoringUrl: monitoringUrlFor(url, user, me.db, password), ...noted() };
23293
23356
  }
23294
23357
  } else if (me.admin && pgProvider !== "supabase") {
23295
- const exists = `${DEFAULT_MONITORING_USER} already exists on this server`;
23296
- const setPassword = `Set PGAI_MON_PASSWORD to the password of ${DEFAULT_MONITORING_USER}, or give it a new one: pgai mon deploy <admin-url> --reset-password (anything else that logs in as ${DEFAULT_MONITORING_USER} then needs the new password)`;
23297
- const needs = storedPasswordNeeds(monitoringUrlFor(url, me.db, ""));
23358
+ const exists = `${role} already exists on this server`;
23359
+ const setPassword = custom ? `Set PGAI_MON_PASSWORD to the password of ${role}, or give it a new one: PGAI_MON_PASSWORD=<new password> pgai mon deploy <admin-url> --monitoring-user ${role} --reset-password (anything else that logs in as ${role} then needs the new password)` : `Set PGAI_MON_PASSWORD to the password of ${role}, or give it a new one: pgai mon deploy <admin-url> --reset-password (anything else that logs in as ${role} then needs the new password)`;
23360
+ const needs = storedPasswordNeeds(monitoringUrlFor(url, user, me.db, ""));
23298
23361
  const noTls = refusedTls || !usedSsl && me.ssl === "off";
23299
- const tlsOnly = `PostgresAI sends the password it keeps for ${DEFAULT_MONITORING_USER} only over TLS`;
23362
+ const tlsOnly = `PostgresAI sends the password it keeps for ${role} only over TLS`;
23300
23363
  const others = opts.others?.length ? opts.others : undefined;
23301
23364
  const disconnectOthers = others ? disconnectEach(others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
23302
23365
  const reconnectOthers = `(and deploy ${others ? others.join(", ") : "them"} again with it)`;
@@ -23310,25 +23373,28 @@ async function prepareDatabase(url, provider, opts = {}) {
23310
23373
  if (reuse) {
23311
23374
  if (opts.check)
23312
23375
  return { checked: true };
23313
- const { password: unused } = await resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
23314
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: unused, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
23376
+ const { password: unused } = await resolveMonitoringPassword({ monitoringUser: role });
23377
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: unused, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
23315
23378
  await applyInitPlan({ client, plan });
23316
- return { monitoringUrl: monitoringUrlFor(url, me.db, ""), storedPassword: true, ...noted() };
23379
+ return { monitoringUrl: monitoringUrlFor(url, user, me.db, ""), storedPassword: true, ...noted() };
23317
23380
  }
23318
23381
  if (me.mon_exists && opts.agent)
23319
23382
  return { next: `${exists}. Pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set to its password` };
23320
- const unset = !opts.storedPassword ? setPassword : noTls ? `This server takes no TLS, and ${tlsOnly}. ${noTlsWayOut}` : !needs ? `Unset PGAI_MON_PASSWORD: PostgresAI keeps the password of ${DEFAULT_MONITORING_USER} for this server` : `Unset PGAI_MON_PASSWORD, and the URL needs ${needs}: PostgresAI keeps the password of ${DEFAULT_MONITORING_USER} for this server, and sends it only over TLS, to a URL with each parameter once`;
23321
- const { password, generated } = await resolveMonitoringPassword({ passwordEnv: opts.agent ? undefined : process.env.PGAI_MON_PASSWORD, monitoringUser: DEFAULT_MONITORING_USER });
23383
+ const unset = !opts.storedPassword ? setPassword : noTls ? `This server takes no TLS, and ${tlsOnly}. ${noTlsWayOut}` : !needs ? `Unset PGAI_MON_PASSWORD: PostgresAI keeps the password of ${role} for this server` : `Unset PGAI_MON_PASSWORD, and the URL needs ${needs}: PostgresAI keeps the password of ${role} for this server, and sends it only over TLS, to a URL with each parameter once`;
23322
23384
  const reset = !!opts.resetPassword && me.mon_exists;
23385
+ if (custom && (!me.mon_exists || reset) && !(opts.agent ? "" : process.env.PGAI_MON_PASSWORD?.trim())) {
23386
+ return { next: opts.agent ? `${role} is a custom role, and PostgresAI keeps no password for it: pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set` : `Set PGAI_MON_PASSWORD to a password for ${role}: PostgresAI keeps no password for a custom role, so a generated one would be lost` };
23387
+ }
23388
+ const { password, generated } = await resolveMonitoringPassword({ passwordEnv: opts.agent ? undefined : process.env.PGAI_MON_PASSWORD, monitoringUser: role });
23323
23389
  if (me.mon_exists && !reset) {
23324
23390
  if (!process.env.PGAI_MON_PASSWORD?.trim())
23325
- return { next: `${exists}. ${setPassword}`, resettable: true };
23391
+ return { next: `${exists}. ${setPassword}`, ...custom ? {} : { resettable: true } };
23326
23392
  let accepted;
23327
23393
  try {
23328
- accepted = await logsIn(loginUrlFor(url, me.db, password));
23394
+ accepted = await logsIn(loginUrlFor(url, user, me.db, password));
23329
23395
  } catch (err) {
23330
23396
  const orUnset = opts.storedPassword && !noTls ? ", or unset PGAI_MON_PASSWORD: PostgresAI keeps its password for this server" : "";
23331
- return { next: `${exists}, and PGAI_MON_PASSWORD could not be checked from this host (${err instanceof Error ? err.message : String(err)}). Run pgai mon deploy from a host that ${DEFAULT_MONITORING_USER} may connect from${orUnset}` };
23397
+ return { next: `${exists}, and PGAI_MON_PASSWORD could not be checked from this host (${err instanceof Error ? err.message : String(err)}). Run pgai mon deploy from a host that ${role} may connect from${orUnset}` };
23332
23398
  }
23333
23399
  if (!accepted)
23334
23400
  return { next: `${exists} and PGAI_MON_PASSWORD is not its password. ${unset}` };
@@ -23337,27 +23403,27 @@ async function prepareDatabase(url, provider, opts = {}) {
23337
23403
  }
23338
23404
  if (opts.check)
23339
23405
  return { checked: true };
23340
- const monitoringUrl = monitoringUrlFor(url, me.db, password);
23341
- const loginUrl = loginUrlFor(url, me.db, password);
23342
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: password, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: !reset });
23406
+ const monitoringUrl = monitoringUrlFor(url, user, me.db, password);
23407
+ const loginUrl = loginUrlFor(url, user, me.db, password);
23408
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: password, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: !reset });
23343
23409
  try {
23344
23410
  await applyInitPlan({ client, plan });
23345
23411
  } catch (err) {
23346
23412
  if (generated && !me.mon_exists && await logsIn(loginUrl).catch(() => false))
23347
- await dropMonitoringRole(client);
23413
+ await dropMonitoringRole(client, role);
23348
23414
  throw err;
23349
23415
  }
23350
23416
  if (!await logsIn(loginUrl).catch(() => true))
23351
- return { next: `${DEFAULT_MONITORING_USER} was created by someone else meanwhile. ${setPassword}` };
23417
+ return { next: `${role} was created by someone else meanwhile. ${setPassword}` };
23352
23418
  return { monitoringUrl, ...noted(), ...generated && !me.mon_exists ? { generated: true } : {} };
23353
23419
  }
23354
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
23420
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
23355
23421
  return {
23356
23422
  sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
23357
23423
  ${redactPasswordsInSql(s.sql)}`).join(`
23358
23424
 
23359
23425
  `),
23360
- next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${DEFAULT_MONITORING_USER} URL`
23426
+ next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${role} URL`
23361
23427
  };
23362
23428
  } finally {
23363
23429
  await client.end();
@@ -23437,7 +23503,7 @@ function platformDeps(p) {
23437
23503
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
23438
23504
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
23439
23505
  prepare: (url, provider, o = {}) => prepareDatabase(url, provider, { ...o, agent: p.agent }),
23440
- unprepare: (url) => unprepareDatabase(url, { agent: p.agent }),
23506
+ unprepare: (url, monitoringUser) => unprepareDatabase(url, { agent: p.agent, monitoringUser }),
23441
23507
  clickhouseOrg: clickhouseOrgFor,
23442
23508
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
23443
23509
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
@@ -30137,6 +30203,7 @@ async function handleToolCall(req, rootOpts, extra) {
30137
30203
  coupon: args.coupon === undefined || args.coupon === null ? undefined : String(args.coupon),
30138
30204
  yes: args.yes === true,
30139
30205
  vcpus: args.vcpus === undefined || args.vcpus === null ? undefined : vcpusArg(String(args.vcpus)),
30206
+ monitoringUser: args.monitoring_user === undefined || args.monitoring_user === null ? undefined : String(args.monitoring_user),
30140
30207
  waitMs: 0,
30141
30208
  agent: true
30142
30209
  }, {
@@ -30722,6 +30789,7 @@ async function startMcpServer(rootOpts, extra) {
30722
30789
  yes: { type: "boolean", description: "Accept the price of a billed box. Without it, a billed box is not provisioned: the result has status action_required and the price; ask the user, then call again with yes: true" },
30723
30790
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
30724
30791
  vcpus: { type: "integer", minimum: 1, maximum: 1024, description: "vCPUs of the database server. Without it there is no AAS (database load) data for this database: ask the user for it" },
30792
+ monitoring_user: { type: "string", description: "Monitoring role to create or use (default postgres_ai_mon). A custom role always carries its own password: PostgresAI keeps only postgres_ai_mon's, so pass the role's own URL as database_url (an admin URL creates only postgres_ai_mon)" },
30725
30793
  debug: { type: "boolean", description: "Enable verbose debug logs" }
30726
30794
  },
30727
30795
  required: ["database_url"],
@@ -31649,7 +31717,7 @@ function priceText2(q) {
31649
31717
  }
31650
31718
  return base;
31651
31719
  }
31652
- var FIRST_CHECKUP_DELAY_MS2 = 30 * 60000;
31720
+ var FIRST_CHECKUP_DELAY_MS2 = 3 * 60000;
31653
31721
  var POLL_MS2 = 15000;
31654
31722
  var PROVIDERS2 = ["clickhouse", "rds", "supabase", "self-managed"];
31655
31723
  var providerArg2 = (provider) => {
@@ -31771,9 +31839,13 @@ function storedPasswordNeeds2(monitoringUrl) {
31771
31839
  }
31772
31840
  var shellWord2 = (s) => /^[\w./:@%+=,-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
31773
31841
  var disconnectEach2 = (names) => names.map((n) => `pgai mon instances delete ${shellWord2(n)} --yes`).join(" and ");
31774
- function roleUrlFor2(url, db, password, kept) {
31842
+ function loginName2(url, sessionUser, role) {
31843
+ const user = decodeURIComponent(new URL(url).username);
31844
+ return user.startsWith(`${sessionUser}.`) ? role + user.slice(sessionUser.length) : role;
31845
+ }
31846
+ function roleUrlFor2(url, user, db, password, kept) {
31775
31847
  const u = new URL(url);
31776
- u.username = DEFAULT_MONITORING_USER;
31848
+ u.username = encodeURIComponent(user);
31777
31849
  u.password = encodeURIComponent(password);
31778
31850
  u.pathname = `/${encodeURIComponent(db)}`;
31779
31851
  for (const name of [...u.searchParams.keys()])
@@ -31782,8 +31854,8 @@ function roleUrlFor2(url, db, password, kept) {
31782
31854
  u.search = u.search.replace(/@/g, "%40");
31783
31855
  return u.toString();
31784
31856
  }
31785
- var monitoringUrlFor2 = (url, db, password) => roleUrlFor2(url, db, password, URL_PARAMS_KEPT2.filter((p) => p !== "channel_binding"));
31786
- var loginUrlFor2 = (url, db, password) => roleUrlFor2(url, db, password, [...URL_PARAMS_KEPT2, ...URL_PARAMS_TLS2]);
31857
+ var monitoringUrlFor2 = (url, user, db, password) => roleUrlFor2(url, user, db, password, URL_PARAMS_KEPT2.filter((p) => p !== "channel_binding"));
31858
+ var loginUrlFor2 = (url, user, db, password) => roleUrlFor2(url, user, db, password, [...URL_PARAMS_KEPT2, ...URL_PARAMS_TLS2]);
31787
31859
  function caNote2(url) {
31788
31860
  const q = new URL(url).searchParams;
31789
31861
  if (!q.get("sslrootcert") || !/^verify-/.test(q.get("sslmode") ?? ""))
@@ -31910,6 +31982,19 @@ async function connect2(url, opts, deps) {
31910
31982
  assertEncodedUserinfo(url);
31911
31983
  checkUrlParams2(url, opts.agent);
31912
31984
  const name = databaseName3(url);
31985
+ const asked = opts.monitoringUser?.trim();
31986
+ if (opts.monitoringUser !== undefined && !asked) {
31987
+ const flag = opts.agent ? "monitoring_user" : "--monitoring-user";
31988
+ return { status: "action_required", provider, name, next: `${flag} is empty: pass a role name, or leave it out for ${DEFAULT_MONITORING_USER}` };
31989
+ }
31990
+ const monitoringUser = asked && asked !== DEFAULT_MONITORING_USER ? asked : undefined;
31991
+ const role = monitoringUser ?? DEFAULT_MONITORING_USER;
31992
+ if (monitoringUser && /['$%\\\u0000-\u001f\u007f]/.test(monitoringUser)) {
31993
+ return { status: "action_required", provider, name, next: `${opts.agent ? "monitoring_user" : "--monitoring-user"} must not contain ', $, %, backslash or control characters` };
31994
+ }
31995
+ if (monitoringUser && Buffer.byteLength(monitoringUser) > 63) {
31996
+ return { status: "action_required", provider, name, next: `${opts.agent ? "monitoring_user" : "--monitoring-user"} must be at most 63 bytes (Postgres truncates longer role names)` };
31997
+ }
31913
31998
  try {
31914
31999
  const collector = await collectorConnection(url, deps.verifyTls);
31915
32000
  const required = splitChannelBinding(url).value === "require";
@@ -31927,7 +32012,8 @@ async function connect2(url, opts, deps) {
31927
32012
  if (key && provider !== "clickhouse")
31928
32013
  throw new Error("--clickhouse-key applies to ClickHouse Managed Postgres only");
31929
32014
  if (!opts.selfHosted && (provider === "rds" || provider === "supabase")) {
31930
- return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}` };
32015
+ const ignored = monitoringUser ? ` (${opts.agent ? "monitoring_user" : "--monitoring-user"} is not used there)` : "";
32016
+ return { status: "action_required", provider, name, next: `Finish in the console: ${await deps.handoffUrl(provider)}${ignored}` };
31931
32017
  }
31932
32018
  if (opts.selfHosted && opts.resetPassword) {
31933
32019
  return { status: "action_required", provider, name, next: "--reset-password works with PostgresAI Cloud only (it checks what else monitors this server): deploy without --self-hosted, or set PGAI_MON_PASSWORD" };
@@ -32003,13 +32089,13 @@ async function connect2(url, opts, deps) {
32003
32089
  }
32004
32090
  const undo = async (p) => {
32005
32091
  if ("generated" in p && p.generated)
32006
- await deps.unprepare(url).catch(() => false);
32092
+ await deps.unprepare(url, monitoringUser).catch(() => false);
32007
32093
  };
32008
32094
  let lockId;
32009
32095
  const unread = (d) => !d.cluster;
32010
32096
  const onServer = (d) => !!d.cluster && serverOf2(d.cluster) === cluster;
32011
32097
  const othersOnServer = (list) => list.filter((d) => !disconnecting2(d.status) && (unread(d) || onServer(d)));
32012
- const storedPassword = rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
32098
+ const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
32013
32099
  const cutOff = (others) => {
32014
32100
  const on = others.filter((d) => !unread(d)).map((d) => d.name).join(", ");
32015
32101
  const maybe = others.filter(unread).map((d) => d.name).join(", ");
@@ -32019,7 +32105,7 @@ async function connect2(url, opts, deps) {
32019
32105
  "set PGAI_MON_PASSWORD to its password instead",
32020
32106
  `${disconnectEach2(others.map((d) => d.name))} first`
32021
32107
  ];
32022
- return { status: "action_required", provider, name, next: `A new password for ${DEFAULT_MONITORING_USER} ${what}: ${instead.join(", or ")}` };
32108
+ return { status: "action_required", provider, name, next: `A new password for ${role} ${what}: ${instead.join(", or ")}` };
32023
32109
  };
32024
32110
  const others = othersOnServer(rows).filter((d) => !unread(d)).map((d) => d.name);
32025
32111
  if (opts.resetPassword && othersOnServer(rows).length)
@@ -32027,7 +32113,7 @@ async function connect2(url, opts, deps) {
32027
32113
  if (opts.coupon !== undefined && !opts.coupon.trim()) {
32028
32114
  return { status: "action_required", provider, name, next: `${opts.agent ? "coupon" : "--coupon"} is empty: pass a promotion code, or leave ${opts.agent ? "coupon" : "--coupon"} out` };
32029
32115
  }
32030
- const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {} };
32116
+ const prepOpts = { resetPassword: opts.resetPassword, ...storedPassword ? { storedPassword, others } : {}, ...monitoringUser ? { monitoringUser } : {} };
32031
32117
  if (!opts.selfHosted) {
32032
32118
  const probe = await deps.prepare(url, provider, { ...prepOpts, check: true }).catch((err) => {
32033
32119
  if (err instanceof HttpStatusError || /Could not connect to/.test(errorText2(err)))
@@ -32072,7 +32158,7 @@ async function connect2(url, opts, deps) {
32072
32158
  return { status: "action_required", provider, name, ...billing, next: `Another pgai mon deploy --reset-password for ${cluster} is running: wait for it to finish, then re-run (a run that stopped frees the server 15 minutes after it started)` };
32073
32159
  }
32074
32160
  if (err instanceof HttpStatusError && err.status === 404) {
32075
- return { status: "action_required", provider, name, ...billing, next: `This platform cannot lock the server for --reset-password yet: set PGAI_MON_PASSWORD to ${DEFAULT_MONITORING_USER}'s password instead` };
32161
+ return { status: "action_required", provider, name, ...billing, next: `This platform cannot lock the server for --reset-password yet: set PGAI_MON_PASSWORD to ${role}'s password instead` };
32076
32162
  }
32077
32163
  throw err;
32078
32164
  }
@@ -32212,23 +32298,34 @@ async function openConnection2(url, opts) {
32212
32298
  await client.query("set search_path = pg_catalog, pg_temp");
32213
32299
  return { client, usedSsl, refusedTls: fallback && !usedSsl };
32214
32300
  }
32215
- async function dropMonitoringRole2(client) {
32216
- for (const sql of [`drop role ${DEFAULT_MONITORING_USER}`, `drop owned by ${DEFAULT_MONITORING_USER}; drop role ${DEFAULT_MONITORING_USER}`]) {
32301
+ async function dropMonitoringRole2(client, role) {
32302
+ const q = quoteIdent(role);
32303
+ for (const sql of [`drop role ${q}`, `drop owned by ${q}; drop role ${q}`]) {
32217
32304
  if (await client.query(sql).then(() => true, () => false))
32218
32305
  return true;
32219
32306
  }
32220
32307
  return false;
32221
32308
  }
32309
+ var MONITORING_GROUPS2 = ["pg_monitor", "pg_read_all_stats", "pg_read_all_settings", "pg_stat_scan_tables"];
32310
+ var MONITORING_FUNCTIONS2 = [
32311
+ "pg_catalog.pg_stat_file(text)",
32312
+ "pg_catalog.pg_stat_file(text, boolean)",
32313
+ "pg_catalog.pg_ls_dir(text)",
32314
+ "pg_catalog.pg_ls_dir(text, boolean, boolean)",
32315
+ "rds_tools.pg_ls_multixactdir()",
32316
+ "postgres_ai.table_describe(text)"
32317
+ ];
32222
32318
  async function unprepareDatabase2(url, opts = {}) {
32223
32319
  const { client } = await openConnection2(url, opts);
32224
32320
  try {
32225
- return await dropMonitoringRole2(client);
32321
+ return await dropMonitoringRole2(client, opts.monitoringUser || DEFAULT_MONITORING_USER);
32226
32322
  } finally {
32227
32323
  await client.end();
32228
32324
  }
32229
32325
  }
32230
32326
  async function prepareDatabase2(url, provider, opts = {}) {
32231
32327
  const pgProvider = provider === "rds" ? "self-managed" : provider;
32328
+ const role = opts.monitoringUser || DEFAULT_MONITORING_USER;
32232
32329
  const open = (u) => openConnection2(u, opts);
32233
32330
  const logsIn = async (u) => {
32234
32331
  try {
@@ -32256,20 +32353,54 @@ async function prepareDatabase2(url, provider, opts = {}) {
32256
32353
  and pg_has_role(current_user, 'pg_read_all_stats', 'USAGE WITH ADMIN OPTION')))
32257
32354
  and has_database_privilege(current_user, current_database(), 'CREATE')
32258
32355
  and exists (select 1 from pg_extension where extname = 'pg_stat_statements')) as admin,
32259
- exists (select 1 from pg_roles where rolname = '${DEFAULT_MONITORING_USER}') as mon_exists,
32356
+ exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)}) as mon_exists,
32357
+ exists (select 1 from pg_roles where rolname = ${quoteLiteral(role)} and (rolsuper or rolcreatedb or rolcreaterole or rolreplication or rolbypassrls)) as mon_privileged,
32358
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m join pg_roles g
32359
+ on g.oid <> m.oid and pg_has_role(m.oid, g.oid, 'MEMBER')
32360
+ where m.rolname = ${quoteLiteral(role)} and g.rolname not in (${MONITORING_GROUPS2.map(quoteLiteral).join(", ")})) as mon_groups,
32361
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles m
32362
+ join pg_auth_members a on a.member = m.oid join pg_roles g on g.oid = a.roleid
32363
+ where m.rolname = ${quoteLiteral(role)} and a.admin_option) as mon_admin_groups,
32364
+ (select string_agg(g.rolname::text, ', ' order by g.rolname::text collate "C") from pg_roles g
32365
+ where g.rolname not in (${[...MONITORING_GROUPS2, role].map(quoteLiteral).join(", ")})
32366
+ and (pg_has_role('pg_monitor', g.oid, 'MEMBER') or pg_has_role('pg_read_all_stats', g.oid, 'MEMBER'))) as mon_plan_groups,
32367
+ exists (select 1 from pg_shdepend d join pg_roles m on m.oid = d.refobjid
32368
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'o' and m.rolname = ${quoteLiteral(role)}) as mon_owns,
32369
+ (select string_agg(distinct db.datname::text, ', ') from pg_shdepend d join pg_roles m on m.oid = d.refobjid join pg_database db on db.oid = d.dbid
32370
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'a' and m.rolname = ${quoteLiteral(role)}
32371
+ and db.datname <> current_database()) as mon_other_dbs,
32372
+ (select string_agg(distinct pg_describe_object(d.classid, d.objid, d.objsubid), ', ') from pg_shdepend d join pg_roles m on m.oid = d.refobjid
32373
+ where d.refclassid = 'pg_authid'::regclass and d.deptype = 'a' and m.rolname = ${quoteLiteral(role)}
32374
+ and d.dbid in (0, (select oid from pg_database where datname = current_database()))
32375
+ and not exists (select 1 from (
32376
+ select relacl as acl, 'SELECT' as ok from pg_class where d.classid = 'pg_class'::regclass and d.objsubid = 0 and oid = d.objid
32377
+ and ((relnamespace not in ('pg_catalog'::regnamespace, 'pg_toast'::regnamespace) and relkind <> 't') or oid = 'pg_catalog.pg_index'::regclass)
32378
+ union all select attacl, 'SELECT' from pg_attribute where d.classid = 'pg_class'::regclass and attrelid = d.objid and attnum = d.objsubid
32379
+ and (select relnamespace not in ('pg_catalog'::regnamespace, 'pg_toast'::regnamespace) and relkind <> 't' from pg_class where oid = d.objid)
32380
+ union all select nspacl, 'USAGE' from pg_namespace where d.classid = 'pg_namespace'::regclass and oid = d.objid and nspname !~ '^pg_toast'
32381
+ union all select proacl, 'EXECUTE' from pg_proc where d.classid = 'pg_proc'::regclass and oid = d.objid
32382
+ and pronamespace::regnamespace::text || '.' || proname || '(' || array_to_string(proargtypes::oid[]::regtype[], ', ') || ')'
32383
+ in (${MONITORING_FUNCTIONS2.map(quoteLiteral).join(", ")})
32384
+ union all select datacl, 'CONNECT' from pg_database where d.classid = 'pg_database'::regclass and oid = d.objid) o
32385
+ where not exists (select 1 from aclexplode(o.acl) e where e.grantee = d.refobjid and (e.privilege_type <> o.ok or e.is_grantable)))) as mon_grants,
32260
32386
  current_setting('scram_iterations', true) as iterations, current_setting('ssl') as ssl
32261
32387
  from pg_roles where rolname = current_user`)).rows[0];
32388
+ const user = loginName2(url, me.name, role);
32389
+ const custom = role !== DEFAULT_MONITORING_USER;
32390
+ const unsafe = me.mon_privileged ? "is a superuser, or has CREATEDB, CREATEROLE, REPLICATION or BYPASSRLS: a monitoring role must not" : me.mon_groups ? `is a member of ${me.mon_groups}: a monitoring role may be a member of ${MONITORING_GROUPS2.slice(0, -1).join(", ")} and ${MONITORING_GROUPS2.at(-1)} only` : me.mon_admin_groups ? `is a member of ${me.mon_admin_groups} WITH ADMIN OPTION: a monitoring role must not have ADMIN OPTION` : me.mon_plan_groups ? `would become a member of ${me.mon_plan_groups} through pg_monitor or pg_read_all_stats: a monitoring role may be a member of ${MONITORING_GROUPS2.slice(0, -1).join(", ")} and ${MONITORING_GROUPS2.at(-1)} only` : me.mon_owns ? "owns objects on this server: a monitoring role must own nothing" : me.mon_other_dbs ? `has grants in database ${me.mon_other_dbs}: a monitoring role may have grants in this database only` : me.mon_grants ? `has grants on ${me.mon_grants}: a monitoring role may have only CONNECT, USAGE on schemas other than pg_toast, SELECT outside pg_catalog and pg_toast, and the grants pgai makes` : "";
32391
+ if (custom && unsafe)
32392
+ return { next: `${role} ${unsafe}. Use another ${opts.agent ? "monitoring_user" : "--monitoring-user"}` };
32262
32393
  const notes = [caNote2(url)].filter((n) => !!n);
32263
32394
  const noted = () => notes.length ? { note: notes.join("; ") } : {};
32264
- const acceptsAnyPassword = async () => logsIn(loginUrlFor2(url, me.db, (await resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER })).password)).catch(() => false);
32395
+ const acceptsAnyPassword = async () => logsIn(loginUrlFor2(url, user, me.db, (await resolveMonitoringPassword({ monitoringUser: role })).password)).catch(() => false);
32265
32396
  const unchecked = (what) => `this server accepts any password from this host, so ${what} was not checked; if no data arrives, delete the instance (pgai mon instances delete) and deploy again with the right password`;
32266
- if (me.name === DEFAULT_MONITORING_USER) {
32397
+ if (me.name === role) {
32267
32398
  const v = await verifyInitSetup({ client, database: me.db, monitoringUser: me.name, includeOptionalPermissions: false, provider: pgProvider });
32268
32399
  if (v.ok) {
32269
32400
  const used = client.password;
32270
32401
  const inUrl = urlPassword2(new URL(url));
32271
32402
  const password = inUrl || (typeof used === "string" ? used : "");
32272
- const putInUrl = `Put the password of ${DEFAULT_MONITORING_USER} in the URL: the monitoring box logs in with it`;
32403
+ const putInUrl = `Put the password of ${role} in the URL: the monitoring box logs in with it`;
32273
32404
  if (!password)
32274
32405
  return { next: putInUrl };
32275
32406
  if (await acceptsAnyPassword()) {
@@ -32277,14 +32408,14 @@ async function prepareDatabase2(url, provider, opts = {}) {
32277
32408
  return { next: `This server accepts any password from this host, so the one from the environment was not checked and is not used. ${putInUrl}` };
32278
32409
  notes.push(unchecked("the password in the URL"));
32279
32410
  }
32280
- return { monitoringUrl: monitoringUrlFor2(url, me.db, password), ...noted() };
32411
+ return { monitoringUrl: monitoringUrlFor2(url, user, me.db, password), ...noted() };
32281
32412
  }
32282
32413
  } else if (me.admin && pgProvider !== "supabase") {
32283
- const exists = `${DEFAULT_MONITORING_USER} already exists on this server`;
32284
- const setPassword = `Set PGAI_MON_PASSWORD to the password of ${DEFAULT_MONITORING_USER}, or give it a new one: pgai mon deploy <admin-url> --reset-password (anything else that logs in as ${DEFAULT_MONITORING_USER} then needs the new password)`;
32285
- const needs = storedPasswordNeeds2(monitoringUrlFor2(url, me.db, ""));
32414
+ const exists = `${role} already exists on this server`;
32415
+ const setPassword = custom ? `Set PGAI_MON_PASSWORD to the password of ${role}, or give it a new one: PGAI_MON_PASSWORD=<new password> pgai mon deploy <admin-url> --monitoring-user ${role} --reset-password (anything else that logs in as ${role} then needs the new password)` : `Set PGAI_MON_PASSWORD to the password of ${role}, or give it a new one: pgai mon deploy <admin-url> --reset-password (anything else that logs in as ${role} then needs the new password)`;
32416
+ const needs = storedPasswordNeeds2(monitoringUrlFor2(url, user, me.db, ""));
32286
32417
  const noTls = refusedTls || !usedSsl && me.ssl === "off";
32287
- const tlsOnly = `PostgresAI sends the password it keeps for ${DEFAULT_MONITORING_USER} only over TLS`;
32418
+ const tlsOnly = `PostgresAI sends the password it keeps for ${role} only over TLS`;
32288
32419
  const others = opts.others?.length ? opts.others : undefined;
32289
32420
  const disconnectOthers = others ? disconnectEach2(others) : "pgai mon instances delete the server's other databases (pgai mon instances list)";
32290
32421
  const reconnectOthers = `(and deploy ${others ? others.join(", ") : "them"} again with it)`;
@@ -32298,25 +32429,28 @@ async function prepareDatabase2(url, provider, opts = {}) {
32298
32429
  if (reuse) {
32299
32430
  if (opts.check)
32300
32431
  return { checked: true };
32301
- const { password: unused } = await resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
32302
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: unused, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
32432
+ const { password: unused } = await resolveMonitoringPassword({ monitoringUser: role });
32433
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: unused, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
32303
32434
  await applyInitPlan({ client, plan });
32304
- return { monitoringUrl: monitoringUrlFor2(url, me.db, ""), storedPassword: true, ...noted() };
32435
+ return { monitoringUrl: monitoringUrlFor2(url, user, me.db, ""), storedPassword: true, ...noted() };
32305
32436
  }
32306
32437
  if (me.mon_exists && opts.agent)
32307
32438
  return { next: `${exists}. Pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set to its password` };
32308
- const unset = !opts.storedPassword ? setPassword : noTls ? `This server takes no TLS, and ${tlsOnly}. ${noTlsWayOut}` : !needs ? `Unset PGAI_MON_PASSWORD: PostgresAI keeps the password of ${DEFAULT_MONITORING_USER} for this server` : `Unset PGAI_MON_PASSWORD, and the URL needs ${needs}: PostgresAI keeps the password of ${DEFAULT_MONITORING_USER} for this server, and sends it only over TLS, to a URL with each parameter once`;
32309
- const { password, generated } = await resolveMonitoringPassword({ passwordEnv: opts.agent ? undefined : process.env.PGAI_MON_PASSWORD, monitoringUser: DEFAULT_MONITORING_USER });
32439
+ const unset = !opts.storedPassword ? setPassword : noTls ? `This server takes no TLS, and ${tlsOnly}. ${noTlsWayOut}` : !needs ? `Unset PGAI_MON_PASSWORD: PostgresAI keeps the password of ${role} for this server` : `Unset PGAI_MON_PASSWORD, and the URL needs ${needs}: PostgresAI keeps the password of ${role} for this server, and sends it only over TLS, to a URL with each parameter once`;
32310
32440
  const reset = !!opts.resetPassword && me.mon_exists;
32441
+ if (custom && (!me.mon_exists || reset) && !(opts.agent ? "" : process.env.PGAI_MON_PASSWORD?.trim())) {
32442
+ return { next: opts.agent ? `${role} is a custom role, and PostgresAI keeps no password for it: pass its URL as database_url, or run pgai mon deploy in a terminal with PGAI_MON_PASSWORD set` : `Set PGAI_MON_PASSWORD to a password for ${role}: PostgresAI keeps no password for a custom role, so a generated one would be lost` };
32443
+ }
32444
+ const { password, generated } = await resolveMonitoringPassword({ passwordEnv: opts.agent ? undefined : process.env.PGAI_MON_PASSWORD, monitoringUser: role });
32311
32445
  if (me.mon_exists && !reset) {
32312
32446
  if (!process.env.PGAI_MON_PASSWORD?.trim())
32313
- return { next: `${exists}. ${setPassword}`, resettable: true };
32447
+ return { next: `${exists}. ${setPassword}`, ...custom ? {} : { resettable: true } };
32314
32448
  let accepted;
32315
32449
  try {
32316
- accepted = await logsIn(loginUrlFor2(url, me.db, password));
32450
+ accepted = await logsIn(loginUrlFor2(url, user, me.db, password));
32317
32451
  } catch (err) {
32318
32452
  const orUnset = opts.storedPassword && !noTls ? ", or unset PGAI_MON_PASSWORD: PostgresAI keeps its password for this server" : "";
32319
- return { next: `${exists}, and PGAI_MON_PASSWORD could not be checked from this host (${err instanceof Error ? err.message : String(err)}). Run pgai mon deploy from a host that ${DEFAULT_MONITORING_USER} may connect from${orUnset}` };
32453
+ return { next: `${exists}, and PGAI_MON_PASSWORD could not be checked from this host (${err instanceof Error ? err.message : String(err)}). Run pgai mon deploy from a host that ${role} may connect from${orUnset}` };
32320
32454
  }
32321
32455
  if (!accepted)
32322
32456
  return { next: `${exists} and PGAI_MON_PASSWORD is not its password. ${unset}` };
@@ -32325,27 +32459,27 @@ async function prepareDatabase2(url, provider, opts = {}) {
32325
32459
  }
32326
32460
  if (opts.check)
32327
32461
  return { checked: true };
32328
- const monitoringUrl = monitoringUrlFor2(url, me.db, password);
32329
- const loginUrl = loginUrlFor2(url, me.db, password);
32330
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: password, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: !reset });
32462
+ const monitoringUrl = monitoringUrlFor2(url, user, me.db, password);
32463
+ const loginUrl = loginUrlFor2(url, user, me.db, password);
32464
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: password, iterations: Number(me.iterations), includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: !reset });
32331
32465
  try {
32332
32466
  await applyInitPlan({ client, plan });
32333
32467
  } catch (err) {
32334
32468
  if (generated && !me.mon_exists && await logsIn(loginUrl).catch(() => false))
32335
- await dropMonitoringRole2(client);
32469
+ await dropMonitoringRole2(client, role);
32336
32470
  throw err;
32337
32471
  }
32338
32472
  if (!await logsIn(loginUrl).catch(() => true))
32339
- return { next: `${DEFAULT_MONITORING_USER} was created by someone else meanwhile. ${setPassword}` };
32473
+ return { next: `${role} was created by someone else meanwhile. ${setPassword}` };
32340
32474
  return { monitoringUrl, ...noted(), ...generated && !me.mon_exists ? { generated: true } : {} };
32341
32475
  }
32342
- const plan = await buildInitPlan({ database: me.db, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
32476
+ const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
32343
32477
  return {
32344
32478
  sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
32345
32479
  ${redactPasswordsInSql(s.sql)}`).join(`
32346
32480
 
32347
32481
  `),
32348
- next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${DEFAULT_MONITORING_USER} URL`
32482
+ next: `Run the SQL as an admin, with a password of your choice in place of <redacted> (or re-run with an admin URL), then pgai mon deploy again with the ${role} URL`
32349
32483
  };
32350
32484
  } finally {
32351
32485
  await client.end();
@@ -32441,7 +32575,7 @@ function platformDeps2(p) {
32441
32575
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
32442
32576
  resetUnlock: (lockId) => rpc("cloud_monitoring_reset_unlock", { lock_id: lockId }),
32443
32577
  prepare: (url, provider, o = {}) => prepareDatabase2(url, provider, { ...o, agent: p.agent }),
32444
- unprepare: (url) => unprepareDatabase2(url, { agent: p.agent }),
32578
+ unprepare: (url, monitoringUser) => unprepareDatabase2(url, { agent: p.agent, monitoringUser }),
32445
32579
  clickhouseOrg: clickhouseOrgFor2,
32446
32580
  quote: (coupon, cluster) => rpc("cloud_monitoring_quote", { ...coupon ? { promo_code: coupon } : {}, ...cluster ? { db_server: cluster } : {} }),
32447
32581
  billingUrl: (orgAlias) => `${p.uiBaseUrl}/${orgAlias}/billing`,
@@ -36654,6 +36788,46 @@ function trimmedEnv(name) {
36654
36788
  const trimmed = raw.trim();
36655
36789
  return trimmed === "" ? undefined : trimmed;
36656
36790
  }
36791
+ function normalizeOrgAlias(value) {
36792
+ return value.replace(/[ :/?#[\]@!$&()*+,;=.~"']/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
36793
+ }
36794
+ async function createOrg(params) {
36795
+ const name = params.name.trim();
36796
+ const rawAlias = params.alias?.trim();
36797
+ if (!name)
36798
+ throw new Error("Organization name must not be empty.");
36799
+ if (rawAlias !== undefined && !rawAlias)
36800
+ throw new Error("Organization alias must not be empty.");
36801
+ const alias = rawAlias === undefined ? undefined : normalizeOrgAlias(rawAlias);
36802
+ const effectiveAlias = normalizeOrgAlias(alias ?? name);
36803
+ if (effectiveAlias === "") {
36804
+ throw new Error("Organization alias must not be empty after normalization. Pass --alias with letters or digits.");
36805
+ }
36806
+ if (/[^\x21-\x7e]/.test(effectiveAlias)) {
36807
+ throw new Error(alias === undefined ? `The alias derived from the name ('${effectiveAlias}') is not ASCII. Pass --alias with ASCII letters, digits, '-' or '_'.` : "Organization alias must use ASCII letters, digits, '-' or '_'.");
36808
+ }
36809
+ if (!isGlobalTokenValue2(params.apiKey)) {
36810
+ throw new Error("Creating an organization requires a global user token. Sign in with pgai auth login.");
36811
+ }
36812
+ const response = await fetch(`${normalizeBaseUrl(params.apiBaseUrl)}/rpc/user_create_org`, {
36813
+ method: "POST",
36814
+ headers: { "access-token": params.apiKey, "Content-Type": "application/json", Connection: "close" },
36815
+ body: JSON.stringify({ name, alias: alias ?? null })
36816
+ });
36817
+ const text = await response.text();
36818
+ if (!response.ok)
36819
+ throw new Error(formatHttpError("create organization", response.status, text));
36820
+ let result;
36821
+ try {
36822
+ result = JSON.parse(text);
36823
+ } catch {
36824
+ result = null;
36825
+ }
36826
+ if (!result || typeof result !== "object" || Array.isArray(result) || !result.id || typeof result.alias !== "string" || result.alias === "") {
36827
+ throw new Error("Create organization returned an invalid response.");
36828
+ }
36829
+ return result;
36830
+ }
36657
36831
 
36658
36832
  // bin/postgres-ai.ts
36659
36833
  init_util();
@@ -45549,13 +45723,21 @@ async function selfRegisterAndPersist(projectDir, apiKey, projectName, opts, reg
45549
45723
  process.exitCode = 1;
45550
45724
  return reg;
45551
45725
  }
45552
- async function applyMonitoringTargetsConfig() {
45726
+ async function applyMonitoringTargetsConfig(restartReporter = false) {
45553
45727
  console.log("Applying monitoring target configuration...");
45554
45728
  const generateCode = await runCompose(["run", "--rm", "sources-generator"]);
45555
45729
  if (generateCode !== 0)
45556
45730
  return generateCode;
45557
45731
  console.log("Restarting pgwatch collectors to pick up target changes...");
45558
- return runCompose(["up", "-d", "--force-recreate", "pgwatch-prometheus", "pgwatch-postgres"]);
45732
+ const upCode = await runCompose(["up", "-d", "--force-recreate", "pgwatch-prometheus", "pgwatch-postgres"]);
45733
+ if (upCode !== 0)
45734
+ return upCode;
45735
+ if (!restartReporter)
45736
+ return 0;
45737
+ if (await runCompose(["restart", "postgres-reports"]) !== 0) {
45738
+ console.error("\u26A0 Could not restart postgres-reports; the target's first report comes with its next daily run");
45739
+ }
45740
+ return 0;
45559
45741
  }
45560
45742
  async function runCompose(args, grafanaPassword, extraEnv) {
45561
45743
  let composeFile;
@@ -45989,13 +46171,13 @@ Cancelling: nothing has been created yet (Ctrl-C again to quit now).`);
45989
46171
  }
45990
46172
  }
45991
46173
  var mon = program2.command("mon").description("monitoring services management");
45992
- sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)").description("deploy PostgresAI Cloud monitoring for a database: prepare it, provision the monitoring box, print its Health Matrix and dashboard").option("--provider <provider>", "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)").option("--clickhouse-key <id:secret>", "ClickHouse Cloud API key (Basic Service API Reader) for CPU, memory and disk; or CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET").option("--self-hosted", "run the monitoring stack on this machine (mon local-install) instead of PostgresAI Cloud").option("--reset-password", "postgres_ai_mon exists and its password is lost: set a new one (admin URL; refused while another database on the server is monitored)").option("--coupon <code>", "promotion code for the organization's monitoring subscription (applies when it is first created)").option("--vcpus <n>", "vCPUs of the database server; without it there is no AAS (database load) data (asked at a terminal)").addHelpText("after", [
46174
+ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)").description("deploy PostgresAI Cloud monitoring for a database: prepare it, provision the monitoring box, print its Health Matrix and dashboard").option("--provider <provider>", "generic (direct PostgreSQL URL; alias: self-managed) | clickhouse | rds | supabase (default: detected from the host)").option("--clickhouse-key <id:secret>", "ClickHouse Cloud API key (Basic Service API Reader) for CPU, memory and disk; or CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET").option("--self-hosted", "run the monitoring stack on this machine (mon local-install) instead of PostgresAI Cloud").option("--reset-password", "the monitoring role exists and its password is lost: set a new one (admin URL; refused while another database on the server is monitored)").option("--monitoring-user <name>", "monitoring role to create or use", DEFAULT_MONITORING_USER2).option("--coupon <code>", "promotion code for the organization's monitoring subscription (applies when it is first created)").option("--vcpus <n>", "vCPUs of the database server; without it there is no AAS (database load) data (asked at a terminal)").addHelpText("after", [
45993
46175
  "",
45994
46176
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
45995
46177
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
45996
46178
  "the monitoring box, wait, print the Health Matrix (health_url) and Grafana, signed in with",
45997
- "your PostgresAI account (dashboard_url). The box runs its first checkup about 30 minutes",
45998
- "after it is ready (first_checkup_eta).",
46179
+ "your PostgresAI account (dashboard_url). The box runs its first checkup at first_checkup_eta",
46180
+ "at the earliest (3 minutes after it is ready), once every target has data (at most 30 minutes).",
45999
46181
  "",
46000
46182
  "Network: the database must be reachable from this machine and from PostgresAI. Before provisioning,",
46001
46183
  "PostgresAI tests the connection from an unpublished address, so the port must accept connections",
@@ -47251,7 +47433,7 @@ async function addTarget(file, projectDir, connStr, name, env, { apply = true, v
47251
47433
  }
47252
47434
  if (!apply)
47253
47435
  return true;
47254
- const applyCode = await applyMonitoringTargetsConfig();
47436
+ const applyCode = await applyMonitoringTargetsConfig(true);
47255
47437
  if (applyCode !== 0) {
47256
47438
  console.error("Monitoring target was saved, but applying the generated pgwatch sources failed. Run 'postgresai mon restart' to apply manually.");
47257
47439
  process.exitCode = 1;
@@ -47857,7 +48039,7 @@ function interpretEscapes2(str) {
47857
48039
  return str.replace(/\\\\/g, "\x00").replace(/\\n/g, `
47858
48040
  `).replace(/\\t/g, "\t").replace(/\\r/g, "\r").replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\x00/g, "\\");
47859
48041
  }
47860
- program2.command("orgs").description("list organizations this credential can reach").option("--debug", "enable debug output").option("--json", "output raw JSON").action(async (opts) => {
48042
+ var orgsCommand = program2.command("orgs").description("list organizations this credential can reach").option("--debug", "enable debug output").option("--json", "output raw JSON").action(async (opts) => {
47861
48043
  try {
47862
48044
  const rootOpts = program2.opts();
47863
48045
  const cfg = readConfig();
@@ -47880,6 +48062,24 @@ program2.command("orgs").description("list organizations this credential can rea
47880
48062
  process.exitCode = 1;
47881
48063
  }
47882
48064
  });
48065
+ orgsCommand.command("create").description("create an organization (requires a global user token; no org selection needed)").requiredOption("--name <name>", "organization display name").option("--alias <alias>", "unique organization alias (default: generated from name)").option("--json", "output the created organization as JSON").addHelpText("after", `
48066
+ Example: pgai orgs create --name 'My team' --alias my-team --json
48067
+ Get a global user token with 'pgai auth login': choose 'All my organizations (global token)'
48068
+ (preselected when you have no organization yet), or create one at
48069
+ https://console.postgres.ai/profile/global-tokens and run 'pgai auth --set-key <token>'.`).action(async (opts) => {
48070
+ try {
48071
+ const rootOpts = program2.opts();
48072
+ const { apiKey } = getConfig(rootOpts);
48073
+ if (!apiKey)
48074
+ throw new Error("API key is required. Run 'pgai auth login' first or set --api-key.");
48075
+ const { apiBaseUrl } = resolveBaseUrls2(rootOpts, readConfig());
48076
+ const result = await createOrg({ apiKey, apiBaseUrl, name: opts.name, alias: opts.alias });
48077
+ printResult(result, opts.json || orgsCommand.opts().json);
48078
+ } catch (err) {
48079
+ console.error(err instanceof Error ? err.message : String(err));
48080
+ process.exitCode = 1;
48081
+ }
48082
+ });
47883
48083
  withOrgOptions(program2.command("promql")).description("run a PromQL query on a monitoring instance's own metric store").argument("<expr>", "PromQL expression").option("--instance <uuid>", "monitoring instance id (default: this box's .pgwatch-config); not with --project").option("--project <id|alias>", "the project's monitoring instance, by project id, alias or name; not with --instance").option("--at <rfc3339>", "evaluate an instant query at this time (default: now; ignored with --range)").option("--range", "run a range query (requires --start, --end, --step)").option("--start <rfc3339>", "range start").option("--end <rfc3339>", "range end").option("--step <duration>", "range step, e.g. 60s or 5m").option("--timeout <duration>", "how long to wait for an answer (default: sized from the instance's poll pacing; 11m if the platform does not report it)").option("--json", "output the raw result payload").action(async (expr, opts) => {
47884
48084
  let queuedJobId = null;
47885
48085
  try {
@@ -7,14 +7,10 @@ grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
7
7
  grant pg_monitor to {{ROLE_IDENT}};
8
8
  grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
9
9
 
10
- -- Required for cluster-wide pg_stat_statements collection.
11
- -- pg_stat_statements is backed by shared memory and holds entries for every database
12
- -- in the cluster, but a role without pg_read_all_stats sees other users' rows with
13
- -- queryid and query text redacted to NULL -- which collapses the per-queryid grouping
14
- -- in the pg_stat_statements metric. pg_monitor already implies pg_read_all_stats;
15
- -- granting it explicitly documents the dependency and keeps the metric working if the
16
- -- pg_monitor grant above is ever narrowed. Idempotent.
17
- grant pg_read_all_stats to {{ROLE_IDENT}};
10
+ -- Cluster-wide pg_stat_statements collection needs pg_read_all_stats (without it, other
11
+ -- users' rows have queryid and query text redacted to NULL). pg_monitor includes it, so it
12
+ -- is not granted directly: on PostgreSQL 16+ that needs ADMIN OPTION on pg_read_all_stats,
13
+ -- which Supabase's `postgres` role does not have (it has ADMIN OPTION on pg_monitor only).
18
14
 
19
15
  -- Create postgres_ai schema for our objects
20
16
  -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.18.0-dev.8",
3
+ "version": "0.18.0-dev.9",
4
4
  "description": "postgres_ai CLI",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
@@ -7,14 +7,10 @@ grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
7
7
  grant pg_monitor to {{ROLE_IDENT}};
8
8
  grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
9
9
 
10
- -- Required for cluster-wide pg_stat_statements collection.
11
- -- pg_stat_statements is backed by shared memory and holds entries for every database
12
- -- in the cluster, but a role without pg_read_all_stats sees other users' rows with
13
- -- queryid and query text redacted to NULL -- which collapses the per-queryid grouping
14
- -- in the pg_stat_statements metric. pg_monitor already implies pg_read_all_stats;
15
- -- granting it explicitly documents the dependency and keeps the metric working if the
16
- -- pg_monitor grant above is ever narrowed. Idempotent.
17
- grant pg_read_all_stats to {{ROLE_IDENT}};
10
+ -- Cluster-wide pg_stat_statements collection needs pg_read_all_stats (without it, other
11
+ -- users' rows have queryid and query text redacted to NULL). pg_monitor includes it, so it
12
+ -- is not granted directly: on PostgreSQL 16+ that needs ADMIN OPTION on pg_read_all_stats,
13
+ -- which Supabase's `postgres` role does not have (it has ADMIN OPTION on pg_monitor only).
18
14
 
19
15
  -- Create postgres_ai schema for our objects
20
16
  -- Using IF NOT EXISTS for idempotency - prepare-db can be run multiple times