postgresai 0.18.0-dev.14 → 0.18.0-dev.16

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.
@@ -13533,7 +13533,7 @@ var {
13533
13533
  // package.json
13534
13534
  var package_default = {
13535
13535
  name: "postgresai",
13536
- version: "0.18.0-dev.14",
13536
+ version: "0.18.0-dev.16",
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.14";
16896
+ var version = "0.18.0-dev.16";
16897
16897
  var package_default2 = {
16898
16898
  name: "postgresai",
16899
16899
  version,
@@ -22045,6 +22045,42 @@ function safeDoDelimiter(...values) {
22045
22045
  function redactPasswordsInSql(sql) {
22046
22046
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
22047
22047
  }
22048
+ function renderInitPlanSql(plan) {
22049
+ const lines = [
22050
+ "-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.",
22051
+ "begin;"
22052
+ ];
22053
+ for (const step of plan.steps) {
22054
+ const sql = redactPasswordsInSql(step.sql);
22055
+ lines.push(`
22056
+ -- ${step.name}${step.optional ? " (optional)" : ""}`);
22057
+ if (!step.optional) {
22058
+ lines.push(sql);
22059
+ continue;
22060
+ }
22061
+ const delimiter = (base) => {
22062
+ let i = 0;
22063
+ while (sql.includes(`$${base}_${i}$`))
22064
+ i++;
22065
+ return `$${base}_${i}$`;
22066
+ };
22067
+ const outer = delimiter("pgai_optional_outer");
22068
+ const inner = delimiter("pgai_optional_sql");
22069
+ lines.push(`do ${outer}
22070
+ begin
22071
+ begin
22072
+ execute ${inner}
22073
+ ${sql}
22074
+ ${inner};
22075
+ exception when others then
22076
+ raise warning 'optional SQL step ${step.name} skipped: %', sqlerrm;
22077
+ end;
22078
+ end ${outer};`);
22079
+ }
22080
+ lines.push("commit;");
22081
+ return lines.join(`
22082
+ `);
22083
+ }
22048
22084
  function maskConnectionString(dbUrl) {
22049
22085
  let masked = dbUrl;
22050
22086
  const head = dbUrl.match(/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^:@\/?#]*):([\s\S]*)$/i);
@@ -22295,7 +22331,7 @@ async function buildInitPlan(params) {
22295
22331
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
22296
22332
  begin
22297
22333
  create user ${qRole} with password ${qPwVerifier};
22298
- exception when duplicate_object then
22334
+ exception when duplicate_object or unique_violation then
22299
22335
  null;
22300
22336
  end;
22301
22337
  end if;${params.keepExistingPassword ? "" : `
@@ -22348,9 +22384,21 @@ async function applyInitPlan(params) {
22348
22384
  throw e;
22349
22385
  }
22350
22386
  };
22387
+ const concurrent = (e) => /tuple concurrently (updated|deleted)/.test(e instanceof Error ? e.message : String(e));
22388
+ const executeRetried = async (step) => {
22389
+ for (let attempt = 1;; attempt++) {
22390
+ try {
22391
+ return await executeStep(step);
22392
+ } catch (e) {
22393
+ if (attempt >= 3 || !concurrent(e))
22394
+ throw e;
22395
+ await new Promise((r) => setTimeout(r, 200 * attempt));
22396
+ }
22397
+ }
22398
+ };
22351
22399
  for (const step of params.plan.steps.filter((s) => !s.optional)) {
22352
22400
  try {
22353
- await executeStep(step);
22401
+ await executeRetried(step);
22354
22402
  applied.push(step.name);
22355
22403
  } catch (e) {
22356
22404
  const msg = e instanceof Error ? e.message : String(e);
@@ -22570,6 +22618,8 @@ function monitoringStatus(raw) {
22570
22618
  return "inactive";
22571
22619
  if (/fail|error/.test(raw ?? ""))
22572
22620
  return "failed";
22621
+ if (raw === "ip_reserved")
22622
+ return "action_required";
22573
22623
  return "in_progress";
22574
22624
  }
22575
22625
  function dblabStatus(deployStatus) {
@@ -22996,6 +23046,7 @@ function connectStatus(row, provider = row.provider, fresh = false) {
22996
23046
  return {
22997
23047
  ...base,
22998
23048
  status,
23049
+ ...row.egress_ip ? { egress_ip: row.egress_ip } : {},
22999
23050
  ...fresh ? { first_checkup_eta: new Date(Date.now() + FIRST_CHECKUP_DELAY_MS).toISOString() } : {},
23000
23051
  next: row.health_url || row.dashboard_url ? `Open ${row.health_url || row.dashboard_url}` : `pgai mon instances watch ${row.id}`
23001
23052
  };
@@ -23004,6 +23055,8 @@ function connectStatus(row, provider = row.provider, fresh = false) {
23004
23055
  return { ...base, status, next: "none" };
23005
23056
  if (status === "failed")
23006
23057
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
23058
+ if (row.status === "ip_reserved" && row.egress_ip)
23059
+ return { ...allowIpResult(row, provider, row.name, { waitMs: 0 }, ""), ...base, status: "action_required", step: "allow_ip" };
23007
23060
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
23008
23061
  }
23009
23062
  var ESCAPES = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
@@ -23017,6 +23070,12 @@ function boxWords(state) {
23017
23070
  return "starting";
23018
23071
  if (state === "registered")
23019
23072
  return "installing monitoring";
23073
+ if (state === "waiting_for_access")
23074
+ return "waiting for database access";
23075
+ if (state === "ip_reserving")
23076
+ return "reserving its IP";
23077
+ if (state === "ip_reserved")
23078
+ return "waiting for its IP to be allowed";
23020
23079
  return monitoringStatus(state).replace("_", " ");
23021
23080
  }
23022
23081
  async function billingFor(q, name, opts, deps, show, ask) {
@@ -23066,6 +23125,9 @@ async function connect(url, opts, deps) {
23066
23125
  if (project !== undefined && provider !== "supabase") {
23067
23126
  return { status: "action_required", provider, name: url ? databaseName2(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
23068
23127
  }
23128
+ if ((opts.ipFirst || opts.ipAllowed) && (opts.selfHosted || provider === "supabase")) {
23129
+ return { status: "action_required", provider, name: url ? databaseName2(url) : "", next: `${opts.agent ? "ip_first / ip_allowed apply" : "--ip-first and --ip-allowed apply"} to PostgresAI Cloud monitoring of a database URL only` };
23130
+ }
23069
23131
  if (!url) {
23070
23132
  if (provider !== "supabase")
23071
23133
  return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
@@ -23124,12 +23186,24 @@ async function connect(url, opts, deps) {
23124
23186
  return live.find(byCluster) ?? live.find(byName);
23125
23187
  };
23126
23188
  const rows = opts.selfHosted ? [] : await deps.list();
23127
- const known = new Set(rows.map((d) => d.id));
23189
+ const known = new Map(rows.map((d) => [d.id, d.status]));
23128
23190
  const findMade = (list) => {
23129
- const fresh = list.filter((d) => !known.has(d.id));
23191
+ const fresh = list.filter((d) => !known.has(d.id) || reservedStatus(known.get(d.id)) && !reservedStatus(d.status));
23130
23192
  return fresh.find(byCluster) ?? fresh.find(byName);
23131
23193
  };
23132
23194
  let row = findDatabase(rows);
23195
+ let continuing = false;
23196
+ let ownId;
23197
+ if (row && reservedStatus(row.status)) {
23198
+ if (!opts.ipAllowed) {
23199
+ const asked = await allowIpStep(row, { provider, name, url, opts, deps, progress });
23200
+ if (asked !== "continue")
23201
+ return asked;
23202
+ }
23203
+ continuing = true;
23204
+ ownId = row.id;
23205
+ row = undefined;
23206
+ }
23133
23207
  const fresh = !row;
23134
23208
  let note = "";
23135
23209
  let billing = {};
@@ -23170,7 +23244,7 @@ async function connect(url, opts, deps) {
23170
23244
  }
23171
23245
  }
23172
23246
  if (row && opts.resetPassword) {
23173
- return { status: "action_required", provider, name, id: row.id, next: `${name} is already monitored, and its monitoring uses the current password: ${disconnectEach([deleteRef(row, rows)])} first` };
23247
+ return { status: "action_required", provider, name, id: row.id, next: `${row.name} is already monitored, and its monitoring uses the current password. Delete it, then run this deploy again with --reset-password: ${disconnectEach([deleteRef(row, rows)])}` };
23174
23248
  }
23175
23249
  if (row && key) {
23176
23250
  const found = await findOrg();
@@ -23199,7 +23273,7 @@ async function connect(url, opts, deps) {
23199
23273
  const unread = (d) => !d.cluster;
23200
23274
  const onServer = (d) => !!d.cluster && serverOf(d.cluster) === cluster;
23201
23275
  const usesRole = (d) => !["deleting", "deleted", "inactive"].includes(stateOf(d.status)) && !(d.status === "failed" && !d.registered_at);
23202
- const othersOnServer = (list) => list.filter((d) => usesRole(d) && (unread(d) || onServer(d)));
23276
+ const othersOnServer = (list) => list.filter((d) => d.id !== ownId && usesRole(d) && (unread(d) || onServer(d)));
23203
23277
  const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
23204
23278
  const cutOff = (others, list) => {
23205
23279
  const label = (d) => deleteRef(d, list) === d.id ? `${d.name} (id ${d.id})` : d.name;
@@ -23285,9 +23359,9 @@ async function connect(url, opts, deps) {
23285
23359
  try {
23286
23360
  if (lockId) {
23287
23361
  const now = await deps.list();
23288
- const same = findDatabase(now);
23362
+ const same = findDatabase(now.filter((d) => d.id !== ownId));
23289
23363
  if (same)
23290
- return { status: "action_required", provider, name, id: same.id, ...billing, next: `${name} is already monitored, and its monitoring uses the current password: ${disconnectEach([deleteRef(same, now)])} first` };
23364
+ return { status: "action_required", provider, name, id: same.id, ...billing, next: `${same.name} is already monitored, and its monitoring uses the current password. Delete it, then run this deploy again with --reset-password: ${disconnectEach([deleteRef(same, now)])}` };
23291
23365
  const others = othersOnServer(now);
23292
23366
  if (others.length)
23293
23367
  return { ...cutOff(others, now), ...billing };
@@ -23301,6 +23375,16 @@ async function connect(url, opts, deps) {
23301
23375
  throw new CancelledError;
23302
23376
  }
23303
23377
  if ("next" in prepared) {
23378
+ if ((continuing || opts.ipAllowed) && /created by someone else meanwhile/.test(prepared.next)) {
23379
+ for (let tries = 0;tries < 10; tries++) {
23380
+ const box = findDatabase(await deps.list());
23381
+ if (!box)
23382
+ break;
23383
+ if (!reservedStatus(box.status))
23384
+ return follow(box, { provider, name, fresh, billing, billingUrl, undoRole, note, place, url }, opts, deps, progress);
23385
+ await deps.sleep(2000);
23386
+ }
23387
+ }
23304
23388
  const { resettable, ...refusal } = prepared;
23305
23389
  return { status: "action_required", provider, name, ...billing, ...refusal };
23306
23390
  }
@@ -23313,8 +23397,12 @@ async function connect(url, opts, deps) {
23313
23397
  return { status: "ready", provider, name, dashboard_url: "http://localhost:3000", host_metrics: !!ch, next: `pgai mon health${note}` };
23314
23398
  }
23315
23399
  progress("provisioning", `Provisioning monitoring for ${name}`);
23316
- created = await deps.create({
23317
- db_url: prepared.monitoringUrl,
23400
+ const monitoringUrl = prepared.monitoringUrl;
23401
+ const request = (ipAllowed) => deps.create({
23402
+ db_url: monitoringUrl,
23403
+ allow_ip_fallback: true,
23404
+ ...opts.ipFirst ? { ip_first: true } : {},
23405
+ ...ipAllowed ? { ip_allowed: true } : {},
23318
23406
  ...provider === "clickhouse" ? { provider } : {},
23319
23407
  ...key && ch ? { clickhouse_org_id: ch.orgId, clickhouse_key_id: key.keyId, clickhouse_key_secret: key.keySecret } : {},
23320
23408
  ...opts.coupon ? { promo_code: opts.coupon } : {},
@@ -23322,7 +23410,38 @@ async function connect(url, opts, deps) {
23322
23410
  ...opts.name ? { project_name: opts.name } : {},
23323
23411
  ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
23324
23412
  ...vcpus ? { vcpus } : {}
23413
+ });
23414
+ const refused = async (c) => {
23415
+ const row = await waitForIp(c.id, deps) ?? { id: c.id, name: c.name, status: c.status };
23416
+ const why = [c.error, c.billing_warning].filter(Boolean).join(" ");
23417
+ return { ...c, status: "allow_ip", result: { ...allowIpResult(row, provider, name, opts, url), next: `${why} Then: ${continueCommand(opts, url)}` } };
23418
+ };
23419
+ const continued = async () => {
23420
+ const c = await request(true);
23421
+ return reservedStatus(c.status) && c.error ? refused(c) : c;
23422
+ };
23423
+ created = await request(continuing || !!opts.ipAllowed).then(async (c) => {
23424
+ if (reservedStatus(c.status))
23425
+ known.set(c.id, c.status);
23426
+ if (reservedStatus(c.status) && c.error)
23427
+ return refused(c);
23428
+ if (!reservedStatus(c.status))
23429
+ return c;
23430
+ const reservation = await waitForIp(c.id, deps);
23431
+ if (!reservation || !reservedStatus(reservation.status))
23432
+ return { ...c, status: reservation?.status ?? "failed", error: reservation ? undefined : "The IP reservation did not report back in time; see pgai mon instances list." };
23433
+ if (continuing && c.status === "ip_reserving" && reservation.status === "ip_reserved")
23434
+ return continued();
23435
+ const asked = await allowIpStep(reservation, { provider, name, url, opts, deps, progress });
23436
+ if (asked !== "continue")
23437
+ return { ...c, status: "allow_ip", result: asked };
23438
+ return continued();
23325
23439
  }).catch(async (err) => {
23440
+ if ((continuing || opts.ipAllowed) && err instanceof HttpStatusError && err.status === 409 && /already monitored/.test(err.message)) {
23441
+ const box = findDatabase(await deps.list());
23442
+ if (box && !reservedStatus(box.status))
23443
+ return { id: box.id, name: box.name, status: box.status ?? "launch_requested" };
23444
+ }
23326
23445
  if (err instanceof HttpStatusError && (err.status < 500 || err.sqlstate))
23327
23446
  await undo(prepared);
23328
23447
  else
@@ -23363,6 +23482,12 @@ async function connect(url, opts, deps) {
23363
23482
  const gone = `PostgresAI no longer keeps the password of ${DEFAULT_MONITORING_USER} for this server`;
23364
23483
  return { status: "action_required", provider, name, ...billing, next: opts.agent ? `${gone}: pass its URL as database_url, or run pgai mon deploy <admin-url> --reset-password in a terminal` : `${gone}: re-run with --reset-password (anything else that logs in as ${DEFAULT_MONITORING_USER} then needs the new one), or set PGAI_MON_PASSWORD to its password` };
23365
23484
  }
23485
+ if (created.status === "allow_ip" && created.result) {
23486
+ const now = findDatabase(await deps.list().catch(() => []));
23487
+ if (!now || reservedStatus(now.status))
23488
+ await undo(prepared);
23489
+ return { ...created.result, ...billing };
23490
+ }
23366
23491
  if (created.status === "failed") {
23367
23492
  await undo(prepared);
23368
23493
  return { status: "failed", provider, name, id: created.id, next: `${created.error} Re-run pgai mon deploy later.` };
@@ -23377,7 +23502,70 @@ async function connect(url, opts, deps) {
23377
23502
  const made = prepared;
23378
23503
  undoRole = () => undo(made);
23379
23504
  }
23380
- return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
23505
+ return follow(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place, url }, opts, deps, progress);
23506
+ }
23507
+ var reservedStatus = (status) => status === "ip_reserving" || status === "ip_reserved";
23508
+ var IP_POLL_MS = 3000;
23509
+ var IP_WAIT_MS = 120000;
23510
+ async function waitForIp(id, deps) {
23511
+ for (const deadline = deps.now() + IP_WAIT_MS;; ) {
23512
+ const row = (await deps.list().catch(() => [])).find((d) => d.id === id);
23513
+ if (row && row.status !== "ip_reserving")
23514
+ return row;
23515
+ if (deps.now() >= deadline)
23516
+ return;
23517
+ await deps.sleep(IP_POLL_MS);
23518
+ }
23519
+ }
23520
+ var continueCommand = (opts, url) => opts.agent ? "call deploy_monitoring again with ip_allowed: true" : `pgai mon deploy ${url ? quoteArg(maskConnectionString(url)) : "<database URL>"} --yes --ip-allowed`;
23521
+ var quoteArg = (s) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
23522
+ var heldUntil = (iso) => iso ? iso.replace(/T(\d\d:\d\d).*$/, " $1 UTC") : "";
23523
+ function allowIpResult(row, provider, name, opts, url, stopped = false) {
23524
+ const [host, port] = row.cluster ? [row.cluster.replace(/:\d+$/, ""), Number(row.cluster.match(/:(\d+)$/)?.[1] ?? 5432)] : [undefined, undefined];
23525
+ const ip = row.egress_ip ?? undefined;
23526
+ const cidr = ip ? `${ip}/32` : undefined;
23527
+ const allow = `Allow inbound TCP ${port ?? 5432} from ${cidr} on ${host ?? "the database"}`;
23528
+ return {
23529
+ status: "action_required",
23530
+ step: "allow_ip",
23531
+ provider,
23532
+ name,
23533
+ id: row.id,
23534
+ ...row.cloud ? { cloud: row.cloud, location: row.location ?? undefined } : {},
23535
+ ip,
23536
+ cidr,
23537
+ host,
23538
+ port,
23539
+ ...row.reserved_until ? { reserved_until: row.reserved_until } : {},
23540
+ ...row.last_error ? { last_error: row.last_error } : {},
23541
+ ...row.precheck_error ? { precheck_error: row.precheck_error } : {},
23542
+ egress_ip: ip,
23543
+ next: stopped ? `Stopped. ${ip} stays reserved until ${heldUntil(row.reserved_until)}. ${allow}, then: ${continueCommand(opts, url)}` : `${allow}, then ${opts.agent ? continueCommand(opts, url) : `re-run with --yes --ip-allowed: ${continueCommand(opts, url)}`}`
23544
+ };
23545
+ }
23546
+ async function allowIpStep(row, c) {
23547
+ if (row.status === "ip_reserving")
23548
+ row = await waitForIp(row.id, c.deps) ?? row;
23549
+ if (!reservedStatus(row.status) || !row.egress_ip) {
23550
+ return {
23551
+ status: "action_required",
23552
+ provider: c.provider,
23553
+ name: c.name,
23554
+ id: row.id,
23555
+ next: row.status === "ip_reserving" ? `The IP is still being reserved: re-run in a minute, or see pgai mon instances list` : `See pgai mon instances list (${row.status ?? "unknown"})`
23556
+ };
23557
+ }
23558
+ const r = allowIpResult(row, c.provider, c.name, c.opts, c.url);
23559
+ c.progress("allow_ip", `Reserved IP for the monitoring box: ${r.ip}`, { ip: r.ip, cidr: r.cidr, host: r.host, port: r.port, reserved_until: r.reserved_until, id: row.id });
23560
+ if (!c.deps.allowIp)
23561
+ return r;
23562
+ const why = row.last_error ? `The box could not connect from ${r.ip}: ${row.last_error}` : c.opts.ipFirst ? "You asked for the IP first (--ip-first)." : !row.precheck_error ? "The IP was reserved first, as asked." : `PostgresAI could not connect to ${r.host}:${r.port} (${row.precheck_error}). The database likely allows only listed IPs.`;
23563
+ const answer = await c.deps.allowIp([
23564
+ `Monitoring box IP: ${r.ip}${row.cloud ? ` (${cloudWord(row.cloud)}, ${row.location})` : ""}`,
23565
+ why,
23566
+ `Allow inbound TCP ${r.port} from ${r.cidr} on ${r.host}, then continue. The IP is held until ${heldUntil(row.reserved_until)} and stays this box's IP.`
23567
+ ]);
23568
+ return answer === "continue" ? "continue" : allowIpResult(row, c.provider, c.name, c.opts, c.url, true);
23381
23569
  }
23382
23570
  async function placeBox(deps, opts, where, progress) {
23383
23571
  if (!deps.deployOptions)
@@ -23720,6 +23908,7 @@ async function lookForBox(findMade, opts, deps, started) {
23720
23908
  }
23721
23909
  async function follow(row, f, opts, deps, progress) {
23722
23910
  const { provider, name, fresh, billingUrl, undoRole, note } = f;
23911
+ const url = (_) => f.url ?? name;
23723
23912
  const billing = { ...f.billing, ...f.place };
23724
23913
  let shown;
23725
23914
  for (const deadline = deps.now() + opts.waitMs;; ) {
@@ -23735,10 +23924,16 @@ async function follow(row, f, opts, deps, progress) {
23735
23924
  next: chargeFailed(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
23736
23925
  };
23737
23926
  }
23927
+ if (row.status === "ip_reserved") {
23928
+ if (undoRole)
23929
+ await undoRole();
23930
+ return { ...allowIpResult(row, provider, name, opts, url(row)), ...billing };
23931
+ }
23738
23932
  const result = connectStatus(row, provider, fresh);
23739
23933
  const state = boxState(row);
23740
- if (state !== shown && (shown !== undefined || result.status === "in_progress"))
23741
- progress("box", `Monitoring box: ${boxWords(state)}`, { state, id: row.id });
23934
+ if (state !== shown && (shown !== undefined || result.status === "in_progress")) {
23935
+ progress("box", state === "waiting_for_access" && row.egress_ip ? `Monitoring box: waiting for database access from ${row.egress_ip}${row.last_error ? ` (${row.last_error})` : ""}` : `Monitoring box: ${boxWords(state)}`, { state, id: row.id, ...state === "waiting_for_access" && row.egress_ip ? { ip: row.egress_ip, ...row.last_error ? { error: row.last_error } : {} } : {} });
23936
+ }
23742
23937
  shown = state;
23743
23938
  if (result.status !== "in_progress" || deps.now() >= deadline) {
23744
23939
  const final = deps.links ? connectStatus(await deps.links(row), provider, fresh) : result;
@@ -23958,10 +24153,7 @@ async function prepareDatabase(url, provider, opts = {}) {
23958
24153
  }
23959
24154
  const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
23960
24155
  return {
23961
- sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
23962
- ${redactPasswordsInSql(s.sql)}`).join(`
23963
-
23964
- `),
24156
+ sql: renderInitPlanSql(plan),
23965
24157
  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`
23966
24158
  };
23967
24159
  } finally {
@@ -24038,14 +24230,43 @@ function platformDeps(p) {
24038
24230
  orgAlias = projects = undefined;
24039
24231
  return;
24040
24232
  });
24041
- const { dashboard_url, host_metrics, ...rest } = row;
24042
- return { ...rest, ...health_url ? { health_url } : {}, dashboard_url: grafanaOAuthUrl(dashboard_url), host_metrics };
24233
+ const { dashboard_url, host_metrics, host_metrics_source, ...rest } = row;
24234
+ return {
24235
+ ...rest,
24236
+ ...health_url ? { health_url } : {},
24237
+ dashboard_url: grafanaOAuthUrl(dashboard_url),
24238
+ host_metrics,
24239
+ ...host_metrics_source !== undefined ? { host_metrics_source } : {}
24240
+ };
24043
24241
  };
24044
24242
  return {
24045
24243
  verifyTls: verifyCollectorTls,
24046
24244
  list: () => rpc("cloud_monitoring_list"),
24047
24245
  links: withLinks,
24048
- create: (body) => rpc("cloud_monitoring_connect", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS : CONNECT_TIMEOUT_MS),
24246
+ create: async (body) => {
24247
+ const { allow_ip_fallback: _fallback, ip_first, ip_allowed, ...older } = body;
24248
+ const asked = !!(ip_first || ip_allowed);
24249
+ const connectMs = p.agent ? AGENT_CONNECT_TIMEOUT_MS : CONNECT_TIMEOUT_MS;
24250
+ const connectTimeout = { timeoutMs: connectMs, timeoutCeilingMs: connectMs };
24251
+ try {
24252
+ return await callRpc({
24253
+ apiKey: p.apiKey,
24254
+ apiBaseUrl: p.apiBaseUrl,
24255
+ fn: "cloud_monitoring_connect",
24256
+ body,
24257
+ operation: "cloud monitoring connect",
24258
+ debug: p.debug,
24259
+ orgScope: p.orgScope,
24260
+ ...connectTimeout,
24261
+ ...asked ? {} : { fallbackBody: older }
24262
+ });
24263
+ } catch (err) {
24264
+ if (asked && err instanceof HttpStatusError && err.status === 404 && /cloud_monitoring_connect/.test(err.message)) {
24265
+ throw new Error("This PostgresAI platform does not support --ip-first or --ip-allowed yet: deploy without them");
24266
+ }
24267
+ throw err;
24268
+ }
24269
+ },
24049
24270
  disconnect: (id) => rpc("cloud_monitoring_disconnect", { instance_id: id }),
24050
24271
  setVcpus: (id, vcpus) => rpc("cloud_monitoring_set_vcpus", { instance_id: id, vcpus }),
24051
24272
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
@@ -30759,6 +30980,8 @@ async function handleToolCall(req, rootOpts, extra) {
30759
30980
  monitoringUser: args.monitoring_user === undefined || args.monitoring_user === null ? undefined : String(args.monitoring_user),
30760
30981
  cloud: args.cloud === undefined || args.cloud === null ? undefined : String(args.cloud),
30761
30982
  location: args.location === undefined || args.location === null ? undefined : String(args.location),
30983
+ ipFirst: args.ip_first === true,
30984
+ ipAllowed: args.ip_allowed === true,
30762
30985
  waitMs: 0,
30763
30986
  agent: true
30764
30987
  }, {
@@ -31333,7 +31556,7 @@ async function startMcpServer(rootOpts, extra) {
31333
31556
  },
31334
31557
  {
31335
31558
  name: "deploy_monitoring",
31336
- description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. Supabase needs no password (PostgresAI prepares the database through the Supabase Management API): the first time, the result is action_required with a consent link in next; give it to the user to open and approve, then call again. Elsewhere the URL must carry its password, and only these query parameters: sslmode, channel_binding, application_name. PGAI_MON_PASSWORD, PGPASSWORD and CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET of the server process are not used (pass clickhouse_key), and a TLS failure is not retried in plaintext (say sslmode=disable for a server without TLS). For another database on a server PostgresAI already monitors for the org, an admin URL with sslmode=require (or verify-*), each query parameter once, is enough: PostgresAI fills in the password of postgres_ai_mon it keeps, over TLS only (on a server without TLS, pass the postgres_ai_mon URL; if nobody has its password, the user runs in a terminal: pgai mon instances delete the server's other databases, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one, then deploys them again with it).",
31559
+ description: "Put a Postgres database under PostgresAI Cloud monitoring (same as `pgai mon deploy`): prepares the monitoring role (an admin URL creates it; otherwise returns the SQL), provisions the monitoring box, and returns JSON with status (ready | in_progress | deleting | deleted | inactive | action_required | failed: the same words as pgai dblab deploy), health_url (the project's Health Matrix in the console), dashboard_url (Grafana, signing in with PostgresAI) and next (the exact next action). A billed box is provisioned only with yes: true: without it the result is action_required with the price (and requires_payment_method), so show the price to the user first. It does not wait for the box: call it again to see the status. Safe to call again. When PostgresAI can't reach the database the way an IP allowlist refuses (or with ip_first), the box's IP is reserved first and the result is action_required with step allow_ip (ip, cidr, host, port, reserved_until): give the user the cidr and port to allow on the database, then call again with ip_allowed: true. ClickHouse Managed Postgres, RDS and Supabase are detected from the host. Supabase needs no password (PostgresAI prepares the database through the Supabase Management API): the first time, the result is action_required with a consent link in next; give it to the user to open and approve, then call again. Elsewhere the URL must carry its password, and only these query parameters: sslmode, channel_binding, application_name. PGAI_MON_PASSWORD, PGPASSWORD and CLICKHOUSE_KEY_ID + CLICKHOUSE_KEY_SECRET of the server process are not used (pass clickhouse_key), and a TLS failure is not retried in plaintext (say sslmode=disable for a server without TLS). For another database on a server PostgresAI already monitors for the org, an admin URL with sslmode=require (or verify-*), each query parameter once, is enough: PostgresAI fills in the password of postgres_ai_mon it keeps, over TLS only (on a server without TLS, pass the postgres_ai_mon URL; if nobody has its password, the user runs in a terminal: pgai mon instances delete the server's other databases, then pgai mon deploy <admin-url> --reset-password with PGAI_MON_PASSWORD set to a new one, then deploys them again with it).",
31337
31560
  inputSchema: {
31338
31561
  type: "object",
31339
31562
  properties: {
@@ -31347,6 +31570,8 @@ async function startMcpServer(rootOpts, extra) {
31347
31570
  coupon: { type: "string", description: "Stripe promotion code for the organization's monitoring subscription (applies when it is first created)" },
31348
31571
  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" },
31349
31572
  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). Not for Supabase, where PostgresAI creates postgres_ai_mon" },
31573
+ ip_first: { type: "boolean", description: "Reserve the monitoring box's IP and stop before the box (even when PostgresAI can reach the database), so the user can allow it on the database first. The result is action_required with step allow_ip: ip, cidr, host, port, reserved_until" },
31574
+ ip_allowed: { type: "boolean", description: "The database now allows the reserved IP (a previous result's step allow_ip): create the box with it. Give the user the cidr and port to allow first, and call with ip_allowed: true only once they confirm" },
31350
31575
  debug: { type: "boolean", description: "Enable verbose debug logs" }
31351
31576
  },
31352
31577
  required: ["database_url"],
@@ -32249,6 +32474,7 @@ function renderMarkdownForTerminal(md) {
32249
32474
  }
32250
32475
 
32251
32476
  // lib/connect.ts
32477
+ var clickhouseKeyHeld = (d) => d.host_metrics && (d.host_metrics_source === undefined || d.host_metrics_source === "clickhouse");
32252
32478
  function httpStatus2(err) {
32253
32479
  const status = err instanceof Error ? err.status : undefined;
32254
32480
  return typeof status === "number" ? status : undefined;
@@ -32438,6 +32664,7 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
32438
32664
  return {
32439
32665
  ...base,
32440
32666
  status,
32667
+ ...row.egress_ip ? { egress_ip: row.egress_ip } : {},
32441
32668
  ...fresh ? { first_checkup_eta: new Date(Date.now() + FIRST_CHECKUP_DELAY_MS2).toISOString() } : {},
32442
32669
  next: row.health_url || row.dashboard_url ? `Open ${row.health_url || row.dashboard_url}` : `pgai mon instances watch ${row.id}`
32443
32670
  };
@@ -32446,6 +32673,8 @@ function connectStatus2(row, provider = row.provider, fresh = false) {
32446
32673
  return { ...base, status, next: "none" };
32447
32674
  if (status === "failed")
32448
32675
  return { ...base, status, next: `pgai mon instances delete ${row.id} --yes, then pgai mon deploy again` };
32676
+ if (row.status === "ip_reserved" && row.egress_ip)
32677
+ return { ...allowIpResult2(row, provider, row.name, { waitMs: 0 }, ""), ...base, status: "action_required", step: "allow_ip" };
32449
32678
  return { ...base, status, next: `pgai mon instances watch ${row.id}` };
32450
32679
  }
32451
32680
  var ESCAPES2 = /(?:\x1b\[|\x9b)[0-?]*[ -\/]*[@-~]|(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?|\x1b[ -~]?/g;
@@ -32455,12 +32684,19 @@ var terminalText2 = (text) => text.replace(ESCAPES2, "").split(`
32455
32684
  function stepProgress(o) {
32456
32685
  let view;
32457
32686
  let priced = false;
32687
+ let refused = "";
32458
32688
  const progress = (e) => {
32459
- if (e.id)
32689
+ if (e.id && e.event !== "allow_ip")
32460
32690
  o.onId?.(e.id);
32461
32691
  if (o.json)
32462
32692
  return o.writeEvent(e);
32463
- e = { ...e, message: terminalText2(e.message), ...e.state ? { state: terminalText2(e.state) } : {} };
32693
+ e = {
32694
+ ...e,
32695
+ message: terminalText2(e.message),
32696
+ ...e.state ? { state: terminalText2(e.state) } : {},
32697
+ ...e.ip ? { ip: terminalText2(e.ip) } : {},
32698
+ ...e.error ? { error: terminalText2(e.error) } : {}
32699
+ };
32464
32700
  if (!o.tty)
32465
32701
  return o.writeLine(progressText(e));
32466
32702
  if (e.event === "billing") {
@@ -32476,12 +32712,26 @@ function stepProgress(o) {
32476
32712
  view.advance(e.event);
32477
32713
  if (/^(Note|Warning):/.test(e.message))
32478
32714
  view.log(e.message);
32479
- if (e.event === "box" && e.state)
32480
- view.setNote(`box: ${boxWords2(e.state)}`);
32715
+ if (e.event === "box" && e.state) {
32716
+ view.setNote(e.state === "waiting_for_access" && e.ip ? `box: waiting for database access from ${e.ip}` : `box: ${boxWords2(e.state)}`);
32717
+ if (e.state === "waiting_for_access" && e.ip && e.error && e.error !== refused) {
32718
+ refused = e.error;
32719
+ view.log(`The database refused ${e.ip}: ${e.error}. The box keeps trying: allow ${e.ip}/32 on the database.`);
32720
+ }
32721
+ }
32481
32722
  if (e.message === STILL_CREATING2)
32482
32723
  view.setNote(`still creating: PostgresAI is slow to answer (checking for up to ${LOOKUP_MS2 / 60000} min)`);
32483
32724
  };
32484
- return { progress, view: () => view };
32725
+ return { progress, view: () => view, reset: () => {
32726
+ view = undefined;
32727
+ } };
32728
+ }
32729
+ function stepViewEnd(r) {
32730
+ if (r.status === "ready")
32731
+ return "complete";
32732
+ if (r.status === "in_progress" || r.step === "allow_ip" || r.next.startsWith(STILL_IN_PROGRESS2))
32733
+ return "stop";
32734
+ return "fail";
32485
32735
  }
32486
32736
  function resultLines(r) {
32487
32737
  return personLines(r).map(terminalText2);
@@ -32499,6 +32749,7 @@ function personLines(r) {
32499
32749
  ...r.dashboard_url ? [` Grafana: ${r.dashboard_url}`] : [],
32500
32750
  ...r.price ? [` Price: ${r.price}`] : [],
32501
32751
  ...r.cloud ? [` Runs on: ${cloudWord2(r.cloud)}, ${r.location}`] : [],
32752
+ ...r.egress_ip ? [` Connects from: ${r.egress_ip}`] : [],
32502
32753
  ...!r.health_url && !r.dashboard_url && r.next && r.next !== "none" ? [`Next: ${r.next}`] : [],
32503
32754
  ...extra && (r.health_url || r.dashboard_url) ? [`Note: ${extra}`] : []
32504
32755
  ];
@@ -32508,6 +32759,15 @@ function personLines(r) {
32508
32759
  case "deleted":
32509
32760
  return [`Deleting the monitoring of ${who}.${billing ? ` Billing: ${billing}.` : ""}${r.next && r.next !== "none" ? ` ${r.next}` : ""}`];
32510
32761
  default:
32762
+ if (r.step === "allow_ip") {
32763
+ if (r.next.startsWith("Stopped."))
32764
+ return [r.next];
32765
+ return [
32766
+ `Monitoring box IP: ${r.ip}${r.cloud ? ` (${cloudWord2(r.cloud)}, ${r.location})` : ""}${r.reserved_until ? `, held until ${heldUntil2(r.reserved_until)}` : ""}`,
32767
+ r.last_error ? `The box could not connect: ${r.last_error}` : r.precheck_error ? `PostgresAI could not connect to ${r.host}:${r.port} (${r.precheck_error}).` : "The IP was reserved first, as asked.",
32768
+ r.next
32769
+ ];
32770
+ }
32511
32771
  if (r.projects?.length)
32512
32772
  return [r.next, ...supabaseProjectRows(r.projects)];
32513
32773
  return r.choices ? [r.next, ...Object.entries(r.choices).map(([cloud, codes]) => ` --cloud ${cloud} --location ${codes.join("|")}`)] : [r.next];
@@ -32528,6 +32788,12 @@ function boxWords2(state) {
32528
32788
  return "starting";
32529
32789
  if (state === "registered")
32530
32790
  return "installing monitoring";
32791
+ if (state === "waiting_for_access")
32792
+ return "waiting for database access";
32793
+ if (state === "ip_reserving")
32794
+ return "reserving its IP";
32795
+ if (state === "ip_reserved")
32796
+ return "waiting for its IP to be allowed";
32531
32797
  return monitoringStatus(state).replace("_", " ");
32532
32798
  }
32533
32799
  async function billingFor2(q, name, opts, deps, show, ask) {
@@ -32577,6 +32843,9 @@ async function connect2(url, opts, deps) {
32577
32843
  if (project !== undefined && provider !== "supabase") {
32578
32844
  return { status: "action_required", provider, name: url ? databaseName3(url) : "", next: "--supabase-project applies to Supabase only: leave it out, or use --provider supabase" };
32579
32845
  }
32846
+ if ((opts.ipFirst || opts.ipAllowed) && (opts.selfHosted || provider === "supabase")) {
32847
+ return { status: "action_required", provider, name: url ? databaseName3(url) : "", next: `${opts.agent ? "ip_first / ip_allowed apply" : "--ip-first and --ip-allowed apply"} to PostgresAI Cloud monitoring of a database URL only` };
32848
+ }
32580
32849
  if (!url) {
32581
32850
  if (provider !== "supabase")
32582
32851
  return { status: "action_required", provider, name: "", next: "Pass the database URL: pgai mon deploy postgresql://user:password@host:5432/dbname (Supabase: --provider supabase)" };
@@ -32635,12 +32904,24 @@ async function connect2(url, opts, deps) {
32635
32904
  return live.find(byCluster) ?? live.find(byName);
32636
32905
  };
32637
32906
  const rows = opts.selfHosted ? [] : await deps.list();
32638
- const known = new Set(rows.map((d) => d.id));
32907
+ const known = new Map(rows.map((d) => [d.id, d.status]));
32639
32908
  const findMade = (list) => {
32640
- const fresh = list.filter((d) => !known.has(d.id));
32909
+ const fresh = list.filter((d) => !known.has(d.id) || reservedStatus2(known.get(d.id)) && !reservedStatus2(d.status));
32641
32910
  return fresh.find(byCluster) ?? fresh.find(byName);
32642
32911
  };
32643
32912
  let row = findDatabase(rows);
32913
+ let continuing = false;
32914
+ let ownId;
32915
+ if (row && reservedStatus2(row.status)) {
32916
+ if (!opts.ipAllowed) {
32917
+ const asked = await allowIpStep2(row, { provider, name, url, opts, deps, progress });
32918
+ if (asked !== "continue")
32919
+ return asked;
32920
+ }
32921
+ continuing = true;
32922
+ ownId = row.id;
32923
+ row = undefined;
32924
+ }
32644
32925
  const fresh = !row;
32645
32926
  let note = "";
32646
32927
  let billing = {};
@@ -32681,7 +32962,7 @@ async function connect2(url, opts, deps) {
32681
32962
  }
32682
32963
  }
32683
32964
  if (row && opts.resetPassword) {
32684
- return { status: "action_required", provider, name, id: row.id, next: `${name} is already monitored, and its monitoring uses the current password: ${disconnectEach2([deleteRef2(row, rows)])} first` };
32965
+ return { status: "action_required", provider, name, id: row.id, next: `${row.name} is already monitored, and its monitoring uses the current password. Delete it, then run this deploy again with --reset-password: ${disconnectEach2([deleteRef2(row, rows)])}` };
32685
32966
  }
32686
32967
  if (row && key) {
32687
32968
  const found = await findOrg();
@@ -32710,7 +32991,7 @@ async function connect2(url, opts, deps) {
32710
32991
  const unread = (d) => !d.cluster;
32711
32992
  const onServer = (d) => !!d.cluster && serverOf2(d.cluster) === cluster;
32712
32993
  const usesRole = (d) => !["deleting", "deleted", "inactive"].includes(stateOf2(d.status)) && !(d.status === "failed" && !d.registered_at);
32713
- const othersOnServer = (list) => list.filter((d) => usesRole(d) && (unread(d) || onServer(d)));
32994
+ const othersOnServer = (list) => list.filter((d) => d.id !== ownId && usesRole(d) && (unread(d) || onServer(d)));
32714
32995
  const storedPassword = !monitoringUser && rows.some((d) => d.monitoring_password_stored && !/delet/.test(d.status ?? "") && onServer(d)) || undefined;
32715
32996
  const cutOff = (others, list) => {
32716
32997
  const label = (d) => deleteRef2(d, list) === d.id ? `${d.name} (id ${d.id})` : d.name;
@@ -32796,9 +33077,9 @@ async function connect2(url, opts, deps) {
32796
33077
  try {
32797
33078
  if (lockId) {
32798
33079
  const now = await deps.list();
32799
- const same = findDatabase(now);
33080
+ const same = findDatabase(now.filter((d) => d.id !== ownId));
32800
33081
  if (same)
32801
- return { status: "action_required", provider, name, id: same.id, ...billing, next: `${name} is already monitored, and its monitoring uses the current password: ${disconnectEach2([deleteRef2(same, now)])} first` };
33082
+ return { status: "action_required", provider, name, id: same.id, ...billing, next: `${same.name} is already monitored, and its monitoring uses the current password. Delete it, then run this deploy again with --reset-password: ${disconnectEach2([deleteRef2(same, now)])}` };
32802
33083
  const others = othersOnServer(now);
32803
33084
  if (others.length)
32804
33085
  return { ...cutOff(others, now), ...billing };
@@ -32812,6 +33093,16 @@ async function connect2(url, opts, deps) {
32812
33093
  throw new CancelledError2;
32813
33094
  }
32814
33095
  if ("next" in prepared) {
33096
+ if ((continuing || opts.ipAllowed) && /created by someone else meanwhile/.test(prepared.next)) {
33097
+ for (let tries = 0;tries < 10; tries++) {
33098
+ const box = findDatabase(await deps.list());
33099
+ if (!box)
33100
+ break;
33101
+ if (!reservedStatus2(box.status))
33102
+ return follow2(box, { provider, name, fresh, billing, billingUrl, undoRole, note, place, url }, opts, deps, progress);
33103
+ await deps.sleep(2000);
33104
+ }
33105
+ }
32815
33106
  const { resettable, ...refusal } = prepared;
32816
33107
  return { status: "action_required", provider, name, ...billing, ...refusal };
32817
33108
  }
@@ -32824,8 +33115,12 @@ async function connect2(url, opts, deps) {
32824
33115
  return { status: "ready", provider, name, dashboard_url: "http://localhost:3000", host_metrics: !!ch, next: `pgai mon health${note}` };
32825
33116
  }
32826
33117
  progress("provisioning", `Provisioning monitoring for ${name}`);
32827
- created = await deps.create({
32828
- db_url: prepared.monitoringUrl,
33118
+ const monitoringUrl = prepared.monitoringUrl;
33119
+ const request = (ipAllowed) => deps.create({
33120
+ db_url: monitoringUrl,
33121
+ allow_ip_fallback: true,
33122
+ ...opts.ipFirst ? { ip_first: true } : {},
33123
+ ...ipAllowed ? { ip_allowed: true } : {},
32829
33124
  ...provider === "clickhouse" ? { provider } : {},
32830
33125
  ...key && ch ? { clickhouse_org_id: ch.orgId, clickhouse_key_id: key.keyId, clickhouse_key_secret: key.keySecret } : {},
32831
33126
  ...opts.coupon ? { promo_code: opts.coupon } : {},
@@ -32833,7 +33128,38 @@ async function connect2(url, opts, deps) {
32833
33128
  ...opts.name ? { project_name: opts.name } : {},
32834
33129
  ...place ? { cloud: place.cloud, server_location: place.location } : opts.location ? { server_location: opts.location } : {},
32835
33130
  ...vcpus ? { vcpus } : {}
33131
+ });
33132
+ const refused = async (c) => {
33133
+ const row = await waitForIp2(c.id, deps) ?? { id: c.id, name: c.name, status: c.status };
33134
+ const why = [c.error, c.billing_warning].filter(Boolean).join(" ");
33135
+ return { ...c, status: "allow_ip", result: { ...allowIpResult2(row, provider, name, opts, url), next: `${why} Then: ${continueCommand2(opts, url)}` } };
33136
+ };
33137
+ const continued = async () => {
33138
+ const c = await request(true);
33139
+ return reservedStatus2(c.status) && c.error ? refused(c) : c;
33140
+ };
33141
+ created = await request(continuing || !!opts.ipAllowed).then(async (c) => {
33142
+ if (reservedStatus2(c.status))
33143
+ known.set(c.id, c.status);
33144
+ if (reservedStatus2(c.status) && c.error)
33145
+ return refused(c);
33146
+ if (!reservedStatus2(c.status))
33147
+ return c;
33148
+ const reservation = await waitForIp2(c.id, deps);
33149
+ if (!reservation || !reservedStatus2(reservation.status))
33150
+ return { ...c, status: reservation?.status ?? "failed", error: reservation ? undefined : "The IP reservation did not report back in time; see pgai mon instances list." };
33151
+ if (continuing && c.status === "ip_reserving" && reservation.status === "ip_reserved")
33152
+ return continued();
33153
+ const asked = await allowIpStep2(reservation, { provider, name, url, opts, deps, progress });
33154
+ if (asked !== "continue")
33155
+ return { ...c, status: "allow_ip", result: asked };
33156
+ return continued();
32836
33157
  }).catch(async (err) => {
33158
+ if ((continuing || opts.ipAllowed) && err instanceof HttpStatusError && err.status === 409 && /already monitored/.test(err.message)) {
33159
+ const box = findDatabase(await deps.list());
33160
+ if (box && !reservedStatus2(box.status))
33161
+ return { id: box.id, name: box.name, status: box.status ?? "launch_requested" };
33162
+ }
32837
33163
  if (err instanceof HttpStatusError && (err.status < 500 || err.sqlstate))
32838
33164
  await undo(prepared);
32839
33165
  else
@@ -32874,6 +33200,12 @@ async function connect2(url, opts, deps) {
32874
33200
  const gone = `PostgresAI no longer keeps the password of ${DEFAULT_MONITORING_USER} for this server`;
32875
33201
  return { status: "action_required", provider, name, ...billing, next: opts.agent ? `${gone}: pass its URL as database_url, or run pgai mon deploy <admin-url> --reset-password in a terminal` : `${gone}: re-run with --reset-password (anything else that logs in as ${DEFAULT_MONITORING_USER} then needs the new one), or set PGAI_MON_PASSWORD to its password` };
32876
33202
  }
33203
+ if (created.status === "allow_ip" && created.result) {
33204
+ const now = findDatabase(await deps.list().catch(() => []));
33205
+ if (!now || reservedStatus2(now.status))
33206
+ await undo(prepared);
33207
+ return { ...created.result, ...billing };
33208
+ }
32877
33209
  if (created.status === "failed") {
32878
33210
  await undo(prepared);
32879
33211
  return { status: "failed", provider, name, id: created.id, next: `${created.error} Re-run pgai mon deploy later.` };
@@ -32888,7 +33220,73 @@ async function connect2(url, opts, deps) {
32888
33220
  const made = prepared;
32889
33221
  undoRole = () => undo(made);
32890
33222
  }
32891
- return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place }, opts, deps, progress);
33223
+ return follow2(row, { provider, name, fresh, billing, billingUrl, undoRole, note, place, url }, opts, deps, progress);
33224
+ }
33225
+ function listedDatabase(d) {
33226
+ return { ...d, status: stateOf2(d.status), ...d.status === "ip_reserved" ? { step: "allow_ip" } : {} };
33227
+ }
33228
+ var reservedStatus2 = (status) => status === "ip_reserving" || status === "ip_reserved";
33229
+ var IP_POLL_MS2 = 3000;
33230
+ var IP_WAIT_MS2 = 120000;
33231
+ async function waitForIp2(id, deps) {
33232
+ for (const deadline = deps.now() + IP_WAIT_MS2;; ) {
33233
+ const row = (await deps.list().catch(() => [])).find((d) => d.id === id);
33234
+ if (row && row.status !== "ip_reserving")
33235
+ return row;
33236
+ if (deps.now() >= deadline)
33237
+ return;
33238
+ await deps.sleep(IP_POLL_MS2);
33239
+ }
33240
+ }
33241
+ var continueCommand2 = (opts, url) => opts.agent ? "call deploy_monitoring again with ip_allowed: true" : `pgai mon deploy ${url ? quoteArg2(maskConnectionString(url)) : "<database URL>"} --yes --ip-allowed`;
33242
+ var quoteArg2 = (s) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
33243
+ var heldUntil2 = (iso) => iso ? iso.replace(/T(\d\d:\d\d).*$/, " $1 UTC") : "";
33244
+ function allowIpResult2(row, provider, name, opts, url, stopped = false) {
33245
+ const [host, port] = row.cluster ? [row.cluster.replace(/:\d+$/, ""), Number(row.cluster.match(/:(\d+)$/)?.[1] ?? 5432)] : [undefined, undefined];
33246
+ const ip = row.egress_ip ?? undefined;
33247
+ const cidr = ip ? `${ip}/32` : undefined;
33248
+ const allow = `Allow inbound TCP ${port ?? 5432} from ${cidr} on ${host ?? "the database"}`;
33249
+ return {
33250
+ status: "action_required",
33251
+ step: "allow_ip",
33252
+ provider,
33253
+ name,
33254
+ id: row.id,
33255
+ ...row.cloud ? { cloud: row.cloud, location: row.location ?? undefined } : {},
33256
+ ip,
33257
+ cidr,
33258
+ host,
33259
+ port,
33260
+ ...row.reserved_until ? { reserved_until: row.reserved_until } : {},
33261
+ ...row.last_error ? { last_error: row.last_error } : {},
33262
+ ...row.precheck_error ? { precheck_error: row.precheck_error } : {},
33263
+ egress_ip: ip,
33264
+ next: stopped ? `Stopped. ${ip} stays reserved until ${heldUntil2(row.reserved_until)}. ${allow}, then: ${continueCommand2(opts, url)}` : `${allow}, then ${opts.agent ? continueCommand2(opts, url) : `re-run with --yes --ip-allowed: ${continueCommand2(opts, url)}`}`
33265
+ };
33266
+ }
33267
+ async function allowIpStep2(row, c) {
33268
+ if (row.status === "ip_reserving")
33269
+ row = await waitForIp2(row.id, c.deps) ?? row;
33270
+ if (!reservedStatus2(row.status) || !row.egress_ip) {
33271
+ return {
33272
+ status: "action_required",
33273
+ provider: c.provider,
33274
+ name: c.name,
33275
+ id: row.id,
33276
+ next: row.status === "ip_reserving" ? `The IP is still being reserved: re-run in a minute, or see pgai mon instances list` : `See pgai mon instances list (${row.status ?? "unknown"})`
33277
+ };
33278
+ }
33279
+ const r = allowIpResult2(row, c.provider, c.name, c.opts, c.url);
33280
+ c.progress("allow_ip", `Reserved IP for the monitoring box: ${r.ip}`, { ip: r.ip, cidr: r.cidr, host: r.host, port: r.port, reserved_until: r.reserved_until, id: row.id });
33281
+ if (!c.deps.allowIp)
33282
+ return r;
33283
+ const why = row.last_error ? `The box could not connect from ${r.ip}: ${row.last_error}` : c.opts.ipFirst ? "You asked for the IP first (--ip-first)." : !row.precheck_error ? "The IP was reserved first, as asked." : `PostgresAI could not connect to ${r.host}:${r.port} (${row.precheck_error}). The database likely allows only listed IPs.`;
33284
+ const answer = await c.deps.allowIp([
33285
+ `Monitoring box IP: ${r.ip}${row.cloud ? ` (${cloudWord2(row.cloud)}, ${row.location})` : ""}`,
33286
+ why,
33287
+ `Allow inbound TCP ${r.port} from ${r.cidr} on ${r.host}, then continue. The IP is held until ${heldUntil2(row.reserved_until)} and stays this box's IP.`
33288
+ ]);
33289
+ return answer === "continue" ? "continue" : allowIpResult2(row, c.provider, c.name, c.opts, c.url, true);
32892
33290
  }
32893
33291
  async function placeBox2(deps, opts, where, progress) {
32894
33292
  if (!deps.deployOptions)
@@ -33296,6 +33694,7 @@ async function lookForBox2(findMade, opts, deps, started) {
33296
33694
  }
33297
33695
  async function follow2(row, f, opts, deps, progress) {
33298
33696
  const { provider, name, fresh, billingUrl, undoRole, note } = f;
33697
+ const url = (_) => f.url ?? name;
33299
33698
  const billing = { ...f.billing, ...f.place };
33300
33699
  let shown;
33301
33700
  for (const deadline = deps.now() + opts.waitMs;; ) {
@@ -33311,10 +33710,16 @@ async function follow2(row, f, opts, deps, progress) {
33311
33710
  next: chargeFailed2(row.billing_error, "re-run", billingUrl, opts.agent ? "coupon" : "--coupon")
33312
33711
  };
33313
33712
  }
33713
+ if (row.status === "ip_reserved") {
33714
+ if (undoRole)
33715
+ await undoRole();
33716
+ return { ...allowIpResult2(row, provider, name, opts, url(row)), ...billing };
33717
+ }
33314
33718
  const result = connectStatus2(row, provider, fresh);
33315
33719
  const state = boxState2(row);
33316
- if (state !== shown && (shown !== undefined || result.status === "in_progress"))
33317
- progress("box", `Monitoring box: ${boxWords2(state)}`, { state, id: row.id });
33720
+ if (state !== shown && (shown !== undefined || result.status === "in_progress")) {
33721
+ progress("box", state === "waiting_for_access" && row.egress_ip ? `Monitoring box: waiting for database access from ${row.egress_ip}${row.last_error ? ` (${row.last_error})` : ""}` : `Monitoring box: ${boxWords2(state)}`, { state, id: row.id, ...state === "waiting_for_access" && row.egress_ip ? { ip: row.egress_ip, ...row.last_error ? { error: row.last_error } : {} } : {} });
33722
+ }
33318
33723
  shown = state;
33319
33724
  if (result.status !== "in_progress" || deps.now() >= deadline) {
33320
33725
  const final = deps.links ? connectStatus2(await deps.links(row), provider, fresh) : result;
@@ -33534,10 +33939,7 @@ async function prepareDatabase2(url, provider, opts = {}) {
33534
33939
  }
33535
33940
  const plan = await buildInitPlan({ database: me.db, monitoringUser: role, monitoringPassword: "<password>", includeOptionalPermissions: true, provider: pgProvider, keepExistingPassword: true });
33536
33941
  return {
33537
- sql: plan.steps.map((s) => `-- ${s.name}${s.optional ? " (optional: an error in this part can be ignored)" : ""}
33538
- ${redactPasswordsInSql(s.sql)}`).join(`
33539
-
33540
- `),
33942
+ sql: renderInitPlanSql(plan),
33541
33943
  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`
33542
33944
  };
33543
33945
  } finally {
@@ -33630,14 +34032,43 @@ function platformDeps2(p) {
33630
34032
  orgAlias = projects = undefined;
33631
34033
  return;
33632
34034
  });
33633
- const { dashboard_url, host_metrics, ...rest } = row;
33634
- return { ...rest, ...health_url ? { health_url } : {}, dashboard_url: grafanaOAuthUrl2(dashboard_url), host_metrics };
34035
+ const { dashboard_url, host_metrics, host_metrics_source, ...rest } = row;
34036
+ return {
34037
+ ...rest,
34038
+ ...health_url ? { health_url } : {},
34039
+ dashboard_url: grafanaOAuthUrl2(dashboard_url),
34040
+ host_metrics,
34041
+ ...host_metrics_source !== undefined ? { host_metrics_source } : {}
34042
+ };
33635
34043
  };
33636
34044
  return {
33637
34045
  verifyTls: verifyCollectorTls,
33638
34046
  list: () => rpc("cloud_monitoring_list"),
33639
34047
  links: withLinks,
33640
- create: (body) => rpc("cloud_monitoring_connect", body, p.agent ? AGENT_CONNECT_TIMEOUT_MS2 : CONNECT_TIMEOUT_MS2),
34048
+ create: async (body) => {
34049
+ const { allow_ip_fallback: _fallback, ip_first, ip_allowed, ...older } = body;
34050
+ const asked = !!(ip_first || ip_allowed);
34051
+ const connectMs = p.agent ? AGENT_CONNECT_TIMEOUT_MS2 : CONNECT_TIMEOUT_MS2;
34052
+ const connectTimeout = { timeoutMs: connectMs, timeoutCeilingMs: connectMs };
34053
+ try {
34054
+ return await callRpc({
34055
+ apiKey: p.apiKey,
34056
+ apiBaseUrl: p.apiBaseUrl,
34057
+ fn: "cloud_monitoring_connect",
34058
+ body,
34059
+ operation: "cloud monitoring connect",
34060
+ debug: p.debug,
34061
+ orgScope: p.orgScope,
34062
+ ...connectTimeout,
34063
+ ...asked ? {} : { fallbackBody: older }
34064
+ });
34065
+ } catch (err) {
34066
+ if (asked && err instanceof HttpStatusError && err.status === 404 && /cloud_monitoring_connect/.test(err.message)) {
34067
+ throw new Error("This PostgresAI platform does not support --ip-first or --ip-allowed yet: deploy without them");
34068
+ }
34069
+ throw err;
34070
+ }
34071
+ },
33641
34072
  disconnect: (id) => rpc("cloud_monitoring_disconnect", { instance_id: id }),
33642
34073
  setVcpus: (id, vcpus) => rpc("cloud_monitoring_set_vcpus", { instance_id: id, vcpus }),
33643
34074
  resetLock: (server) => rpc("cloud_monitoring_reset_lock", { server }),
@@ -35513,6 +35944,8 @@ function monitoringStatus2(raw) {
35513
35944
  return "inactive";
35514
35945
  if (/fail|error/.test(raw ?? ""))
35515
35946
  return "failed";
35947
+ if (raw === "ip_reserved")
35948
+ return "action_required";
35516
35949
  return "in_progress";
35517
35950
  }
35518
35951
  function databaseUrlArg2(positional, dbUrl, command) {
@@ -36509,6 +36942,42 @@ function safeDoDelimiter2(...values) {
36509
36942
  function redactPasswordsInSql2(sql) {
36510
36943
  return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
36511
36944
  }
36945
+ function renderInitPlanSql2(plan) {
36946
+ const lines = [
36947
+ "-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.",
36948
+ "begin;"
36949
+ ];
36950
+ for (const step of plan.steps) {
36951
+ const sql = redactPasswordsInSql2(step.sql);
36952
+ lines.push(`
36953
+ -- ${step.name}${step.optional ? " (optional)" : ""}`);
36954
+ if (!step.optional) {
36955
+ lines.push(sql);
36956
+ continue;
36957
+ }
36958
+ const delimiter = (base) => {
36959
+ let i = 0;
36960
+ while (sql.includes(`$${base}_${i}$`))
36961
+ i++;
36962
+ return `$${base}_${i}$`;
36963
+ };
36964
+ const outer = delimiter("pgai_optional_outer");
36965
+ const inner = delimiter("pgai_optional_sql");
36966
+ lines.push(`do ${outer}
36967
+ begin
36968
+ begin
36969
+ execute ${inner}
36970
+ ${sql}
36971
+ ${inner};
36972
+ exception when others then
36973
+ raise warning 'optional SQL step ${step.name} skipped: %', sqlerrm;
36974
+ end;
36975
+ end ${outer};`);
36976
+ }
36977
+ lines.push("commit;");
36978
+ return lines.join(`
36979
+ `);
36980
+ }
36512
36981
  function maskConnectionString2(dbUrl) {
36513
36982
  let masked = dbUrl;
36514
36983
  const head = dbUrl.match(/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^:@\/?#]*):([\s\S]*)$/i);
@@ -36759,7 +37228,7 @@ async function buildInitPlan2(params) {
36759
37228
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
36760
37229
  begin
36761
37230
  create user ${qRole} with password ${qPwVerifier};
36762
- exception when duplicate_object then
37231
+ exception when duplicate_object or unique_violation then
36763
37232
  null;
36764
37233
  end;
36765
37234
  end if;${params.keepExistingPassword ? "" : `
@@ -36812,9 +37281,21 @@ async function applyInitPlan2(params) {
36812
37281
  throw e;
36813
37282
  }
36814
37283
  };
37284
+ const concurrent = (e) => /tuple concurrently (updated|deleted)/.test(e instanceof Error ? e.message : String(e));
37285
+ const executeRetried = async (step) => {
37286
+ for (let attempt = 1;; attempt++) {
37287
+ try {
37288
+ return await executeStep(step);
37289
+ } catch (e) {
37290
+ if (attempt >= 3 || !concurrent(e))
37291
+ throw e;
37292
+ await new Promise((r) => setTimeout(r, 200 * attempt));
37293
+ }
37294
+ }
37295
+ };
36815
37296
  for (const step of params.plan.steps.filter((s) => !s.optional)) {
36816
37297
  try {
36817
- await executeStep(step);
37298
+ await executeRetried(step);
36818
37299
  applied.push(step.name);
36819
37300
  } catch (e) {
36820
37301
  const msg = e instanceof Error ? e.message : String(e);
@@ -38124,6 +38605,32 @@ function raiseConnectAttemptTimeout(execArgv = process.execArgv, nodeOptions = p
38124
38605
  return nodeNet.getDefaultAutoSelectFamilyAttemptTimeout();
38125
38606
  }
38126
38607
 
38608
+ // lib/prepare-error.ts
38609
+ function terminalDiagnosticLine(value) {
38610
+ return terminalText(value).replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/[\u202a-\u202e\u2066-\u2069]/g, "");
38611
+ }
38612
+ function prepareDbPrivilegeAdvice(code, failedStep, message, supabase) {
38613
+ if (code !== "42501")
38614
+ return [];
38615
+ if (failedStep === "03.permissions" && message.includes("postgres_ai schema ")) {
38616
+ return ["Fix: ask a DBA to inspect the named schema ownership, grants, or object before retrying"];
38617
+ }
38618
+ const lines = [];
38619
+ if (failedStep === "01.role") {
38620
+ lines.push("Context: role creation/update requires CREATEROLE or superuser");
38621
+ } else if (failedStep === "03.permissions") {
38622
+ lines.push("Context: grants/view/search_path require sufficient GRANT/DDL privileges");
38623
+ }
38624
+ if (supabase) {
38625
+ lines.push("Fix: ensure your Supabase access token has sufficient permissions");
38626
+ } else {
38627
+ lines.push("Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
38628
+ lines.push("Fix: on managed Postgres, use the provider's admin/master user");
38629
+ }
38630
+ lines.push("Tip: run with --print-sql to review the exact SQL plan");
38631
+ return lines;
38632
+ }
38633
+
38127
38634
  // lib/feedback.ts
38128
38635
  var FEEDBACK_URL = "https://gitlab.com/postgres-ai/postgresai/-/work_items/300";
38129
38636
  var FEEDBACK_SUPPRESS_ENV = "PGAI_NO_FEEDBACK_TIP";
@@ -45549,7 +46056,6 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45549
46056
  conn = process.env.PGAI_DB_URL || undefined;
45550
46057
  }
45551
46058
  const shouldPrintSql = !!opts.printSql;
45552
- const redactPasswords = (sql) => redactPasswordsInSql2(sql);
45553
46059
  const { provider, detected } = resolveProvider(opts.provider, conn ?? opts.dbUrl ?? opts.host ?? process.env.PGHOST);
45554
46060
  const note = opts.json ? console.error : console.log;
45555
46061
  if (detected)
@@ -45581,11 +46087,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45581
46087
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
45582
46088
  console.log(`-- provider: ${provider}`);
45583
46089
  console.log(`-- optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
45584
- for (const step of plan.steps) {
45585
- console.log(`
45586
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
45587
- console.log(redactPasswords(step.sql));
45588
- }
46090
+ console.log(renderInitPlanSql2(plan));
45589
46091
  console.log(`
45590
46092
  --- end SQL plan ---
45591
46093
  `);
@@ -45747,11 +46249,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45747
46249
  if (shouldPrintSql) {
45748
46250
  console.log(`
45749
46251
  --- SQL plan ---`);
45750
- for (const step of effectivePlan.steps) {
45751
- console.log(`
45752
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
45753
- console.log(redactPasswords(step.sql));
45754
- }
46252
+ console.log(renderInitPlanSql2(effectivePlan));
45755
46253
  console.log(`
45756
46254
  --- end SQL plan ---
45757
46255
  `);
@@ -45842,24 +46340,18 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
45842
46340
  console.error(` Code: ${errAny.code}`);
45843
46341
  }
45844
46342
  if (typeof errAny.detail === "string" && errAny.detail) {
45845
- console.error(` Detail: ${errAny.detail}`);
46343
+ console.error(` Detail: ${terminalDiagnosticLine(errAny.detail)}`);
45846
46344
  }
45847
46345
  if (typeof errAny.hint === "string" && errAny.hint) {
45848
- console.error(` Hint: ${errAny.hint}`);
46346
+ console.error(` Hint: ${terminalDiagnosticLine(errAny.hint)}`);
45849
46347
  }
45850
46348
  if (typeof errAny.httpStatus === "number") {
45851
46349
  console.error(` HTTP Status: ${errAny.httpStatus}`);
45852
46350
  }
45853
46351
  }
45854
46352
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
45855
- if (errAny.code === "42501") {
45856
- if (failedStep === "01.role") {
45857
- console.error(" Context: role creation/update requires CREATEROLE or superuser");
45858
- } else if (failedStep === "03.permissions") {
45859
- console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
45860
- }
45861
- console.error(" Fix: ensure your Supabase access token has sufficient permissions");
45862
- console.error(" Tip: run with --print-sql to review the exact SQL plan");
46353
+ for (const line of prepareDbPrivilegeAdvice(errAny.code, failedStep, message, true)) {
46354
+ console.error(` ${line}`);
45863
46355
  }
45864
46356
  if (errAny.code === "42P06" || message.includes("already exists") && failedStep === "03.permissions") {
45865
46357
  console.error(" Hint: postgres_ai schema or objects already exist from a previous setup.");
@@ -46045,11 +46537,7 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46045
46537
  if (shouldPrintSql) {
46046
46538
  console.log(`
46047
46539
  --- SQL plan ---`);
46048
- for (const step of effectivePlan.steps) {
46049
- console.log(`
46050
- -- ${step.name}${step.optional ? " (optional)" : ""}`);
46051
- console.log(redactPasswords(step.sql));
46052
- }
46540
+ console.log(renderInitPlanSql2(effectivePlan));
46053
46541
  console.log(`
46054
46542
  --- end SQL plan ---
46055
46543
  `);
@@ -46134,24 +46622,17 @@ program2.command("prepare-db [conn]").description("prepare database for monitori
46134
46622
  console.error(` Code: ${errAny.code}`);
46135
46623
  }
46136
46624
  if (typeof errAny.detail === "string" && errAny.detail) {
46137
- console.error(` Detail: ${errAny.detail}`);
46625
+ console.error(` Detail: ${terminalDiagnosticLine(errAny.detail)}`);
46138
46626
  }
46139
46627
  if (typeof errAny.hint === "string" && errAny.hint) {
46140
- console.error(` Hint: ${errAny.hint}`);
46628
+ console.error(` Hint: ${terminalDiagnosticLine(errAny.hint)}`);
46141
46629
  }
46142
46630
  }
46143
46631
  for (const w of legacyWarnings)
46144
46632
  console.error(`\u26A0 ${w}`);
46145
46633
  if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
46146
- if (errAny.code === "42501") {
46147
- if (failedStep === "01.role") {
46148
- console.error(" Context: role creation/update requires CREATEROLE or superuser");
46149
- } else if (failedStep === "03.permissions") {
46150
- console.error(" Context: grants/view/search_path require sufficient GRANT/DDL privileges");
46151
- }
46152
- console.error(" Fix: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges)");
46153
- console.error(" Fix: on managed Postgres, use the provider's admin/master user");
46154
- console.error(" Tip: run with --print-sql to review the exact SQL plan");
46634
+ for (const line of prepareDbPrivilegeAdvice(errAny.code, failedStep, message, false)) {
46635
+ console.error(` ${line}`);
46155
46636
  }
46156
46637
  if (errAny.code === "42P06" || message.includes("already exists") && failedStep === "03.permissions") {
46157
46638
  console.error(" Hint: postgres_ai schema or objects already exist from a previous setup.");
@@ -46248,11 +46729,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46248
46729
  console.log(`-- monitoring user: ${opts.monitoringUser}`);
46249
46730
  console.log(`-- provider: ${provider}`);
46250
46731
  console.log(`-- drop role: ${dropRole}`);
46732
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46733
+ console.log("begin;");
46251
46734
  for (const step of plan.steps) {
46252
46735
  console.log(`
46253
46736
  -- ${step.name}`);
46254
46737
  console.log(step.sql);
46255
46738
  }
46739
+ console.log("commit;");
46256
46740
  console.log(`
46257
46741
  --- end SQL plan ---
46258
46742
  `);
@@ -46318,11 +46802,14 @@ program2.command("unprepare-db [conn]").description("remove monitoring setup: dr
46318
46802
  if (shouldPrintSql) {
46319
46803
  console.log(`
46320
46804
  --- SQL plan ---`);
46805
+ console.log("-- Run the complete plan in one session. For psql, use -v ON_ERROR_STOP=1.");
46806
+ console.log("begin;");
46321
46807
  for (const step of plan.steps) {
46322
46808
  console.log(`
46323
46809
  -- ${step.name}`);
46324
46810
  console.log(step.sql);
46325
46811
  }
46812
+ console.log("commit;");
46326
46813
  console.log(`
46327
46814
  --- end SQL plan ---
46328
46815
  `);
@@ -47480,6 +47967,27 @@ ${reply}`);
47480
47967
  closeReadline();
47481
47968
  }
47482
47969
  },
47970
+ ...interactive(opts.json) ? { allowIp: async (lines) => {
47971
+ steps.view()?.stop();
47972
+ console.error("");
47973
+ for (const line of lines)
47974
+ console.error(terminalText2(line));
47975
+ process.exitCode = 130;
47976
+ try {
47977
+ for (let tries = 0;tries < 3; tries++) {
47978
+ const answer = (await question("[Enter] continue / [s]top: ")).trim().toLowerCase();
47979
+ if (answer === "" || answer === "c" || answer === "continue")
47980
+ return "continue";
47981
+ if (answer === "s" || answer === "stop")
47982
+ return "stop";
47983
+ }
47984
+ return "stop";
47985
+ } finally {
47986
+ process.exitCode = undefined;
47987
+ closeReadline();
47988
+ steps.reset();
47989
+ }
47990
+ } } : {},
47483
47991
  ...interactive(opts.json) ? { chooseSupabaseProject: async (projects, org) => {
47484
47992
  const selectable = projects.filter((x) => x.selectable);
47485
47993
  console.error(terminalText2(`
@@ -47551,9 +48059,10 @@ Projects in the Supabase organization "${org}":`));
47551
48059
  view.setNote("stopped watching");
47552
48060
  else if (looking)
47553
48061
  view.setNote("");
47554
- if (result.status === "ready")
48062
+ const end = stepViewEnd(result);
48063
+ if (end === "complete")
47555
48064
  view.complete();
47556
- else if (result.status !== "in_progress" && !result.next.startsWith(STILL_IN_PROGRESS2))
48065
+ else if (end === "fail")
47557
48066
  view.fail();
47558
48067
  view.stop();
47559
48068
  }
@@ -47568,7 +48077,7 @@ Projects in the Supabase organization "${org}":`));
47568
48077
  }
47569
48078
  }
47570
48079
  var mon = program2.command("mon").description("monitoring services management");
47571
- sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)", "the box's region on its cloud (default: the database's region when that cloud has it; see below)", "where the monitoring box runs: aws or hetzner (default: the database's cloud, else aws)").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; Supabase: from the project's compute size)").option("--supabase-project <name|project-id>", "the Supabase project to monitor (its exact name, or its project ID), instead of a URL; implies --provider supabase").addHelpText("after", [
48080
+ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (default: host[:port]/database)", "the box's region on its cloud (default: the database's region when that cloud has it; see below)", "where the monitoring box runs: aws or hetzner (default: the database's cloud, else aws)").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; Supabase: from the project's compute size)").option("--supabase-project <name|project-id>", "the Supabase project to monitor (its exact name, or its project ID), instead of a URL; implies --provider supabase").option("--ip-first", "reserve the monitoring box's IP and stop before the box: the IP is kept for a week, so you can allow it on the database and continue the deploy afterwards with --ip-allowed (PostgresAI Cloud only)").option("--ip-allowed", "the database now allows the reserved IP: create the box with it").addHelpText("after", [
47572
48081
  "",
47573
48082
  "Steps (each skipped when already done; safe to re-run): sign in, prepare the database",
47574
48083
  "(an admin URL creates the postgres_ai_mon role; otherwise the SQL is printed), provision",
@@ -47587,10 +48096,14 @@ sharedDeployOptions2(withOrgOptions(mon.command("deploy")), 20, "instance name (
47587
48096
  'place, the price and the choices ("choices" in the JSON result): re-run with --yes, and with',
47588
48097
  "--cloud/--location to pick another place.",
47589
48098
  "",
47590
- "Network: the database must be reachable from this machine and from PostgresAI. Before provisioning,",
47591
- "PostgresAI tests the connection from an unpublished address, so the port must accept connections",
47592
- "from the internet; after it, the monitoring box connects from the IP shown on its Console page.",
47593
- "Behind an IP allowlist, use AWS PrivateLink (RDS) or --self-hosted.",
48099
+ "Network: the database must be reachable from this machine. The monitoring box connects from its",
48100
+ "own static IP, shown before the box is created when PostgresAI can't reach the database the way",
48101
+ "an IP allowlist refuses (timeout, refused, no pg_hba.conf entry), or with --ip-first: deploy then",
48102
+ 'stops at the IP ("step":"allow_ip" with ip, cidr, host, port, reserved_until; exit 3 when not',
48103
+ "at a terminal). Allow it on the database, then re-run with --ip-allowed (at a terminal: Enter).",
48104
+ "The IP is held 7 days and stays the box's for its life. If the box still can't connect, it waits",
48105
+ "up to 90 minutes, then is removed and the IP kept: allow it and re-run with --ip-allowed.",
48106
+ "RDS can also use AWS PrivateLink (no public IP), or monitor with --self-hosted.",
47594
48107
  "",
47595
48108
  "Billing is per Postgres cluster observed: another database in a cluster the organization already",
47596
48109
  'monitors is included. Once the URL is checked, deploy shows the price (or "free (N of M free slots)"). A billed',
@@ -47673,7 +48186,7 @@ var monPollMs = () => {
47673
48186
  var monInstances = mon.command("instances").description("monitoring instances in PostgresAI Cloud (pgai mon deploy)");
47674
48187
  withOrgOptions(monInstances.command("list")).description("list the organization's monitoring instances").option("--json", "JSON output").option("--debug", "print HTTP requests (secrets masked)").action(async (opts) => {
47675
48188
  try {
47676
- printResult((await linkedDatabases(opts)).map((d) => ({ ...d, status: stateOf2(d.status) })), opts.json);
48189
+ printResult((await linkedDatabases(opts)).map(listedDatabase), opts.json);
47677
48190
  } catch (err) {
47678
48191
  failCloud(err, opts.json);
47679
48192
  }
@@ -47713,7 +48226,7 @@ withOrgOptions(monInstances.command("delete <id-or-name>")).description("stop mo
47713
48226
  name: row.name,
47714
48227
  id: row.id,
47715
48228
  ...billing ? { billing } : {},
47716
- next: row.host_metrics ? "Delete the ClickHouse Cloud API key you gave us" : "none"
48229
+ next: clickhouseKeyHeld(row) ? "Delete the ClickHouse Cloud API key you gave us" : "none"
47717
48230
  }, opts.json);
47718
48231
  } catch (err) {
47719
48232
  failCloud(err, opts.json);